Http://acm.hdu.edu.cn/showproblem.php?
pid=1224
The basis for finding the longest path and recording paths.
Feel Dijstra than SPFA easy to use, WA two times.
#include <stdio.h> #include <algorithm> #include <set> #include <map> #include <vector># Include <math.h> #include <string.h> #include <queue> #define LL long long#define _ll __int64using namespace Std;const int INF = 0x3f3f3f3f;const int maxn = 110;int n,m;int inter[maxn];int map[maxn][maxn];int dis[maxn],vi S[maxn];int pre[maxn];void Debug () {for (int i = 1; I <= n+1; i++) {for (int j = 1; J <= N+1; j + +) printf ("%d", Map[i][j] );p rintf ("\ n");}} void Spfa () {queue <int> que;memset (vis,0,sizeof (Vis)), memset (dis,-inf,sizeof (DIS)), memset (pre,-1,sizeof (pre ));d is[1] = 0;vis[1] = 1;que.push (1), while (!que.empty ()) {int u = que.front (); Que.pop (); Vis[u] = 0;for (int v = 1; v <= n +1; v++) {if (Map[u][v] >= 0&& dis[v] < Dis[u] + Map[u][v]) {Dis[v] = Map[u][v] + dis[u];p re[v] = u;if (!vis[v]) {Vis [V] = 1;que.push (v);}}}} void output () {int t = n+1;int Ans[maxn];int cnt = 0;while (pre[t]! =-1) {ans[cnt++] = T;t = Pre[t];} printf ("1"); for (int i = CNt-1; I >= 1; i--) printf ("->%d", Ans[i]);p rintf ("->1\n");} int main () {int test;int u,v;scanf ("%d", &test), for (int item = 1; item <= test; item++) {if (item! = 1) printf ("\ n"); SCA NF ("%d", &n), for (int i = 1; I <= n; i++) scanf ("%d", &inter[i]); inter[n+1] = 0;memset (map,-1,sizeof (MAP)); scanf ("%d", &m), while (m--) {scanf ("%d%d", &u,&v); MAP[U][V] = Inter[v];} SPFA ();p rintf ("Case%d#\n", item);p rintf ("Points:%d\n", dis[n+1]);p rintf ("Circuit:"); output ();} return 0;}
To find the longest road is a bit like the longest ascending sub-sequence, and then take the longest ascending sub-sequence of water.
#include <stdio.h> #include <algorithm> #include <set> #include <map> #include <vector># Include <math.h> #include <string.h> #include <queue> #define LL long long#define _ll __int64using namespace Std;const int INF = 0x3f3f3f3f;const int maxn = 110;int n,m;int inter[maxn];int map[maxn][maxn];int dis[maxn],vi S[maxn];int pre[maxn];int dp[maxn];void Solve () {memset (pre,-1,sizeof (pre)), for (int i = 1; I <= n+1; i++) {Dp[i] = inter[ i];for (int j = 1; j < I; J + +) {if (Map[j][i] >= 0 && dp[i] < Dp[j] + Map[j][i]) {dp[i] = Dp[j] + map[j][i]; Pre[i] = j;}}} printf ("Points:%d\n", dp[n+1]);p rintf ("Circuit:"); int ans[maxn],cnt = 0;int T = n+1;while (t! =-1) {ans[cnt++] = T;t = P RE[T];} ANS[CNT] = 1;for (int i = cnt; I >= 1; i--) printf ("%d->", Ans[i]);p rintf ("%d\n", 1);} int main () {int test;int u,v;scanf ("%d", &test), for (int item = 1; item <= test; item++) {if (item! = 1) printf ("\ n"); SCA NF ("%d", &n), for (int i = 1; I <= n; i++) scanf ("%d ", &inter[i]); inter[n+1] = 0;memset (map,-1,sizeof (MAP)), scanf ("%d ", &m), while (m--) {scanf ("%d%d ", &u, &V); MAP[U][V] = Inter[v];} printf ("Case%d#\n", item); Solve ();} return 0;}
HDU 1224 free DIY tour (longest road/DP)