HDU 2647 Reward(拓扑排序)

来源:互联网 发布:nginx 密码访问 编辑:程序博客网 时间:2024/04/24 07:36

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7049    Accepted Submission(s): 2192


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.
 

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.
 

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 11 22 21 22 1
 

Sample Output
1777-1

分析:拓扑排序,判断有向五环图。入度为0的结点跳出结点集合,根据结点在哪一次跳出结点集合决定需要花费的钱,即888+top-1(第一个结点为888),根据跳出的结点数,来判断是否有环存在。

代码如下:

#include <stdio.h>#include <vector>#include <string.h>#define MAX 10010using namespace std;int n,m;int money[MAX];int vis[MAX],indegree[MAX],f[MAX];int sum=0,top,t;vector <int>map[MAX];void init(){for(int i=1;i<MAX;i++)map[i].clear();//清空邻接表 for(int i=0;i<MAX;i++)money[i]=888;//初始工资 memset(indegree,0,sizeof(indegree)); //入度清零memset(f,0,sizeof(f));top=0;//层数清零t=0;//访问结点数清零 }void toposort(){int i,j,k;bool p;p=true;while(p){p=false;top++;for(i=1;i<=n;i++){if(!indegree[i]){p=true;f[i]=top;money[i]=money[i]+top-1;t++;}}for(i=1;i<=n;i++){if(f[i]==top){for(k=0;k<map[i].size();k++){int v=map[i][k];indegree[v]--;}indegree[i]=-1;}}}top--;}int main(){int i,j;int a,b;while(~scanf("%d %d",&n,&m)){init();for(i=1;i<=m;i++){scanf("%d %d",&a,&b);map[b].push_back(a);indegree[a]++;}toposort();if(t==n){int sum=0;for(i=1;i<=n;i++)sum+=money[i];printf("%d\n",sum);}elseprintf("-1\n");}return 0;}




0 0
原创粉丝点击