zoukankan      html  css  js  c++  java
  • HDU2647Reward (拓扑排序)

    Reward

    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

    思路,构建反图,将工资高的放在后面,好比树,越深的工资越高,这里不算u->v,而是v->u;

    无解当前仅当形成环,n个节点没有走完一遍。

    代码:

    #include <iostream>
    #include<vector>
    #include<queue>
    using namespace std;
    const int M=100005;
    vector<int>G[M];
    int in[M],num[M];
    void topsort(int n){
        int ans=0;
        int cnt=0;//统计是否形成环,n个点全部输出则不可能形成环
        queue<int>que;
        //将入度为0 的压入队列
        for (int i = 1; i <= n; i++){
            if(in[i]==0)que.push(i);
        }
        while (!que.empty()){
            cnt++;
            int u=que.front();
            que.pop();
            ans+=num[u];
            for (int i = 0; i <G[u].size(); i++){
                int v = G[u][i];
                if(--in[v]==0)que.push(v);
                num[v]=num[u]+1;
            }
        }
        if(cnt!=n)
            cout<<-1<<endl;
        else{
            cout<<ans<<endl;
        }
    }
    
    int main(){
        int n,m,u,v;
        while (cin>>n>>m){
            //初始化
            for (int i = 1; i <= n; i++){
                G[i].clear();
                num[i]=888;
                in[i]=0;
            }
            while (m--){
                cin>>u>>v;
                G[v].push_back(u);
                in[u]++;
            }
            topsort(n);
        }
    }
    View Code

    因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/14305699.html

  • 相关阅读:
    PHP开发APP接口(九)
    C#深入理解类型
    C#从委托、lambda表达式到linq总结
    C# ==和Equals()
    C# 泛型
    C# Reflection
    原声JS网络请求
    JavaScript预编译
    泛型初探
    C#内存分配
  • 原文地址:https://www.cnblogs.com/BlairGrowing/p/14305699.html
Copyright © 2011-2022 走看看