求助,样例没过输出2
查看原帖
求助,样例没过输出2
1231078
bjzjh楼主2024/9/24 17:25
#include<bits/stdc++.h>
using namespace std;
int to[200010],pr[200010],hd[100010],cnt,x,y,f[100010],ans,n,m,sum,ind[100010],out[100010];
struct node{
    int u,w,next;
}e[200010];
long long read(){
	char ch;
	long long x=0,f=1;
	ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-') f=-f;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=(x<<3)+(x<<1)+(ch^48);
		ch=getchar();
	}
	return x*f;
}
void write(long long x){
	if(x<0){
		x=-x;
		putchar('-');
	}
    if(x>=10) write(x/10);
    putchar('0'+x%10); 
}
void _add(){
	e[++cnt].u=x;
	e[cnt].w=y;
	e[cnt].next=hd[x];
	hd[x]=cnt;
}
int dfs(int x){
	if(f[x]) return f[x];
	ans=0;
	if(out[x]==0) return 1;
	for(int i=hd[x];i;i=e[i].next){
		ans+=dfs(e[i].w);
		
	}
	f[x]=ans;
	return ans;
}
int main(){
	n=read(); m=read();
	for(int i=1;i<=m;i++){
		x=read();
		y=read();
		_add();
//		cout<<x<<' '<<y<<endl;
		ind[x]++;
		out[y]++;
	}
	for(int i=1;i<=n;i++){
		if(ind[i]==0&&out[i]){
			sum+=dfs(i);
		}
	}
	//for(int i=1;i<=n;i++){
//		cout<<f[i]<<endl;
	//}
	write(sum);
}
2024/9/24 17:25
加载中...