codeforces1472 G. Moving to the Capital
生活随笔
收集整理的這篇文章主要介紹了
codeforces1472 G. Moving to the Capital
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
G. Moving to the Capital
先bfs一邊,求出距1號點的最短路用數組d1[]記錄,求的過程中如果當前點t遍歷到之前遍歷過的點j意味著這條邊就是能夠拉近與1號點距離的邊(橫向邊或者后向邊)那么就用d1[j]更新d2[t],d2[]表示最終求得答案。
然后反向邊建圖,從上面bfs的葉子節點開始,就像“撥葉子”一樣更新d2[]
注意:反向建圖跑bfs的更新條件
#define IO ios::sync_with_stdio(false);cin.tie();cout.tie(0) #pragma GCC optimize(2) #include<set> #include<map> #include<cmath> #include<stack> #include<queue> #include<random> #include<bitset> #include<string> #include<vector> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<unordered_map> #include<unordered_set> using namespace std; typedef long long ll; typedef pair<int,int> pii; const int N=200010,M=2*N; const ll mod=1e9+7; int n,m; int h1[N],h2[N],e[M],ne[M],idx; int d1[N],d2[N]; bool st[N],in[N]; void add(int h[],int a,int b) {e[idx]=b,ne[idx]=h[a],h[a]=idx++; } queue<int> q; void bfs() {for(int i=1;i<=n;i++)in[i]=st[i]=0,d1[i]=-1,d2[i]=0x3f3f3f3f;d1[1]=d2[1]=0;q.push(1);while(q.size()){int t=q.front();q.pop();int cnt=0;for(int i=h1[t];i!=-1;i=ne[i]){int j=e[i];if(d1[j]!=-1){d2[t]=min(d2[t],d1[j]);continue;}cnt++;d1[j]=d2[j]=d1[t]+1;q.push(j);}if(!cnt) st[t]=1;}for(int i=1;i<=n;i++)if(st[i]) {q.push(i);in[i]=1;}while(q.size()){int t=q.front();q.pop();in[t]=0;for(int i=h2[t];i!=-1;i=ne[i]){int j=e[i];if(d1[t]>d1[j]){d2[j]=min(d2[t],d2[j]);if(!in[j]) q.push(j);in[j]=1;}}} } int main() {IO;int T=1;cin>>T;while(T--){cin>>n>>m;for(int i=1;i<=n;i++) h1[i]=h2[i]=-1;idx=0;while(m--){int a,b;cin>>a>>b;add(h1,a,b);add(h2,b,a);}bfs();for(int i=1;i<=n;i++) cout<<d2[i]<<' ';cout<<'\n';}return 0; }要加油哦~
總結
以上是生活随笔為你收集整理的codeforces1472 G. Moving to the Capital的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 谪仙人
- 下一篇: codeforces1467 E. Di