poj 3249 Test for Job (拓撲排序)

題目鏈接:http://poj.org/problem?id=3249


給出每個點的價值以及有向邊,然後求所有路徑中,價值和最大的路徑,問最大價值爲多少。

路徑要求從入度爲0的點出發,出度爲0的點停止,價值可能爲負值。

直接用拓撲排序,並不斷向後累加每個點在價值,最後找出度爲0的點的價值就可以了。


#include <cstdio>
#include <queue>
#include <vector>

using namespace std;
const int maxn = 100005;
const int oo = 1 << 31;

vector<int> G[maxn];

int weight[maxn];
int sumw[maxn];
int indeg[maxn];
int outdeg[maxn];

void topo(int n);

int main() {
    int n, m, from, to;
//    freopen("1.in", "r", stdin);
    while (scanf("%d%d", &n, &m) != EOF) {
        for (int i = 1; i <= n; i ++) {
            scanf("%d", weight + i);
        }
        for (int i = 0; i < m; i ++) {
            scanf("%d%d", &from, &to);
            G[from].push_back(to);
            outdeg[from] ++;
            indeg[to] ++;
        }
        topo(n);
        for (int i = 1; i <= n; i ++) {
            G[i].clear();
            indeg[i] = outdeg[i] = 0;
        }
    }
    return 0;
}

void topo(int n) {
    queue<int> que;
    for (int i = 1; i <= n; i ++) {
        if(indeg[i] == 0) {
            que.push(i);
            sumw[i] =weight[i];
        }
        else {
            sumw[i] = -oo;
        }
    }
    while (!que.empty()) {
        int cur = que.front();
        que.pop();
        for (int i = 0, qs = G[cur].size(); i < qs; i ++) {
            int to = G[cur][i];
            sumw[to] = max(sumw[to], sumw[cur] + weight[to]);
            indeg[to] --;
            if(indeg[to] == 0) {
                que.push(to);
            }
        }
    }
    int ans = -oo;
    for (int i = 1; i <= n; i ++) {
        if(outdeg[i] == 0) {
            if(ans < sumw[i]) {
                ans = sumw[i];
            }
        }
        sumw[i] = -oo;
    }
    printf("%d\n", ans);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章