题目 :
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
题意 :
老板给员工发奖金,最少的奖金是888,但是有些条件,有些人的奖金应该比另些人的奖金多
( each line contains two integers a and b ,stands for a's reward should be more than b's.)
问最少需要多少钱。 如果没有办法实现给的条件,则输出-1.(比如要求2比1的奖金多,1也要比2多)
思路 :
拓 扑 排 序 ( http://baike.baidu.com/view/288212.htm )
一开始没有想着用拓扑排序,以为是每个节点只能有一个父节点 并且 没有环就可以了,这样写出来错了好多次。
后来才发现是可以有多个父节点的,然后就用拓扑排序写的。
代码 :
1 #include<iostream> 2 #include<vector> 3 #include<cstring> 4 5 using namespace std; 6 7 const int T=10005; 8 vector < int > Q[T]; 9 int in[T],sum; 10 11 void find( int n ){ 12 int s=887,x=0; 13 while(1){ 14 s++; x--; 15 int Flag=0; 16 for( int i=1;i<=n;i++ ){ 17 if(in[i]==0) 18 { 19 Flag=1; 20 sum+=s; 21 in[i]=x; 22 } 23 } 24 for( int i=1;i<=n;i++) 25 if( in[i]==x ) 26 for( int j=0;j<(int)Q[i].size();j++){ 27 int k=Q[i][j]; 28 in[k]--; 29 } 30 if( !Flag ) break; 31 } 32 } 33 34 int main( ){ 35 36 int n,m,a,b,flag; 37 while( cin>>n>>m ){ 38 flag=0; 39 sum=0; 40 memset(in,0,sizeof(in)); 41 for( int i=1;i<=n;i++) 42 Q[i].clear(); 43 for( int i=1;i<=m;i++){ 44 cin >>a >>b; 45 Q[b].push_back(a); 46 in[a]++; 47 } 48 find( n ); 49 for( int i=1;i<=n;i++) 50 if(in[i]>0) 51 { 52 flag=1; 53 break; 54 } 55 if( flag ) cout <<"-1" <<endl; 56 else cout <<sum <<endl; 57 } 58 }