您的位置:首页 > 其它

HDU 2647 Reward

2015-05-03 09:58 239 查看


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
简单拓扑排序
#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 10005;
int n, m, x, y, v[maxn], f[maxn];
vector<int> tree[maxn];

int main()
{
    while (scanf("%d%d", &n, &m) != EOF)
    {
        queue<int> p;
        memset(v, 0, sizeof(v));
        memset(f, 0, sizeof(f));
        for (int i = 1; i <= n; i++) tree[i].clear();
        while (m--)
        {
            scanf("%d%d", &x, &y);
            v[x]++;
            tree[y].push_back(x);
        }
        for (int i = 1; i <= n; i++) if (!v[i]) { p.push(i); f[i] = 888; }
        while (!p.empty())
        {
            int q = p.front();    p.pop();
            for (int i = 0; i < tree[q].size(); i++)
            {
                v[tree[q][i]]--;
                if (!v[tree[q][i]])
                {
                    p.push(tree[q][i]);
                    f[tree[q][i]] = f[q] + 1;
                }
            }
        }
        int tot = 0;
        for (int i = 1; i <= n; i++) 
            if (f[i]) tot += f[i]; else { tot = -1; break; }
        printf("%d\n", tot);
    }
    return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: