售貨員的難題
阿新 • • 發佈:2018-11-03
售貨員的難題
5000(ms)
65535(kb)
675 / 3441
Tags: 動態規劃
@淺夏沫若.code:
#include<iostream>
using namespace std;
const int MAXN = 21;
int map[MAXN][MAXN];
bool vis[MAXN];
int minlength = 20000;
int n = 0;
void dfs(int t,int tot,int count)
{
if (tot > minlength) return;
if (count == n)
{
if (map[t][1])
{
tot +=map[t][1];
if (tot <minlength)
{
minlength= tot;
}
}
return;
}
for (int i = 1; i <= n; i++)
if (!vis[i] &&map[t][i])
{
vis[i] =1;
dfs(i, tot +map[t][i], count+1);
vis[i] =0;
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n;j++)
cin >>map[i][j];
vis[1] = 1;
dfs(1, 0, 1);
cout << minlength << endl;
return 0;
}
某鄉有n個村莊(1< n < 20),有一個售貨員,他要到各個村莊去售貨,各村莊之間的路程s(0 < s <1000)是已知的,且A村到B村與B村到A村的路大多不同。為了提高效率,他從商店出發到每個村莊一次,然後返回商店所在的村,假設商店所在的村莊為1,他不知道選擇什麼樣的路線才能使所走的路程最短。請你幫他選擇一條最短的路。
輸入
村莊數n和各村之間的路程(均是整數)。
輸出
最短的路程
樣例輸入
3 {村莊數} 0 2 1 {村莊1到各村的路程} 1 0 2 {村莊2到各村的路程} 2 1 0 {村莊3到各村的路程}
樣例輸出
3
@淺夏沫若.code:
#include<iostream>
using namespace std;
const int MAXN = 21;
int map[MAXN][MAXN];
bool vis[MAXN];
int minlength = 20000;
int n = 0;
{
if (tot > minlength) return;
if (count == n)
{
if (map[t][1])
{
tot +=map[t][1];
if (tot <minlength)
{
minlength= tot;
}
}
return;
}
for (int i = 1; i <= n; i++)
if (!vis[i] &&map[t][i])
{
vis[i] =1;
dfs(i, tot +map[t][i], count+1);
vis[i] =0;
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n;j++)
cin >>map[i][j];
vis[1] = 1;
dfs(1, 0, 1);
cout << minlength << endl;
return 0;
}