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.
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
思路
分清楚哪个点是入度哪个是出度。拓扑排序的层次结构!!
代码
#include<bits/stdc++.h>
using namespace std;
vector<int> mp[10005];
int in[10005],r[10005];
int main(){
int n,m,a,b;
while(cin>>n>>m){
//初始化
for(int i=0;i<=n;i++){
in[i]=0;
r[i]=888;
mp[i].clear();
}
//输入
for(int i=0;i<m;i++){
cin>>a>>b;
mp[b].push_back(a);
in[a]++;
}
//拓扑排序
queue<int> Q;
for(int i=1;i<=n;i++){
if(in[i]==0){
Q.push(i);
}
}
int k=0;
while(!Q.empty()){
int now=Q.front();
Q.pop();
k++;
for(int i=0;i<mp[now].size();i++){
in[mp[now][i]]--;
if(in[mp[now][i]]==0){
Q.push(mp[now][i]);
r[mp[now][i]]=r[now]+1;
}
}
}
if(k<n){
cout << -1 <<endl;
}else{
int sum=0;
for(int i=1;i<=n;i++){
sum+=r[i];
}
cout << sum <<endl;
}
}
return 0;
}