POJ 3249 Test for Job (拓扑排序+dp)

原题地址;http://poj.org/problem?id=3249
题意:给出n个点,m条边,每个点都提供了相对的点权值,然后给出相连着的边,问最大利润值。
思路:在拓扑排序的时候同步更新dp数组就行了.
注意:顶点权值可以取负就行了.

#include <cmath>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <cctype>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define MOD 1e9+7
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define CLR(x,y) memset((x),y,sizeof(x))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e6 + 5;
int head[maxn], tot, n, m;
struct node {
    int u, v, nxt;
} e[maxn * 10];
void add_edge(int u, int v) {
    e[tot].u = u;
    e[tot].v = v;
    e[tot].nxt = head[u];
    head[u] = tot++;
}
int arr[maxn];
int into[maxn], out[maxn];
int dp[maxn];
queue<int>q;
void toposort() {
    for(int i = 1; i <= n; i++) {
        if(into[i] == 0) {
            dp[i] = arr[i];
            q.push(i);
        }
    }
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        for(int i = head[u]; ~i; i = e[i].nxt) {
            int v = e[i].v;
            if(into[v] == 0) continue;
            dp[v] = max(dp[v], dp[u] + arr[v]);
            into[v]--;
            if(into[v] == 0) q.push(v);
        }
    }

}
int main() {
    while(~scanf("%d%d", &n, &m)) {
        tot = 0;
        CLR(head, -1);
        CLR(into, 0);
        CLR(out, 0);

        while(!q.empty()) q.pop();
        for(int i = 1; i <= n; i++) scanf("%d", &arr[i]);
        for(int i = 1; i <= m; i++) {
            int u, v;
            scanf("%d%d", &u, &v);
            add_edge(u, v);
            into[v]++;
            out[u]++;
        }
        for(int i=1;i<=n;i++){
            dp[i]=-INF;
        }
        toposort();
        int ans = -INF;
        for(int i = 1; i <= n; i++) {
            if(out[i]==0)ans = max(ans, dp[i]);
        }
        printf("%d\n", ans);
    }
    return 0;
}
    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/yiqzq/article/details/81348086
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞