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]了。因此我們要反向建邊,建邊后跑兩次最短路就可以了。
代碼如下:
努力加油a啊,(o)/~
總結
以上是生活随笔為你收集整理的Nearest Opposite Parity(反向建边+spfa)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Remove One Element(贪
- 下一篇: Common Number(奇偶二分+找