1. 程式人生 > >上白澤慧音——原來Tarjan 適用混合圖,原來String 排字典序的確坑(或者說我的腦袋太水?)

上白澤慧音——原來Tarjan 適用混合圖,原來String 排字典序的確坑(或者說我的腦袋太水?)

show sort 所有 open logs true 的確 back 字典序

  模板強連通分量,強連通Tarjan 可以直接過,只是題目多了需要字典序比較並輸出的需要。然而我偷懶想用String 儲存所有計算出的強連通分量,然後sort 一遍輸出,結果是提交了三次都是錯的。看到別處題解的字典序求法,然後就改對了。

技術分享
 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<vector>
 5 #include<stack>
 6 #include<queue>
 7 using namespace
std; 8 const int N=5011; 9 int n,m,num,cnt,val[N],low[N],col[N],coln[N],pri[N],res; 10 bool in[N]; 11 vector<int> gr[N]; 12 stack<int> s; 13 14 void dfs(int x){ 15 val[x]=low[x]=num++; 16 s.push(x); 17 in[x]=true; 18 19 for(int i=0;i<gr[x].size();i++)
20 if(!val[gr[x][i]]){ 21 dfs(gr[x][i]); 22 low[x]=min(low[x],low[gr[x][i]]); 23 } 24 else if(in[gr[x][i]]) 25 low[x]=min(low[x],val[gr[x][i]]); 26 27 if(low[x]==val[x]){ 28 cnt++; 29 while(1){ 30 int
u=s.top();s.pop(); 31 in[u]=false; 32 col[u]=cnt; 33 if(u==x)break; 34 } 35 36 } 37 } 38 39 int main(){ 40 cin>>n>>m; 41 for(int i=1;i<=m;i++){ 42 int x,y,z;scanf("%d%d%d",&x,&y,&z); 43 gr[x].push_back(y); 44 if(z==2)gr[y].push_back(x); 45 } 46 47 for(int i=1;i<=n;i++) 48 if(!val[i]) 49 dfs(i); 50 51 for(int i=1;i<=n;i++){ 52 coln[col[i]]++; 53 if(!pri[col[n]])pri[col[n]]=i; 54 } 55 56 for(int i=1;i<=cnt;i++) 57 if(coln[col[i]]>coln[res]||(coln[col[i]]==coln[res]&&pri[col[i]]<pri[res])) 58 res=col[i]; 59 cout<<coln[res]<<endl; 60 for(int i=1;i<=n;i++) 61 if(col[i]==res) 62 cout<<i<<" "; 63 cout<<endl; 64 return 0; 65 }
Method_01

  洛谷 Aqours 16ms

上白澤慧音——原來Tarjan 適用混合圖,原來String 排字典序的確坑(或者說我的腦袋太水?)