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
题解:使用拓扑排序解决问题,第一次做,注意 x y的顺序。
代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int sum_son;
vector<int>son; //使用了动态数组
int sum_rudu,sum;
} Node[10100];
int main()
{
int m,n;
while(scanf("%d%d",&n,&m)!=EOF)
{
queue<int> q;
int x,y,i,j;
unsigned long long sum=0;
memset(Node,0,sizeof(Node));
for(i=0; i<m; i++)
{
scanf("%d%d",&y,&x);
Node[x].son.push_back(y); //直接赋值会崩溃的,要使用push_back
Node[x].sum_son++;
Node[y].sum_rudu++;
}
for(i=1; i<=n; i++)
if(Node[i].sum_rudu==0) q.push(i),Node[i].sum=888;
int cnt=n;
while(!q.empty())
{
int cur=q.front();
q.pop();
cnt--;
for(i=0; i<Node[cur].sum_son; i++)
{
if(--Node[Node[cur].son[i]].sum_rudu==0) q.push(Node[cur].son[i]);
Node[Node[cur].son[i]].sum=Node[cur].sum+1;
}
}
if(cnt) printf("-1\n");
else
{
for(i=1; i<=n; i++)
sum+=Node[i].sum;
printf("%lld\n",sum);
}
}
return 0;
}