暑假训练 Reward HDU - 2647 拓扑排序

题目描述:
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<cstdio>
#include<string.h>
#define max(a, b) a > b? a : b

struct node
{
    int low;             //比他工资低的人数
    int high[20];        //比他工资高的人
    int num;             //比他工资高的人数
    int ans;             //他的工资
}p[10005];

int topo(int n)
{
    int k = 0, t, f;
    while(k < n)
    {
        f = 0;
        for(int i = 1; i <= n; i++)
        {
            if(p[i].low == 0)
            {
                p[i].low--;
                k++;
                t = p[i].ans + 1;
                for(int j = 0; j < p[i].num; j++)
                {
                    p[p[i].high[j]].low--;
                    p[p[i].high[j]].ans = max(p[p[i].high[j]].ans, t);       //重点,找出他必须的最大的工资。。。
                }
                f = 1;
                break;
            }
        }
        if(f == 0)return 0;
    }
    return 1;
}

int main()
{
    int m, n, a, b;
    while(~scanf("%d%d", &n, &m))
    {
        memset(p, 0, sizeof p);
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d", &a, &b);
            p[a].low++;
            p[b].high[p[b].num++] = a;
        }
        int ans = topo(n);
        if(ans == 0)printf("-1\n");
        else
        {
            ans = 888 * n;
            for(int i = 1; i <= n; i++)
                ans += p[i].ans;
            printf("%d\n", ans);
        }
    }
    return 0;
}

因为开不起临界矩阵,原想利用vector来解决,可是最后还是写崩了,无奈只好借用互联网的力量了>_<

猜你喜欢

转载自blog.csdn.net/wbl1970353515/article/details/82831999