Reward acm入门 day2---拓扑排序 第1题

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.

题意:使用最少的资金给每个人发工资且要求有等级,所以每次高一个level就多加1块,使用拓扑排序就能解决,但注意这题重要的一点是等级并列的情况,也就是工资相同。

拓扑排序算法要求图中存在入度为0的点,也就是不能是环或圈

拓扑排序算法过程是:1.设置一个数组保存每个点的入度
2.找到一个入度为0的点,将他的边删除,同时这条边所指向的另一个点入度-1
3.删除后,肯定会出现入度为0的点,因此重复1,2.

而这道题需要算出最少工资,因此再设置一个数组来记录每个员工的工资,然后在删除边时,让当前点所指向的点(相邻点)的工资等于自己+1

Sample Input

2 1
1 2
2 2
1 2
2 1

Sample Output

1777
-1
#include <stdio.h>
#include <vector>
#include <queue>
const int maxn = 20000 + 10;
using namespace std;
int in[maxn];
vector<int> gra[maxn];
int sum[maxn];

int tou(int n)
{
    int u;
    queue<int> q;
    //1.找度数为0的点,放入队列
    for(int j=1;j<=n;j++)
    {
        if(in[j]==0)
        {
            u=j;
            sum[u]=888;
            in[j]--;//同时记得对度数为0的点标记,保证不会被重复遍历
            q.push(j);
        }
    }
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(size_t j=0;j<gra[u].size();j++)
        {
            int to=gra[u][j];
            in[to]--;
            if(in[to]==0)
            {
                q.push(to);
                in[to]--;
                //让当前点所指向的点(相邻点)的工资等于自己+1    
                sum[to]=sum[u]+1;
            }
        }
    }
    int s=0;
    for(int i=1;i<=n;i++)
    {
        if(in[i]!=-1) return -1;
        s+=sum[i];
    }
    return s;
}

void init(int n)
{
    for (int i = 0; i <= n; i++)
    {
        gra[i].clear();
        in[i] = 0;
    }
}
int main()
{
    int n, m;
    while (scanf("%d %d", &n, &m) != EOF)
    {
        init(n);
        for (int i = 0; i < m; i++)
        {
            int u, t;
            scanf("%d %d", &u, &t);
            gra[t].push_back(u);
            in[u]++;
        }
        int s=tou(n);
        printf("%d\n",s);


    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值