上白澤慧音(tarjan求強連通分量)
阿新 • • 發佈:2019-02-15
題目描述
在幻想鄉,上白澤慧音是以知識淵博聞名的老師。春雪異變導致人間之裡的很多道路都被大雪堵塞,使有的學生不能順利地到達慧音所在的村莊。因此慧音決定換一個能夠聚集最多人數的村莊作為新的教學地點。人間之裡由 N 個村莊(編號為 1..N)和 M 條道路組成,道路分為兩種一種為單向通行的,一種為雙向通行的,分別用 1 和 2 來標記。如果存在由村莊 A 到達村莊 B 的通路,那麼我們認為可以從村莊 A 到達村莊 B,記為(A,B)。當(A,B)和(B,A)同時滿足時,我們認為 A,B 是絕對連通的,記為
輸入格式
第 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
tarjan求強連通分量,很裸的,輸出結構體排序處理,就可以A掉了
程式碼
#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
#define MAXN 50010
using namespace std;
int n,m;
int dfn[MAXN],low[MAXN],cnt;
bool vis[MAXN];
int head[MAXN],tot;
struct node {
int tal;
short s[5000];
};
node e[5000];
struct nod {
int to;
int next;
};
nod ed[MAXN*2];
stack<int> s;
inline void read(int&x) {
x=0;char c=getchar();
while(c>'9'||c<'0') c=getchar();
while(c>='0'&&c<='9') x=10*x+c-48,c=getchar();
}
inline void add(int x,int y) {
ed[++tot].to=y;
ed[tot].next=head[x];
head[x]=tot;
}
inline bool cmp(const node&a,const node&b) {
if(a.tal==b.tal)
for(int i=1;i<=a.tal;i++)
return a.s[i]<b.s[i];
return a.tal>b.tal;
}
inline void tarjan(int u) {
dfn[u]=low[u]=++tot;
vis[u]=true;
s.push(u);
for(int i=head[u];i;i=ed[i].next) {
int v=ed[i].to;
if(!dfn[v]) {
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(vis[v]) low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u]) {
++cnt;
int t,sum=0;
do {
t=s.top();
s.pop();
vis[t]=false;
e[cnt].s[++sum]=t;
}while(u!=t);
e[cnt].tal=sum;
sort(e[cnt].s+1,e[cnt].s+sum+1);
}
}
int hh() {
freopen("classroom.in","r",stdin);
freopen("classroom.out","w",stdout);
read(n);read(m);
int x,y,z;
for(int i=1;i<=m;i++) {
read(x);read(y);read(z);
if(z==1) add(x,y);
else add(x,y),add(y,x);
}
tot=0;
for(int i=1;i<=n;i++) {
if(!dfn[i])
tarjan(i);
}
sort(e+1,e+1+cnt,cmp);
printf("%d\n",e[1].tal);
for(int i=1;i<=e[1].tal;i++)
printf("%d ",e[1].s[i]);
printf("\n");
return 0;
}
int hhh=hh();
int main() {;}