본문 바로가기

AtCoder/ABC

166E This Message Will Self-Destruct in 5s

https://atcoder.jp/contests/abc166/tasks/abc166_e

 

E - This Message Will Self-Destruct in 5s

AtCoder is a programming contest site for anyone from beginners to experts. We hold weekly programming contests online.

atcoder.jp

두개의 인덱스의 차이와 각 인덱스에 해당하는 키의 합이 같은 짝의 갯수를 찾는 문제이다.

다시 말해서 j - i = h[j] + h[i] for i < j 인 짝이 몇개인지 찾아야 한다.

이 식을 바꿔보면 i + h[i] = j - h[j]가 된다.

1부터 n까지 h를 입력받을때마다 배열 a에 i + h[i]값을 저장하면서, 동시에 맵 m에 i - h[i]값이 나올때마다 1 더해준다.

다시 1부터 n까지 for문을 돌면서 ans +=  m[a[i]] 해주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
 
int n, a[200001];
map<intint> m;
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> n;
    for(int i = 1; i <= n; i++) {
        int h;
        cin >> h;
        a[i] = i - h;
        m[i + h]++;
    }
 
    long long ans = 0;
    for(int i = 1; i <= n; i++)
        ans += m[a[i]];
 
    cout << ans << '\n';
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

'AtCoder > ABC' 카테고리의 다른 글

166F Three Variables Game  (0) 2020.05.04