Question 21 (DFS): The Salesperson's Dilemma

 
 

Topic description

【Question meaning】 There are n villages (1 < n < 15) in a township. There is a salesperson. He wants to go to each village to sell goods. The distance s (0 < s < 1000) between the villages is known. And the road from village A to village B and from village B to village A are mostly different. To improve efficiency, he starts from the store to each village once, and then returns to the village where the store is located. Assuming that the village where the store is located is 1, he does not know what route to choose to minimize the distance traveled. Please help him choose the shortest way. [Input format] The number of villages n and the distance between each village (both are integers). 【Output format】 The shortest distance. 【Sample input】 3 0 2 1

1 0 2 2 1 0 [Sample output] 3 [Data interpretation] 3 {Number of villages} 0 2 l {distance from village 1 to each village} 1 0 2 {distance from village 2 to each village} 2 1 0 {village 3 Distances to the villages} 

AC CODE:

#include <bits/stdc++.h>
using namespace std;
#define max 0xFFFFFF
int n;
int x[25];
int bestx[25];
int bestc;
int cc;
int a[25][25];
void swap(int &a,int &b) {
    int tep = a;
    a=b;
    b=tep;
}
void dfs(int i) {
    int j;
    if(i==n) {
        if(a[x[n-1]][x[n]]<max&&a[x[n]][1]<max&&(bestc==max||cc+a[x[n-1]][x[n]]+a[x[n]][1]<bestc)) {
            for(j=1; j<=n; j++)
                bestx[j]=x[j];
            bestc=cc+a[x[n-1]][x[n]]+a[x[n]][1];
        }
    } else {
        for(j=i; j<=n; j++)
            if(a[x[i-1]][x[j]]<max&&(bestc==max||cc+a[x[i-1]][x[j]]<bestc)) {
                swap(x[i],x[j]);
                cc+=a[x[i-1]][x[i]];
                dfs(i+1);
                cc-=a[x[i-1]][x[i]];
                swap(x[i],x[j]);
            }
    }
}
int tsp() {
    int i;
    for(i=1; i<=n; i++)
    x[i]=i;
    bestc = max;
    cc=0;
    dfs(2);
    return bestc;
}
int main() {
    cin>>n;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            cin>>a[i][j];
    cout<<tsp()<<endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324412216&siteId=291194637