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
题意:
老板打算给员工们发奖励,但是员工会去存在一些要求,例如,输入a b 即a员工的奖励要比b员工的奖励多。老板决定每个员工的最低奖励为888元。老板想要知道自己最少需要多少钱俩奖励员工。所以最低工资为888,它的上一层的工资就是889,所以可以逆向建图,利于计算每个员工的工资。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
#include<queue>
#include<vector>
using namespace std;
const int maxn=10007;
vector<int>path[maxn];
int sum[maxn]; //记录每个员工的工资
int rudu[maxn]; //每个员工的入度,即要有几个人的工资比他低
queue<int> q;
int n,m;
void tuopu()
{
for(int i=1;i<=n;i++)
{
if(rudu[i]==0) //逆向建图,所以入度为0的工资最低
{
q.push(i);
sum[i]=888;
rudu[i]--;
}
}
while(!q.empty())
{
int x=q.front();
q.pop();
for(int i=0;i<path[x].size();i++)
{
rudu[path[x][i]]--;
if(rudu[path[x][i]]==0)
{
q.push(path[x][i]);
sum[path[x][i]]=sum[x]+1;
rudu[path[x][i]]--;
}
}
}
int flag=0;
int ans=0; //工资总数
for(int i=1;i<=n;i++)
{
if(rudu[i]!=-1)flag++; //有员工没有处理,说明存在回路,无法确定,要输出-1
}
if(flag!=0)printf("-1\n");
else
{
for(int i=1;i<=n;i++)
ans+=sum[i];
printf("%d\n",ans);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<=n;i++)
path[i].clear();
while(!q.empty())q.pop();
memset(rudu,0,sizeof(rudu));
memset(sum,0,sizeof(sum));
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
rudu[a]++;
path[b].push_back(a);
}
tuopu();
}
return 0;
}