模擬賽 上白澤慧音
阿新 • • 發佈:2019-02-19
題目描述
在幻想鄉,上白澤慧音是以知識淵博聞名的老師。春雪異變導致人間之裡的很多道路都被大雪堵塞,使有的學生不能順利地到達慧音所在的村莊。因此慧音決定換一個能夠聚集最多人數的村莊作為新的教學地點。人間之裡由 N 個村莊(編號為 1..N)和 M 條道路組成,道路分為兩種一種為單向通行的,一種為雙向通行的,分別用 1 和 2 來標記。如果存在由村莊 A 到達村莊 B 的通路,那麼我們認為可以從村莊 A 到達村莊 B,記為(A,B)。當(A,B)和(B,A)同時滿足時,我們認為 A,B 是絕對連通的,記為<A,B>。絕對連通區域是指一個村莊的集合,在這個集合中任意兩個村莊 X,Y 都滿足<X,Y>。 現在你的任務是,找出最大的絕對連通區域,並將這個絕對連通區域的村莊按編號依次輸出。若存在兩個最大的,輸出字典序最小的,比如當存在 1,3,4和 2,5,6 這兩個最大連通區域時,輸出的是 1,3,4。
輸入格式
第 1 行:兩個正整數 N,M
第 2..M+1 行:每行三個正整數 a,b,t, t = 1 表示存在從村莊 a 到 b 的單向道路,t = 2 表示村莊a,b 之間存在雙向通行的道路。保證每條道路只出現一次。
輸出格式
第 1 行: 1 個整數,表示最大的絕對連通區域包含的村莊個數。
第 2 行:若干個整數,依次輸出最大的絕對連通區域所包含的村莊編號。
輸入樣例
5 5
1 2 1
1 3 2
2 4 2
5 1 2
3 5 1
輸出樣例
3
1 3 5
資料範圍
對於 60%的資料:N <= 200 且 M <= 10,000
對於 100%的資料:N <= 5,000 且 M <= 50,000
題解
上課的晚上抽一個小時做四題簡直作死,四題只打了一個小時還不帶檢查,不靠譜到飛。所以第一次交時變數名打錯了0分。
#include<cstdio> #include<cstring> #include<iostream> #include<cstdlib> #include<cmath> #include<algorithm> #define ll long long using namespace std; int n,m,zz,head[5002],ans; struct bian{int to,nx;} e[100002]; int pre[5002],low[5002],sccnum[5002],scc,ct; int stack[5002],top,num[5002]; void insert(int x,int y) { zz++; e[zz].to=y; e[zz].nx=head[x]; head[x]=zz; } void init() { scanf("%d%d",&n,&m); int i,x,y,z; for(i=1;i<=m;i++) {scanf("%d%d%d",&x,&y,&z); insert(x,y); if(z==2) insert(y,x); } } void dfs(int x) { low[x]=pre[x]=++ct; stack[++top]=x; int i,p; for(i=head[x];i;i=e[i].nx) {p=e[i].to; if(!pre[p]) {dfs(p); low[x]=min(low[x],low[p]);} else if(!sccnum[p]) low[x]=min(low[x],pre[p]); } p=-1; if(low[x]==pre[x]) {scc++; while(p!=x) {p=stack[top]; top--; sccnum[p]=scc; num[scc]++; } if(num[scc]>num[ans]) ans=scc; } } void tarjan() { int i,tag=0; for(i=1;i<=n;i++) {if(!pre[i]) dfs(i);} printf("%d\n",num[ans]); for(i=1;i<=n;i++) {if(sccnum[i]==ans) {if(tag) printf(" "); printf("%d",i); tag=1; } } } int main() { freopen("classroom.in","r",stdin); freopen("classroom.out","w",stdout); init(); tarjan(); return 0; }