Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Dữ liệu

const int inf = 30000;


const int maxn = 50;

int G[maxn][maxn];
bool C[maxn]={false}, cn = false;
int X[maxn],Y[maxn], n, m, ans=inf;

Hàm quay lui chọn đỉnh thứ i

void Try(int i){


for (int j=1;j<=n;j++){
if (!C[j] && G[i][j]<inf){
X[i] = j;
C[j] = true;
if (i==n) GhiNghiem();
Try(i+1);
C[j] = false;
}
}
}

Hàm ghi nghiệm


void GhiNghiem(){

int t=0;
for (int i=2;i<=n;i++){
t+=G[X[i-1]][X[i]];
}

t+=G[X[n]][X[1]];
//Nếu nghiệm này tốt hơn thì ghi nhận
//và lưu vector nghiệm X vào Y
if (t<ans){
for (int i=1;i<=n;i++) Y[i] = X[i];
ans = t;
cn=true;
}
}

Thuật toán (hàm main)


cin >> n >> m;
for (int i=1; i<n; i++){
for (int j=i;j<=n;j++) G[i][j] = G[j][i] = inf;
}
for (int i=1; i<=m; i++){
int u, v, w;
cin >> u >> v >> w;
G[u][v] = G[v][u] = w;
}

Try(1);

if (cn){
cout << ans << endl;
for (int i=1; i<=n; i++) cout << Y[i] << " ";
cout << Y[1];
} else cout << -1;

You might also like