0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今更考えるABC過去問 ~ABC395 C問題~

Posted at

問題

解答案

#include <bits/stdc++.h>
using namespace std;

int main() {
    int N;
    cin >> N;

    vector<int> B(1000009, -1);
    int A;
    int ans = N + 1;
    
    for (int i=1; i<=N; i++) {
        cin >> A;
        if (B[A] != -1) {
            ans = min(ans, i - B[A] + 1);
        }
        B[A] = i;
    }

    if (ans == N + 1) cout << -1 << endl;
    else cout << ans << endl;
}

ある値が出現した位置を配列に記憶し、再び現れたときに位置の差分を取ることで距離が求められる。その最小値が答えとなる。記憶する位置は直前のものだけで良い。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?