Codeforces Round #374 (Div. 2) 721C Journey DAG上DP

DAG 上动态规划

跑一遍dfs 转移状态,记录路径


#include

using namespace std;

const int maxn = 5007, INF = 0x7f7f7f7f;

int n, m, len;
int edge[maxn][3];
int f[maxn][maxn];
int g[maxn][maxn];
int route[maxn];


int main() {
    scanf("%d %d %d", &n, &m, &len);

    for(int i = 1; i <= m; ++i) {
        scanf("%d %d %d", &edge[i][0], &edge[i][1], &edge[i][2]);
    }

    for(int i = 1; i <= n; ++i) {
        for(int j = 1; j <= n; ++j) {
            f[i][j] = len+1;
        }
    }

    int ans = 0;
    f[1][1] = 0;
    for(int i = 2; i <= n; ++i) {
        for(int j = 1; j <= m; ++j) {
            int u = edge[j][0];
            int v = edge[j][1];
            int t = edge[j][2];
            if(f[i-1][u] + t < f[i][v]) {
                f[i][v] = f[i-1][u] + t;
                g[i][v] = u;
            }
        }
        if(f[i][n] <= len) {
            ans = i;
        }
    }

    printf("%d\n", ans);
    int u = n;
    for(int i = ans; i >= 1; --i) {
        route[i] = u;
        u = g[i][u];
    }
    for(int i = 1; i <= ans; ++i) {
        printf("%d ", route[i]);
    }

    return 0;
}


你可能感兴趣的:(codefoces,DP)