旅行商問題

來源:互聯網
上載者:User

標籤:

NPC問題,不存在多項式時間的演算法,但是在演算法中可以做剪枝最佳化:

1. 第一次寫的演算法,缺少剪枝:  當前路徑 >= 之前算出的最短路徑, 則當前路徑不在繼續遍曆

#include <cstdio>#include <iostream>#include <cstring>using namespace std;int N;int map[12][12];int flag[12];int solve(int start) {    int i,val, all_visited = 1, min = 999999999;    for (i = 2; i <= N; i++) {        if (flag[i] != 0 || map[start][i] == 0) {            continue;        }        all_visited = 0;        flag[i] = 1; //visited        val = map[start][i] + solve(i);        if (val < min) {            min = val;        }        flag[i] = 0;    }    if (all_visited) {        return map[start][1];    } else {        return min;    }}int main(int argc, char** argv){    int tc, T, i, j;    // freopen("input.txt", "r", stdin);    cin >> T;    for(tc = 0; tc < T; tc++)    {        cin>>N;        for (i = 1; i <= N; i++) {            for (j = 1; j <= N; j++) {                cin>>map[i][j];            }        }        memset(flag, 0x00, 12*sizeof(int));        printf("%d\n", solve(1));    }    return 0;}

 

2. 最佳化演算法,路徑判斷剪枝

#include <cstdio>#include <iostream>#include <cstring>using namespace std;int N, cost, min_cost;int map[13][13];int flag[13];int sum;void solve(int start) {    int i;    if (sum >= N) {        if (map[start][1]!=0 && cost + map[start][1] < min_cost) {            min_cost = cost + map[start][1];        }        return;    }    for (i = 2; i <= N; i++) {        if (flag[i] != 0 || map[start][i] == 0 || cost + map[start][i] >= min_cost) {            continue;        }        flag[i] = 1; //visited        cost += map[start][i];        sum++;        solve(i);        sum--;        flag[i] = 0;        cost -= map[start][i];    }}int main(int argc, char** argv){    int tc, T, i, j;    //freopen("input.txt", "r", stdin);    cin >> T;    for(tc = 0; tc < T; tc++)    {        cin>>N;        for (i = 1; i <= N; i++) {            for (j = 1; j <= N; j++) {                    cin>>map[i][j];            }        }        memset(flag, 0x00, 13*sizeof(int));        cost = 0; min_cost = 99999999999;        sum = 1;        solve(1);        cout<<min_cost<<endl;    }    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.