﻿HDU 2647 Reward(拓扑排序)-Ocrosoft

# Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7149    Accepted Submission(s): 2230

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

Solution

```#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <list>
#include <stack>
#include <string>
#include <vector>
#include <cstring>
#include <cctype>
#include <queue>
#include <set>
#include <map>
#include <climits>
#define ms(a) memset(a,0,sizeof(a))
using namespace std;

int n,m,t,tt;
vector<int> v[100001];
int in[100001];
vector<int> ans;
queue<int> q;
void toposort()
{
ans.clear();
int sum=0,now=888,cnt=0;
int qs=q.size();
while(!q.empty())
{
while(qs--)
{
t=q.front(),q.pop();
sum+=now;
cnt++;
ans.push_back(t);
for(int i=0,vs=v[t].size(); i<vs; i++)
{
in[v[t][i]]--;
if(!in[v[t][i]])q.push(v[t][i]);
}
}
qs=q.size();
now++;
}
if(cnt==n)printf("%d\n",sum);
else printf("-1\n");
}
int main()
{
while(cin>>n>>m)
{
ms(in);
for(int i=1; i<=n; i++)v[i].clear();
for(int i=0; i<m; i++)
scanf("%d%d",&t,&tt),v[tt].push_back(t),in[t]++;
for(int i=1; i<=n; i++)if(!in[i])q.push(i);
toposort();
}
return 0;
}
```