求条45pts tarjan
查看原帖
求条45pts tarjan
551417
CommonDigger楼主2024/11/23 15:49

记录

/*
Luogu P2002 消息的扩散
https://www.luogu.com.cn/problem/P2002
*/
#include "iostream"
#include "stack"
#include "cstring"
using namespace std;
const int N=100005, M=500005;
int n, m, temp1, temp2, t=0, ans, belong[N];
int head[N], idx, j;
int dfn[N],  low[N];
int in[N], c1, c2;
bool ins[N];
stack<int>s;
struct edge{
	int to, nxt;
}e[M];
void add_edge(int u, int v){
	e[++idx].to=v;
	e[idx].nxt=head[u];
	head[u]=idx;
}
void dfs(int x){
	low[x]=dfn[x]=++t;
	s.push(x);
	ins[x]=true;
	for(int i=head[x];i;i=e[i].nxt){
		j=e[i].to;
		if(!dfn[j]){
			dfs(j);
			low[x]=min(low[x], low[j]);
		}else if(ins[j]) low[x]=min(low[x], dfn[j]);
	}
	if(dfn[x]==low[x]){
		ins[x]=false;
		belong[x]=++ans;
		while(s.top()!=x)
		{
			belong[s.top()]=ans;
			ins[s.top()]=false;
			s.pop();
		}
		s.pop();
	}
}
int main(){
	scanf("%d%d", &n, &m);
	for(int i=1;i<=m;i++){
		scanf("%d%d", &temp1, &temp2);
		if(temp1==temp2) continue;
		add_edge(temp1, temp2);
	}
	for(int i=1;i<=n;i++) if(!dfn[i]) dfs(i);
	for(int i=1;i<=n;i++){
		for(j=head[i];j;j=e[j].nxt){
			if(belong[i]!=belong[e[j].to])
				in[belong[e[j].to]]+=1;
		}
	}
	for(int i=1;i<=ans;i++) if(in[i]==0) c1+=1;
	if(c1==0) c1=1;
	printf("%d", c1);
}
2024/11/23 15:49
加载中...