题目连接
http://acm.hdu.edu.cn/showproblem.php?pid=2647
Reward
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 \leq 10000,m \leq 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
简单的拓扑排序。。
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<map>
using std::cin;
using std::cout;
using std::endl;
using std::find;
using std::sort;
using std::map;
using std::pair;
using std::queue;
using std::vector;
using std::multimap;
#define pb(e) push_back(e)
#define sz(c) (int)(c).size()
#define mp(a, b) make_pair(a, b)
#define all(c) (c).begin(), (c).end()
#define iter(c) decltype((c).begin())
#define cls(arr,val) memset(arr,val,sizeof(arr))
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define tr(c, i) for (iter(c) i = (c).begin(); i != (c).end(); ++i)
const int N = ;
typedef unsigned long long ull;
struct Node {
int vex, val;
Node(int i = , int j = ) :vex(i), val(j) {}
};
struct TopSort {
vector<int> G[N];
int topNum, inq[N];
inline void init(int n) {
topNum = ;
cls(inq, );
rep(i, n) G[i].clear();
}
inline void built(int m) {
int a, b;
rep(i, m) {
scanf("%d %d", &a, &b);
--a, --b;
inq[a]++;
G[b].push_back(a);
}
}
inline void bfs(int n) {
int ans = ;
queue<Node> q;
rep(i, n) {
if (!inq[i]) { q.push(Node(i, )); topNum++; }
}
while (!q.empty()) {
Node t = q.front(); q.pop();
ans += t.val;
rep(i, sz(G[t.vex])) {
if (--inq[G[t.vex][i]] == ) q.push(Node(G[t.vex][i], t.val + )), topNum++;
}
}
printf("%d\n", topNum == n ? ans : -);
}
}work;
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int n, m;
while (~scanf("%d %d", &n, &m)) {
work.init(n);
work.built(m);
work.bfs(n);
}
return ;
}