HDU - 2647 Reward 拓扑排序
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
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cstring> #include<string> #include<stack> using namespace std; typedef long long LL; #define MAXN 10006 #define N 100 /* 报酬 已知所有人之间报酬的大小关系,最小值为888要求求出满足要求的报酬解中最小的。 要求有满足条件的关系组合 可以用有向图拓扑排序的长度为n来判断 注意在拓扑排序时,要注意从小到大排序,更新要入队的结点,同时确保满足前面的限制 */ int num[MAXN], n, m, cnt = 0; vector<int> E[MAXN]; int in[MAXN]; void Topsort() { queue<int> q; for (int i = 1; i <= n; i++) { if (in[i] == 0) q.push(i); } while (!q.empty()) { int t = q.front(); cnt++; q.pop(); for (int i = 0; i < E[t].size(); i++) { if (--in[E[t][i]] == 0) { q.push(E[t][i]); num[E[t][i]] = max(num[E[t][i]], num[t] + 1); } } } } int main() { while (scanf("%d%d", &n, &m) != EOF) { int a, b, sum = 0; for (int i = 1; i <= n; i++) E[i].clear(); memset(num, 0, sizeof(num)); memset(in, 0, sizeof(in)); for (int i = 0; i < m; i++) { scanf("%d%d", &a, &b); in[a]++; E[b].push_back(a); } cnt = 0; Topsort(); if (cnt == n) { for (int i = 1; i <= n; i++) sum += (num[i]); printf("%d\n", 888 * n + sum); } else printf("-1\n"); } }