HDU_Reward_拓扑排序
Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7009 Accepted Submission(s): 2174
Problem Description
Dandelion's uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards.
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.
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.
Input
One line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000)
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
Output
For every case ,print the least money dandelion 's uncle needs to distribute .If it's impossible to fulfill all the works' demands ,print -1.
Sample Input
2 1
1 2
2 2
1 2
2 1
Sample Output
1777
-1
wa了很多次,一直没找出错在哪,想了很久,发现了错误。
{6 6 2 6 3 6 4 2 4 3 4 1 4 5}这组数据的结果就不对。
如图:
最开始的程序算出的结果为5331,但正确答案为5332。找到了问题。需要每次对当前入度为0的点的后继更新值,而不是当后继度数为零了才更新。
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<vector> #include<stack> using namespace std; int n,m; vector<int> v[10005]; int degree[10005]; int mon[10005]; void topusort() { stack<int>s; for(int i=1; i<=n; i++) if(degree[i]==0) { mon[i]=0; s.push(i); } long long tot=0,cnt=0; while(!s.empty()) { int h=s.top(); degree[h]--; s.pop(); cnt++; tot+=mon[h]; for(int i=0; i<v[h].size(); i++) { degree[v[h][i]]--; mon[v[h][i]]=max(mon[v[h][i]],mon[h]+1); //做出的修改 if(degree[v[h][i]]==0) { //mon[v[h][i]]=mon[h]+1; //之前的问题就出在这 s.push(v[h][i]); } } } if(cnt==n) printf("%I64d\n",tot+888*n); else printf("-1\n"); } int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(degree,0,sizeof(degree)); memset(mon,0,sizeof(mon)); for(int i=0; i<=n; i++) v[i].clear(); for(int i=0; i<m; i++) { int a,b; scanf("%d%d",&a,&b); v[b].push_back(a); degree[a]++; } //cout<<degree[1]<<endl; topusort(); } return 0; } /* 7 8 2 1 3 1 4 1 5 2 5 3 6 4 7 5 7 6 */