程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> HDU 2647 Reward(圖論-拓撲排序)

HDU 2647 Reward(圖論-拓撲排序)

編輯:C++入門知識

HDU 2647 Reward(圖論-拓撲排序)


Reward


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 曾是驚鴻照影來
Recommend yifenfei

題目大意:

n個人,m條邊,每條邊a,b 表示a比b的工資要多,每個人的工資至少888,問滿足關系的工資總和至少多少?如果出現關系矛盾,輸出-1


解題思路:

根據工資關系建立拓撲圖,0入度的人工資從888開始,一層一層,逐漸增加工資,若最後還有人入度不為0,則出現矛盾。


參考代碼:

#include 
#include 
#include 
#include 
using namespace std;

const int MAXN = 10010;
int inDegree[MAXN], ans, cnt, n, m;
vector child[MAXN];

struct State {
    int reward, node;
    State(int _reward, int _node) : reward(_reward), node(_node) {}
};
queue q;

void init() {
    memset(inDegree, 0, sizeof(inDegree));
    for (int i = 0; i <= n; i++) {
        child[i].clear();
    }
    ans = cnt = 0;
    while (!q.empty()) q.pop();
}

void input() {
    for (int i = 0; i < m; i++) {
        int a, b;
        cin >> a >> b;
        inDegree[a]++;
        child[b].push_back(a);
    }
}

void work() {
    for (int i = 1; i <= n; i++) {
        if (inDegree[i] == 0) {
            q.push(State(888, i));
            cnt++;
        }
    }
    while (!q.empty()) {
        State cur = q.front();
        q.pop();

        ans += cur.reward;

        for (int i = 0; i < child[cur.node].size(); i++) {
            inDegree[child[cur.node][i]]--;
            if (inDegree[child[cur.node][i]] == 0) {
                q.push(State(cur.reward+1, child[cur.node][i]));
                cnt++;
            }
        }
    }
}

void output() {
    if (cnt == n) {
        cout << ans << endl;
    } else {
        cout << -1 << endl;
    }
}

int main() {
    ios::sync_with_stdio(false);
    while (cin >> n >> m) {
        init();
        input();
        work();
        output();
    }
    return 0;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved