Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9882 Accepted Submission(s): 3153
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
Author
dandelion
Source
曾是惊鸿照影来
Recommend
yifenfei | We have carefully selected several similar problems for you: 3342 1811 2094 2729 1596
拓扑图分层,位于第0层的可以获得888奖金,位于第1层的可以获得889奖金,依次类推.
最终的奖金总数就是888*N+(所有节点层数总和).
程序实现基于BFS和连接表
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1e4+5;
const int maxm = 2e4+5;
int i,j,k,n,m,a,b,cnt;
struct node{
int in,dep,head;
}point[maxn];
struct Node{
int to,next;
}edge[maxm];
void add_edge(int i, int u, int v){
edge[i].to = v;
edge[i].next = point[u].head;
point[u].head = i;
point[v].in++;
}
void init(){
memset(point,0,sizeof(point));
for (i=1; i<=m; i++) {
scanf("%d%d",&a,&b);
add_edge(i,b,a);
}
cnt = 0;
}
bool tuopu(){
int sum = 0;
int u,v;
queue<int>que;
for (i=1; i<=n; i++) if (point[i].in==0) que.push(i);
while (!que.empty()){
u = que.front();
que.pop();
sum++;
cnt += point[u].dep;
for (i=point[u].head; i!=0; i=edge[i].next) {
v = edge[i].to;
if (--point[v].in==0) {
que.push(v);
point[v].dep = point[u].dep+1;
}
}
}
return sum==n;
}
int main(){
while (~scanf("%d%d",&n,&m)){
init();
printf("%d\n",tuopu()?888*n+cnt:-1);
}
return 0;
}