HDU 2647Reward(拓扑排序)

探讨了一道经典的奖励分配问题,通过使用拓扑排序解决工人间的奖励需求冲突,确保每位工人的奖励不低于指定数额的同时,使总花费最小。文章分享了从问题理解到算法实现的心得,并介绍了临接表和拓扑排序的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
 

Source

总结:

这他吗是一道血泪题啊!思路搞清楚之后很快就完成了,最后debug要死了都,才发现问题出在数组的大小没开对,这道题学习了两个新的知识,一个是拓扑排序,一个是临接表,虽然这两个以前都高过,但是其实一直没有搞的特别清楚,果然知识点还是要一个一个稳扎稳打的攻啊
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn=10000+10;
const int maxm=20000+10;
int n,m,frist[maxn],nex[maxn],u[maxm],v[maxm],in[maxn],vis[maxn];
void init()
{
    for(int i=0;i<n+10;i++) frist[i]=-1;
    for(int i=0;i<n+10;i++) in[i]=0;
    for(int i=0;i<n+10;i++) vis[i]=0;
}
int topsort()
{
    int sum=0;
    int temp=0;
    int tot=0;
    queue <int> q;
    while(1)
    {
        for(int i=1;i<=n;i++)
            if(vis[i]==0&&!in[i]) {q.push(i); sum+=888+temp;tot++;vis[i]=1;}
        if(tot>=n) return sum;
        if(q.empty()) return -1;
        while(!q.empty())
        {
            int top=q.front();
            q.pop();
            int k=frist[top];
            while(k!=-1)
            {
                in[v[k]]--;
                k=nex[k];
            }
        }
        temp++;
    }
    
}



int main()
{
    //freopen("/Users/zhangjiatao/Documents/暑期训练/input.txt","r",stdin);
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        int ans;
        for(int i=1;i<=m;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            u[i]=b;//from u to v;
            v[i]=a;
            nex[i]=frist[u[i]];
            frist[u[i]]=i;
            in[v[i]]++;
        }
       ans=topsort();
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值