Victor and World
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)
Total Submission(s): 891 Accepted Submission(s): 399
Problem Description
After trying hard for many years, Victor has finally received a pilot license. To have a celebration, he intends to buy himself an airplane and fly around the world. There are n countries on the earth, which are numbered from 1 to n. They are connected by m undirected flights, detailedly the i-th flight connects the ui-th and thevi-th country, and it will cost Victor's airplane wi L fuel if Victor flies through it. And it is possible for him to fly to every country from the first country.
Victor now is at the country whose number is 1, he wants to know the minimal amount of fuel for him to visit every country at least once and finally return to the first country.
Input
The first line of the input contains an integer T, denoting the number of test cases.
In every test case, there are two integers n and m in the first line, denoting the number of the countries and the number of the flights.
Then there are m lines, each line contains three integers ui, vi and wi, describing a flight.
1≤T≤20.
1≤n≤16.
1≤m≤100000.
1≤wi≤100.
1≤ui,vi≤n.
Output
Your program should print T lines : the i-th of these should contain a single integer, denoting the minimal amount of fuel for Victor to finish the travel.
Sample Input
1
3 2
1 2 2
1 3 3
s
#include <iostream>
#include <algorithm>
#include <math.h>
#include <vector>
#include<cstdio>
#include <cstring>
#include <queue>
#include<bitset>
typedef long long ll;
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn = 2e5+100;
int dp[(1<<20)][20];
int g[100][100];
int n,m;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
memset(g,inf,sizeof(g));
memset(dp,inf,sizeof(dp));
for(int i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(g[a][b]>c)
g[a][b]=g[b][a]=c;
}
for(int i=1;i<=n;i++)
g[i][i]=0;
for(int k=1;k<=n;k++)//floyd
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(g[i][k]!=inf&&g[k][j]!=inf&&g[i][k]+g[k][j]<g[i][j])
{
g[i][j]=g[i][k]+g[k][j];//k和j之间的最短路
}
}
dp[1][1]=0;//起点
for(int i=1;i<(1<<n);i++)//枚举在所有city的情况
for(int k=1;k<=n;k++)//枚举从i到j的情况
for(int j=1;j<=n;j++)//枚举从i到j再到k的情况是否为更优解
{
if((i&(1<<k-1))==0&&(i&(1<<j-1)))
{
dp[i|(1<<k-1)][k]=min(dp[i|(1<<k-1)][k],dp[i][j]+g[j][k]);//表示当前在i,仍未访问k但已经访问了j,枚举从j到k的情况
}
}
int ans=inf;
for(int i=1;i<=n;i++)
{
ans=min(ans,dp[(1<<n)-1][i]+g[i][1]);//回到终点
}
printf("%d\n",ans);
}
return 0;
}
ample Output
10
题目大意:给你t组数据,每组数据给出n和m,分别表示n个城市,m条航线,然后会有m行u,v,w分别表示航线的起点和终点以及飞跃这段航线需要的燃油量,问你从城市1至少经过其余所有城市1次最后飞回城市1的的燃油量最少是多少。