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
思路:拓扑排序+反图
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
vector<int >s[10005];
int in[10002];//记录下入度
int cost[10005];
int main()
{
int n,m;
queue<int >q;
while(~scanf("%d%d",&n,&m))
{
memset(in,0,sizeof(in));
for(int i=1;i<=n;i++)
{
s[i].clear();
cost[i]=888;//开一个数组表示第i个所需要的奖金
}
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
s[b].push_back(a);//表示一条边,
in[a]++;
}
int sum=0,k=0;
for(int i=1;i<=n;i++)
{
if(in[i]==0)
{
q.push(i);
k++;
sum+=cost[i];
in[i]=-1;
}
}
while(!q.empty())
{
int t=q.front();q.pop();
for(int i=0;i<s[t].size();i++)
{
int c=s[t][i];
if(cost[c]<cost[t]+1) cost[c]=cost[t]+1;
in[c]--;
if(in[c]==0)
{
q.push(c);
k++;
sum+=cost[c];
}
}
}
if(k==n)
printf("%d\n",sum);
else
printf("-1\n");
}
return 0;
}