蒻蒟求助!80pts
查看原帖
蒻蒟求助!80pts
544458
WAI_kycm楼主2023/4/20 14:50
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int n, m;
struct Tree{
	int to, next, from;
}e[maxn], e2[maxn];
int len, head[maxn], len2, head2[maxn];
void Insert(int u, int v, int &len, int head[], Tree e[]){
	e[++len].to = v; e[len].from = u; e[len].next = head[u]; head[u] = len;
}
void Read(){
	cin>>n>>m;
	for(int i = 1; i <= m; ++i){
		int u, v; cin>>u>>v;
		Insert(u, v, len, head, e);
	}
}
int dfn[maxn], low[maxn], Time;
int siz[maxn], belong[maxn], vis[maxn], q[maxn], top, cnt;
void Tarjan(int u){
	dfn[u] = low[u] = ++Time;
	vis[u] = 1; q[++top] = u;
	for(int i = head[u]; i; i = e[i].next){
		int v = e[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++;
		while(q[top + 1] != u){
			int v = q[top--];
			vis[v] = 0;
			belong[v] = cnt;
			siz[cnt]++;
		}
	}
}
int ans, res;
int out[maxn];
void Solve(){
	Read();
	for(int i = 1; i <= n; ++i) if(!dfn[i]) Tarjan(i);
	for(int i = 1; i <= n; ++i){
		int u = belong[e[i].from], v = belong[e[i].to];
		if(u != v) Insert(u, v, len2, head2, e2);
	}
	for(int i = 1; i <= cnt; ++i)
		for(int j = head2[i]; j; j = e2[j].next)
			out[i]++;
	for(int i = 1; i <= cnt; ++i) if(!out[i]) ans = siz[i], res++;
	if(res == 1) cout<<ans<<endl;
	else cout<<"0"<<endl;
}
int main(){
	Solve();
	return 0;
}

主要为缩点后建新图,然后判断出度

2023/4/20 14:50
加载中...