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 <stdio.h>
#include <queue>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxv=100010;
vector<int> Adj[maxv];
int n,m;
int indegree[maxv];
int topo(){
queue<int> q;
int sum=0,money=0;
int num[maxv]={0};//记录对应编号的工资
for(int i=1;i<=n;i++){
if(indegree[i]==0){
num[i]=888;
money+=num[i];
q.push(i);
}
}
while(!q.empty()){
int top=q.front();
q.pop();
for(int i=0;i<Adj[top].size();i++){
int v=Adj[top][i];
indegree[v]--;
if(indegree[v]==0){
q.push(v);
num[v]=num[top]+1;
money+=num[v];
}
}
sum++;
}
if(sum==n){
return money;
}else{
return -1;
}
}
int main(){
int u,v;
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=0;i<=n;i++){//初始化
Adj[i].clear();
}
memset(indegree,0,sizeof(indegree));
for(int i=0;i<m;i++){
scanf("%d%d",&u,&v);
Adj[v].push_back(u);//反向拓扑
indegree[u]++;
}
int ans=topo();
if(ans==-1){
printf("-1\n");
}else{
printf("%d\n",ans);
}
}
return 0;
}
来源:CSDN
作者:嘻嘻哈哈,
链接:https://blog.csdn.net/huantingyizhan/article/details/104531064