Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7231 Accepted Submission(s): 2263
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
#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; }