UVA 116 Unidirectional TSP (多階段決策問題,DP解決)

來源:互聯網
上載者:User

紫書上的例題,我們令dp【i】【j】為從表格i,j點開始到最後一列的最小花費。由於還需要輸出字典序,所以每一個點我們都要得到它能到下一列哪三行,對於第0行和第n-1行特殊處理,然後將這三行排序,從最小的開始檢驗,如果符合條件則更新,這樣就可以處理相等的情況,並且字典序是最小的。

代碼如下:

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<vector>#include<string>#include<set>#include<map>#include<stack>#include<queue>using namespace std;#define eps 1e-7const int maxn = 105;const int maxm = 10005;const int INF = 0x3f3f3f3f;int n, m;int dp[maxn][maxn], nx[maxn][maxn], G[maxn][maxn];int main() {#ifndef ONLINE_JUDGE    freopen("in.txt", "r", stdin);#endif // ONLINE_JUDGE    while(scanf("%d%d", &n, &m) != EOF) {        for(int i = 0; i < n; i++) {            for(int j = 0; j < m; j++) {                scanf("%d", &G[i][j]);            }        }        for(int i = 0; i < n; i++) {            dp[i][m - 1] = G[i][m - 1];        }        for(int j = m - 2; j >= 0; j--) {            for(int i = 0; i < n; i++) {                dp[i][j] = INF;                int row[3] = {i - 1, i, i + 1};                if(i == 0)                    row[0] = n - 1;                if(i == n - 1)                    row[2] = 0;                sort(row, row + 3);                for(int k = 0; k < 3; k++) {                    int d = dp[row[k]][j + 1] + G[i][j];                    if(dp[i][j] > d) {                        dp[i][j] = d;                        nx[i][j] = row[k];                    }                }            }        }        int Min = INF, key;        for(int i = 0; i < n; i++) {            if(dp[i][0] < Min) {                Min = dp[i][0];                key = i;            }        }        for(int i = 0; i < m; i++) {            printf("%d%c", key + 1, i == m - 1 ? '\n' : ' ');            key = nx[key][i];        }        printf("%d\n", Min);    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.