玄关求调
查看原帖
玄关求调
936616
zibenlun楼主2024/1/27 15:36

感觉和题解已经差不多了……

#include<bits/stdc++.h>
using namespace std;
inline long long read() {
	long long s=0;
	char ch=getchar();
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9') {
		s=(s<<3)+(s<<1)+(ch^48);
		ch=getchar();
	}
	return s;
}
inline void write(long long x) {
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+'0');
}
int n,m;
vector<int> v[1000005];
int cnt[1000005],f[1000005];
queue<int> q;
int main() {
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        v[x].push_back(y);
        cnt[y]++;
    }
    for(int i=1;i<=n;i++){
        if(cnt[i]==0){
            q.push(i);
            f[i]=1;
            break;
        }
    }
    while(q.size()){
        int x=q.front();
        q.pop();
        for(auto i:v[x]){
            if(--cnt[i]==0){
                q.push(i);
                f[i]=f[x]+1;
            }
        }
    }
    for(int i=1;i<=n;i++){
        cout<<f[i]<<"\n";
    }
	return 0;
}

2024/1/27 15:36
加载中...