浙江财经大学
信息管理与工程学院

HDU 2647 Reward(拓扑排序)

本文由 Ocrosoft 于 2016-07-15 8:49:42 发表

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7149    Accepted Submission(s): 2230

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
 

Solution

发工资,n个人,m个要求,对于要求u v,表示u的工资要比v的高。由于要求总工资最小,那么就是每次工资加1.

反向建边,同一轮的人都是不冲突的,工资一样,过了一轮工资加1.

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <list>
#include <stack>
#include <string>
#include <vector>
#include <cstring>
#include <cctype>
#include <queue>
#include <set>
#include <map>
#include <climits>
#define ms(a) memset(a,0,sizeof(a))
using namespace std;

int n,m,t,tt;
vector<int> v[100001];
int in[100001];
vector<int> ans;
queue<int> q;
void toposort()
{
    ans.clear();
    int sum=0,now=888,cnt=0;
    int qs=q.size();
    while(!q.empty())
    {
        while(qs--)
        {
            t=q.front(),q.pop();
            sum+=now;
            cnt++;
            ans.push_back(t);
            for(int i=0,vs=v[t].size(); i<vs; i++)
            {
                in[v[t][i]]--;
                if(!in[v[t][i]])q.push(v[t][i]);
            }
        }
        qs=q.size();
        now++;
    }
    if(cnt==n)printf("%d\n",sum);
    else printf("-1\n");
}
int main()
{
    while(cin>>n>>m)
    {
        ms(in);
        for(int i=1; i<=n; i++)v[i].clear();
        for(int i=0; i<m; i++)
            scanf("%d%d",&t,&tt),v[tt].push_back(t),in[t]++;
        for(int i=1; i<=n; i++)if(!in[i])q.push(i);
        toposort();
    }
    return 0;
}

 

欢迎转载,请保留出处与链接。Ocrosoft » HDU 2647 Reward(拓扑排序)

点赞 (0)or拍砖 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址