Solving the problem: finding the longest road in a direction-free graph, simple dynamic programming
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include < algorithm> #include <vector> #include <cmath> #define LL long longusing namespace Std;const int maxn = 100000 + 10;const int maxm = 1000000 + 10;const LL INF =-1 * 20000 * 100000-10;struct edge{int to, next;} Edge[maxm];int tot, HEAD[MAXN]; LL W[MAXN]; LL Dp[maxn];int OUT[MAXN], vis[maxn];int N, m;void init () {tot = 0; Memset (Head,-1, sizeof (head)); memset (w, 0, sizeof (w)); Memset (DP, INF, sizeof (DP)); memset (Vis, 0, sizeof (VIS)); memset (out, 0, sizeof);} void Addedge (int u, int v) {edge[tot].to = v; Edge[tot].next = Head[u]; Head[u] = tot++;} int dfs (int u) {//cout << u << endl; if (Vis[u]) return dp[u]; Vis[u] = 1; for (int i=head[u];i!=-1;i=edge[i].next) {int v = edge[i].to; Dp[u] = max (Dp[u], (LL) Dfs (v)); } if (head[u] = = 1) return dp[u] = W[u]; else return dp[u] = (Dp[u] + w[u]); return dp[u];} int main () {while (scanf ("%d%d", &n, &m)!=eof) {init (); for (int i=1;i<=n;i++) scanf ("%d", &w[i]); int u, v; for (int i=1;i<=m;i++) {scanf ("%d%d", &u, &v); Addedge (V, u); out[u]++; } LL ans = INF; for (int i=1;i<=n;i++) cout << dp[i] << "; for (int i=1;i<=n;i++) if (!out[i]) ans = max (ans, (LL) DFS (i)); printf ("%d\n", ans); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU 3249 Test for job (longest, DP) on a forward-free graph