Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7523 Accepted Submission(s): 2373
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
Author
dandelion
Source
Recommend
yifenfei
题目大意:快过年了,老板要给员工们发年终奖,员工个数为n,但是这些员工们有m条愿望,下面m行,每行输入a b,代表a的奖金比b多,怎么才能使老板花费最少并且满足所有的愿望呢?最低员工的年终奖金为888元,如果不能满足所有愿望,输出-1。
解题思路:用链表来拓扑排序,如果不能满足的话说明其中有环,判断处理顶点的个数与总数是否相等即可判断是否有环。
代码如下:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int to,next;
}bian[20010];
int in[10010];
int n,m;
int head[20010];
int money[10010];
void tuopu()
{
queue<int>q;
memset(money,0,sizeof(money));
for(int i=1;i<=n;i++)
{
if(in[i]==0)//度数为0(无要求的员工888元)
{
q.push(i);
money[i]=888;
}
}
int sum=0;//记录处理的节点的个数
while(!q.empty())
{
int tmp=q.front();
q.pop();
sum++;
for(int i=head[tmp];i!=-1;i=bian[i].next)
{
in[bian[i].to]--;//将与tmp连接的点的度数都减一
if(in[bian[i].to]==0)//一旦度数为0 则加入队列
{
money[bian[i].to]=money[tmp]+1;//要最节省,所有他最多是他前面元素的钱数+1
q.push(bian[i].to);
}
}
}
if(sum!=n)//判断是否成环
{
printf("-1\n");
}
else
{
int ans=0;
for(int i=1;i<=n;i++)
{
ans=ans+money[i];
}
printf("%d\n",ans);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(head,-1,sizeof(head));//初始化表头
memset(in,0,sizeof(in));//初始化入读
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
bian[i].to=a;//a约束着b,所以在树中,a在b的右端
bian[i].next=head[b];
head[b]=i;
in[a]++;
}
tuopu();
}
return 0;
}