【CodeForces 1272E --- Nearest Opposite Parity】

【CodeForces 1272E --- Nearest Opposite Parity】

题目来源:点击进入【CodeForces 1272E — Nearest Opposite Parity】

Description

You are given an array a consisting of n integers. In one move, you can jump from the position i to the position i−ai (if 1≤i−ai) or to the position i+ai (if i+ai≤n).

For each position i from 1 to n you want to know the minimum the number of moves required to reach any position j such that aj has the opposite parity from ai (i.e. if ai is odd then aj has to be even and vice versa).

Input

The first line of the input contains one integer n (1≤n≤2⋅105) — the number of elements in a.

The second line of the input contains n integers a1,a2,…,an (1≤ai≤n), where ai is the i-th element of a.

Output

Print n integers d1,d2,…,dn, where di is the minimum the number of moves required to reach any position j such that aj has the opposite parity from ai (i.e. if ai is odd then aj has to be even and vice versa) or -1 if it is impossible to reach such a position.

Sample Input

10
4 5 7 6 7 5 4 4 6 4

Sample Output

1 1 1 2 -1 1 1 3 1 1

AC代码:

#include <bits/stdc++.h>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
const int MAXN = 2e5+5;
int arr[MAXN],ans[MAXN];
vector<int> v[MAXN];

int main()
{
    SIS;
    int n;
    memset(ans,-1,sizeof(ans));
    cin >> n;
    for(int i=0;i<n;i++) cin >> arr[i];
    queue<int> q;
    for(int i=0;i<n;i++)
    {
        if(i-arr[i]>=0)
        {
            v[i-arr[i]].emplace_back(i);
            if((arr[i]&1)^(arr[i-arr[i]]&1)) ans[i]=1;
        }
        if(i+arr[i]<n)
        {
            v[i+arr[i]].emplace_back(i);
            if((arr[i]&1)^(arr[i+arr[i]]&1)) ans[i]=1;
        }
        if(ans[i]==1) q.push(i);
    }
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(auto to:v[x])
        {
            if(ans[to]==-1 && (arr[x]&1)==(arr[to]&1))
            {
                ans[to]=ans[x]+1;
                q.push(to);
            }
        }
    }
    for(int i=0;i<n;i++)
        cout << ans[i] << (i==n-1?'\n':' ');
    return 0;
}
发布了361 篇原创文章 · 获赞 127 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41879343/article/details/103529384
今日推荐