Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 6399 Accepted Submission(s): 1974
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
Author
dandelion
Source
思路:拓扑排序的简单应用,根据题目的要求,可以知道所求的最小的花费是逆拓扑排序的结果,并且对于在同一层的节点,工资应该是相同的,注意这里要用邻接表,用邻接矩阵会爆内存。
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int maxn=10000+5;
vector<int> vec[maxn] ;
int degree[maxn];
void toposort(int n){
int cnt=0;
int ans=0;
int num=888;
queue<int> Q;
while(!Q.empty()) Q.pop();
bool ok=true;
while(cnt<n){
int ttmp=0;
for(int i=1;i<=n;i++){
if(degree[i]==0){
ttmp++;
Q.push(i);
degree[i]=-1;
}
}
if(ttmp==0){
ok=false;
break;
}
ans+=num*ttmp;
num++;
cnt+=ttmp;
while(!Q.empty()){
int tmp=Q.front();
Q.pop();
for(int j=0;j<vec[tmp].size();j++){
int tt=vec[tmp][j];
degree[tt]--;
}
}
}
if(ok)
cout<<ans<<endl;
else cout<<"-1"<<endl;
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m)==2){
for(int i=0;i<maxn;i++){
vec[i].clear();
}
memset(degree,0,sizeof(degree));
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
vec[b].push_back(a);
degree[a]++;
}
toposort(n);
}
return 0;
}