您的位置:首页 > 运维架构

poj--3249 Test for Job(topsort + dp)

2016-09-23 20:48 344 查看
Test for Job

题解

DAG图上的单源最短路径。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn = 100000 + 5;
const int maxe = 1000000 + 5;
const int inf  = 0x7f7f7f7f;

int n, m, tot;
int head[maxn], val[maxn];
int out[maxn], in[maxn];
int dp[maxn], q[maxn];  // dp[i] means that the maximum profit of i city;
struct Edge{
int to, next;
}edge[maxe];

void init(){
tot = 0;
memset(head, -1, sizeof(head));
memset(out, 0, sizeof(out));
memset(in, 0, sizeof(in));
}

void addEdge(int u, int v){
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}

void topsort(){
// queue
int h = 0, t = 0;
for(int i = 1; i <= n; ++i) if(in[i] == 0) q[t++] = i;
while(h < t){
int u = q[h++];
for(int i = head[u]; ~i; i = edge[i].next){
int v = edge[i].to;
dp[v] = max(dp[v], dp[u] + val[v]);
if(--in[v] == 0) q[t++] = v;
}
}

}

int main(){
#ifdef EXMY
freopen("data.in", "r", stdin);
#endif // EXMY

// 10864K   2094MS
while(~scanf("%d %d", &n, &m)){
init();
for(int i = 1; i <= n; ++i) scanf("%d", val + i);
int u, v;
for(int i = 1; i <= m; ++i){
scanf("%d %d", &u, &v);
addEdge(u, v);
in[v]++;
out[u]++;
}
for(int i = 1; i <= n; ++i) dp[i] = -inf;
for(int i = 1; i <= n; ++i) if(in[i] == 0) dp[i] = val[i];
topsort();
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj graph topsort dp