[关闭]
@Chilling 2017-02-16T09:54:58.000000Z 字数 1963 阅读 779

HDU-2647: Reward

拓扑排序


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 1
1 2
2 2
1 2
2 1

Sample Output

1777
-1

题意:输入n和m,代表有n个人,以下有m行需求,每行两个数字x和y,表示x的奖金要比y的奖金高,最低的奖金是888元,求能满足所有人的需求的最小奖金。

分析:这道题数据比较多,最好用邻接表来存。将x作为入度,y作为出度,入度为0说明只有基础奖励888元。

比如1>2,2>3,3>4,存入的时候in[1]++,in[2]++,in[3]++,4这个人入度为0,就只有基础奖金。

  1. void topsort()
  2. {
  3. queue<int>q;
  4. for(int i=1;i<=n;i++) //找出入度为0的点
  5. {
  6. if(in[i]==0)
  7. {
  8. pay[i]=888;
  9. q.push(i);
  10. }
  11. }
  12. s=0;
  13. while(!q.empty())
  14. {
  15. int now=q.front();
  16. q.pop();
  17. s++;
  18. int l=v[now].size();
  19. for(int i=0;i<l;i++)
  20. {
  21. int k=v[now][i];
  22. in[k]--;
  23. if(in[k]==0)
  24. {
  25. q.push(k);
  26. pay[k]=pay[now]+1; //比前一个人的奖金多1元
  27. }
  28. }
  29. }
  30. if(s<n) flag=0;
  31. }
  1. #include<stdio.h>
  2. #include<vector>
  3. #include<queue>
  4. #include<string.h>
  5. using namespace std;
  6. vector<int>v[10005];
  7. int in[10005],pay[10005];
  8. int n,m,s,flag;
  9. void topsort()
  10. {
  11. queue<int>q;
  12. for(int i=1;i<=n;i++)
  13. {
  14. if(in[i]==0)
  15. {
  16. pay[i]=888;
  17. q.push(i);
  18. }
  19. }
  20. s=0;
  21. while(!q.empty())
  22. {
  23. int now=q.front();
  24. q.pop();
  25. s++;
  26. int l=v[now].size();
  27. for(int i=0;i<l;i++)
  28. {
  29. int k=v[now][i];
  30. in[k]--;
  31. if(in[k]==0)
  32. {
  33. q.push(k);
  34. pay[k]=pay[now]+1;
  35. }
  36. }
  37. }
  38. if(s<n) flag=0;
  39. }
  40. int main()
  41. {
  42. int i,x,y,sum;
  43. while(scanf("%d%d",&n,&m)!=EOF)
  44. {
  45. flag=1,sum=0;
  46. memset(in,0,sizeof(in));
  47. memset(pay,0,sizeof(pay));
  48. for(i=0;i<m;i++)
  49. {
  50. scanf("%d%d",&x,&y);
  51. v[y].push_back(x);
  52. in[x]++;
  53. }
  54. topsort();
  55. if(flag==0)
  56. printf("-1\n");
  57. else
  58. {
  59. for(i=1;i<=n;i++)
  60. sum+=pay[i];
  61. printf("%d\n",sum);
  62. }
  63. for(i=1;i<=n;i++)
  64. v[i].clear();
  65. }
  66. return 0;
  67. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注