传送门:CodeForces-1272E
思路分析
设两个超级源点A和B
将所有奇数与A连一条有向边,所有偶数与B连一条有向边,$i$和$i+a[i]$,$i-a[i]$连一条有向边
那么题意可以转化为每个奇数点到达B的最短距离以及每个偶数点到达A的最短距离
直接求显然不行的,所以可以建立反向边,跑两次最短路,分别以A,B为起点,就可以得到各个点到A和B的最短距离了
样例输入
10
4 5 7 6 7 5 4 4 6 4
样例输出
1 1 1 2 -1 1 1 3 1 1
AC代码
#include <functional>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <string>
#include <cstdio>
#include <chrono>
#include <random>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N=2e5+10;
int n;
int dis[N],a[N],ans[N],vis[N];
vector<int>e[N];
void spfa(int s){
mem(dis,INF);
mem(vis,0);
dis[s]=0;
queue<int>q;
q.push(s);
while(!q.empty()){
int u=q.front();
q.pop();
vis[u]=0;
for(auto v:e[u]){
if(dis[v]>dis[u]+1 && !vis[v]){
q.push(v);
vis[v]=1;
dis[v]=dis[u]+1;
}
}
}
}
int main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
read(n);
for(int i=1;i<=n;i++) {
read(a[i]);
if(i-a[i]>=1) e[i-a[i]].push_back(i);
if(i+a[i]<=n) e[i+a[i]].push_back(i);
}
for(int i=1;i<=n;i++) {
if(a[i]&1) e[0].push_back(i);
else e[n+1].push_back(i);
}
spfa(0);
for(int i=1;i<=n;i++) if(a[i]%2==0) ans[i]=(dis[i]==INF?-1:dis[i]-1);
spfa(n+1);
for(int i=1;i<=n;i++) if(a[i]&1) ans[i]=(dis[i]==INF?-1:dis[i]-1);
for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
return 0;
}