拓扑排序啦,就是像这样写的,邻接表好像挺好用的,不需要判断有无边,注意入度为0的一开始都放到队列里面;
这题很坑的就是输入u v是指v->u而不是u->v,由题意!!!
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 vector <int> graph[10005]; 6 int ind[10005]; 7 int cost[10005]; 8 9 void bfs(int n) 10 { 11 int ans=0; 12 int count=0; 13 queue <int> q; 14 for(int i=1; i<=n; i++) 15 { 16 if(ind[i] == 0) 17 { 18 q.push(i); 19 cost[i]=100; 20 } 21 } 22 while(!q.empty()) 23 { 24 int temp = q.front(); 25 q.pop(); 26 count++; 27 ans += cost[temp]; 28 29 for(int i=0; i<graph[temp].size(); i++) 30 { 31 if(--ind[graph[temp][i]] == 0) 32 { 33 q.push(graph[temp][i]); 34 cost[graph[temp][i]] = cost[temp]+1; 35 } 36 } 37 } 38 if(count == n) 39 printf("%d\n", ans); 40 else 41 printf("Poor Xed\n"); 42 } 43 44 45 int main() 46 { 47 int t,n,m; 48 while(scanf("%d%d", &n, &m) != EOF) 49 { 50 memset(graph, 0, sizeof(graph)); 51 memset(ind, 0, sizeof(ind)); 52 memset(cost, 0, sizeof(cost)); 53 int u,v; 54 for(int i=0; i<m; i++) 55 { 56 scanf("%d%d", &u, &v); 57 graph[v].push_back(u); 58 ind[u]++; 59 } 60 bfs(n); 61 } 62 return 0; 63 }
时间: 2024-10-10 10:08:20