Reward

Reward

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 3
描述
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.
输入
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.
输出
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.
样例输入
2 1
1 2
2 2
1 2
2 1
样例输出
1777

-1

思路:拓扑排序判断环路。。。

//nyoj Reward

#include <stdio.h>
#include <vector>
#include <string.h>

using namespace std;

int indegree[10001], n;
vector<int> map[10001], out;

int topsort()
{
    int i, j, cnt = n, num, sum = 0, pay = 888, ts;
    while(cnt > 0)
    {
        num = 0;
        out.clear();
        for(i = 1; i <= n; i++)
        {
            if(indegree[i] == 0)
            {
                out.push_back(i);
                indegree[i] = -1;
                num++;
            }
        }
        if(num == 0)
        {
            return -1;
        }
        else
        {
            cnt -= num;
            sum += (pay*num);
            pay++;
            for(i = 0; i < num; i++)
            {
                ts = map[out[i]].size();
                for(j = 0; j < ts; j++)
                {
                    indegree[map[out[i]][j]]--;
                }
            }
        }
    }
    return sum;
}

int main()
{
    int m, i,  sp, ep, ans;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        for(i = 0; i < 10001; i++)
        {
            map[i].clear();
        }
        memset(indegree, 0, sizeof(indegree));
        for(i = 0; i < m; i++)
        {
            scanf("%d%d", &sp, &ep);
            indegree[sp]++;
            map[ep].push_back(sp);
        }
        ans = topsort();
        if(ans == -1)
        {
            printf("-1\n");
        }
        else
        {
            printf("%d\n", ans);
        }
    }
    return 0;
}


你可能感兴趣的:(网络)