日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Nearest Opposite Parity(反向建边+spfa)

發布時間:2023/12/15 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Nearest Opposite Parity(反向建边+spfa) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

You are given an array aa consisting of nn integers. In one move, you can jump from the position ii to the position i?aii?ai (if 1≤i?ai1≤i?ai) or to the position i+aii+ai (if i+ai≤ni+ai≤n).

For each position ii from 11 to nn you want to know the minimum the number of moves required to reach any position jj such that ajaj has the opposite parity from aiai (i.e. if aiai is odd then ajaj has to be even and vice versa).

Input
The first line of the input contains one integer nn (1≤n≤2?1051≤n≤2?105) — the number of elements in aa.

The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.

Output
Print nn integers d1,d2,…,dnd1,d2,…,dn, where didi is the minimum the number of moves required to reach any position jj such that ajaj has the opposite parity from aiai (i.e. if aiai is odd then ajaj has to be even and vice versa) or -1 if it is impossible to reach such a position.

Example
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
思路:一開始以為是記憶化搜索,就dfs,結果成環的情況不能處理。這種題目,一般進行轉化,將這些數字建成圖來處理。我們建立一個超級偶數源點和一個超級奇數源點,分別連接偶數點和奇數點。
對于建邊操作,我們要反向建邊。為什么要反向建邊呢?我們反向建邊后,拿超級偶數源點來說,我們跑最短路,dis[i]代表的是這個源點到i點的最短路,反過來說也就是i到超級源點的最短路。我們取奇數點記錄dis[i],這樣一來,就可以找到每一個奇數點離它最近的偶數點了。如果我們正向建邊,dis[i]代表的是這個源點到i點的最短路,但是不能代表i點到源點的最短路。這樣就不能記錄dis[i]了。因此我們要反向建邊,建邊后跑兩次最短路就可以了。
代碼如下:

#include<bits/stdc++.h> #define ll long long #define inf 1e9 using namespace std;const int maxx=2e6+100; struct edge{int to;int next; }e[maxx<<1]; int dis[maxx],vis[maxx],ans[maxx]; int a[maxx],head[maxx<<1]; int n,tot=0;inline void add(int u,int v) {e[tot].to=v,e[tot].next=head[u],head[u]=tot++; } inline void spfa(int u) {for(int i=0;i<=n+2;i++) dis[i]=inf,vis[i]=0;dis[u]=0;vis[u]=1;queue<int> q;while(q.size()) q.pop();q.push(u);while(q.size()){int v=q.front();q.pop();vis[v]=0;for(int i=head[v];i!=-1;i=e[i].next){int to=e[i].to;if(dis[to]>dis[v]+1){dis[to]=dis[v]+1;if(vis[to]==0){vis[to]=1;q.push(to);}}}}} int main() {scanf("%d",&n);tot=0;for(int i=1;i<=n;i++) scanf("%d",&a[i]);memset(head,-1,sizeof(head));for(int i=1;i<=n;i++){if(i+a[i]<=n) add(i+a[i],i);if(i-a[i]>=1) add(i-a[i],i);if(a[i]%2==0) add(n+1,i);else add(n+2,i);}spfa(n+1);//偶數源點跑最短路for(int i=1;i<=n;i++) if(a[i]%2==1) ans[i]=dis[i];spfa(n+2);//奇數源點跑最短路for(int i=1;i<=n;i++) if(a[i]%2==0) ans[i]=dis[i];for(int i=1;i<=n;i++) cout<<(ans[i]==inf?-1:(ans[i]-1))<<" ";cout<<endl;return 0; } /*10 3 3 3 1 1 1 2 3 4 6*/

努力加油a啊,(o)/~

總結

以上是生活随笔為你收集整理的Nearest Opposite Parity(反向建边+spfa)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。