Reward
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4306 Accepted Submission(s): 1318
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
一开始我以为是差分约束,然后写了下发现超时,无奈去看了下发现是topo排序,然后改正后就AC了
#include <map>
#include <set>
#include <list>
#include <stack>
#include <vector>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10010;
const int M = 20010;
int tot, n, m;
int head[N];
int num[N];
int in_degree[N];
struct node
{
int next;
int to;
}edge[M];
void addedge(int from, int to)
{
edge[tot].to = to;
edge[tot].next = head[from];
head[from] = tot++;
}
bool topo_sort()
{
queue <pair<int, int> > du;
memset (num, 0, sizeof(num) );
int cnt = 0;
while ( !du.empty() )
{
du.pop();
}
for (int i = 1; i <= n; ++i)
{
if (!in_degree[i])
{
du.push( make_pair(0, i) );
num[i] = 0;
}
}
while ( !du.empty() )
{
pair<int, int> tmp = du.front();
du.pop();
cnt++;
int u = tmp.second;
int res = tmp.first;
for (int i = head[u]; ~i; i = edge[i].next)
{
in_degree[edge[i].to]--;
if ( !in_degree[edge[i].to] )
{
num[edge[i].to] = res + 1;
du.push( make_pair(res + 1, edge[i].to) );
}
}
}
return cnt == n;
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
int u, v;
memset (head, -1, sizeof(head) );
memset (in_degree, 0, sizeof(in_degree) );
tot = 0;
for (int i = 0; i < m; ++i)
{
scanf("%d%d", &u, &v);
addedge(v, u);
in_degree[u]++;
}
bool flag = topo_sort();
if (!flag)
{
printf("-1\n");
continue;
}
int ans = 0;
for (int i = 1; i <= n; ++i)
{
ans += num[i];
}
ans += 888 * n;
printf("%d\n", ans);
}
return 0;
}