80pts求助
查看原帖
80pts求助
195705
李湛然楼主2021/8/2 10:33
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
const int N=1e5+5;
int n,m;
int head[N];
int nxt[N];
int to[N];
int tot=0;
int in[N];
int out[N];
int path[N]; 
inline void add(int x,int y)
{
	nxt[++tot]=head[x];
	head[x]=tot;
	to[tot]=y;
}
queue<int> q; 
inline int read()
{
    char ch=getchar();
    int x=0,f=1;
    while((ch>'9'||ch<'0')&&ch!='-')
        ch=getchar();
    if(ch=='-')
    {
        f=-1;
        ch=getchar();
    }
    while('0'<=ch&&ch<='9')
    {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*f;
}
int main()
{
	int x,y;
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		x=read();
		y=read();
		add(x,y);
		in[y]++;
		out[x]++;
	}
	for(int i=1;i<=n;i++)
	{
		if(in[i]==0)
		{
			q.push(i);
			path[i]=1;
		}
	}
	//topo;
	while(!q.empty())
	{
		int a=q.front();
		q.pop();
		for(int i=head[a];i;i=nxt[i])
		{
			int y=to[i];
			in[y]--;
			path[y]=path[a]+1;
			if(in[y]==0)
			{
				if(out[y]==0)
				{
					continue;
				}
				q.push(y);
			}
		}
	}
	for(int i=1;i<=n;i++)
	{
		printf("%d\n",path[i]);
	}
	return 0;
}
2021/8/2 10:33
加载中...