有大佬帮能我看一下哪里错了吗?我感觉没问题啊!
查看原帖
有大佬帮能我看一下哪里错了吗?我感觉没问题啊!
809522
zhongxh666楼主2024/8/6 20:41
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 100010, M = 200010;
int n, m;
int h[N], e[M], ne[M], idx;
int din[N];
int res[N];
queue<PII> q;
void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int main(){
    memset(h, -1, sizeof h);
	scanf("%d%d", &n, &m);
	while(m--){
	    int a, b;
	    scanf("%d%d", &a, &b);
	    add(a, b); //邻接表加边函数
	    din[b]++; //入度加1
	}
	for(int i = 1;i <= n;i++){
	    if(!din[i]){ //如果入度为0,则加入队列
	        q.push({i, 1});
	        res[i] = 1;
	    }
	}
	while(q.size()){ //bfs
	    PII t = q.front();
	    q.pop();
	    for(int i = h[t.x];~i;i = ne[i]){ //遍历邻边
	        int j = e[i];
	        q.push({j, t.y + 1});
	        res[j] = max(res[j], t.y + 1); //更新
	    }
	}
	for(int i = 1;i <= n;i++){
	    printf("%d\n", res[i]);
	}
	return 0;
}

万分感谢!!!!!!!!!!!!!!!(下跪

2024/8/6 20:41
加载中...