标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7231 Accepted Submission(s): 2263
#include <iostream> #include <cstdio> #include <string.h> #include <queue> #include <algorithm> #include <math.h> using namespace std; const int N = 10005; const int M = 20005; struct Edge{ int v,next; }edge[M]; int head[N]; int indegree[N]; int w[N]; int tot; void init(){ memset(head,-1,sizeof(head)); memset(indegree,0,sizeof(indegree)); tot = 0; } void addEdge(int u,int v,int& tot){ edge[tot].v = v,edge[tot].next = head[u],head[u] = tot++; } int main(){ int n,m; while(scanf("%d%d",&n,&m)!=EOF){ init(); for(int i=1;i<=m;i++){ int u,v; scanf("%d%d",&u,&v); addEdge(v,u,tot); indegree[u]++; } queue<int> q; int tot = 0; for(int i=1;i<=n;i++){ if(!indegree[i]) { q.push(i); w[i] = 888; tot+=w[i]; } } int cnt = 0; while(!q.empty()){ int u = q.front(); q.pop(); cnt++; for(int k = head[u];k!=-1;k=edge[k].next){ int v = edge[k].v; indegree[v]--; if(!indegree[v]){ w[v] = w[u]+1; tot+=w[v]; q.push(v); } } } if(cnt!=n) printf("-1\n"); else{ printf("%d\n",tot); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5692904.html