joisino's travel
D - joisino's travel
Problem Statement
There are N towns in the State of Atcoder, connected by M bidirectional roads.
The i-th road connects Town Ai and Bi and has a length of Ci.
Joisino is visiting R towns in the state, r1,r2,..,rR (not necessarily in this order).
She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.
If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?
Constraints
- 2≤N≤200
- 1≤M≤N×(N−1)⁄2
- 2≤R≤min(8,N) (min(8,N) is the smaller of 8 and N.)
- ri≠rj(i≠j)
- 1≤Ai,Bi≤N,Ai≠Bi
- (Ai,Bi)≠(Aj,Bj),(Ai,Bi)≠(Bj,Aj)(i≠j)
- 1≤Ci≤100000
- Every town can be reached from every town by road.
- All input values are integers.
Input is given from Standard Input in the following format:
N M R r1 … rR A1 B1 C1 : AM BM CM
Output
Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.
Sample Input 1
3 3 3 1 2 3 1 2 1 2 3 1 3 1 4
Sample Output 1
2
For example, if she visits the towns in the order of 1, 2, 3, the distance traveled will be 2, which is the minimum possible.
Sample Input 2
3 3 2 1 3 2 3 2 1 3 6 1 2 2
Sample Output 2
4
The shortest distance between Towns 1 and 3 is 4. Thus, whether she visits Town 1 or 3 first, the distance traveled will be 4.
Sample Input 3
4 6 3 2 3 4 1 2 4 2 3 3 4 3 1 1 4 1 4 2 2 3 1 6
Sample Output 3
3 最短路+排序
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <vector> #include <queue> #include <stack> #include <cstdlib> #include <iomanip> #include <cmath> #include <cassert> #include <ctime> #include <map> #include <set> using namespace std; #define lowbit(x) (x&(-x)) #define max(x,y) (x>=y?x:y) #define min(x,y) (x<=y?x:y) #define MAX 100000000000000000 #define MOD 1000000007 #define pi acos(-1.0) #define ei exp(1) #define PI 3.141592653589793238462 #define ios() ios::sync_with_stdio(true) #define INF 1044266558 #define mem(a) (memset(a,0,sizeof(a))) typedef long long ll; ll g[212][202],vis[10],n,x,y,w,m,s; void init() { for(int i=0;i<=n;i++) { for(int j=0;j<=i;j++) g[j][i]=g[i][j]=INF; g[i][i]=0; } for(int i=0;i<m;i++) { scanf("%lld%lld%lld",&x,&y,&w); g[x][y]=g[y][x]=min(g[x][y],w); } } void flyod() { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { for(int k=1;k<=n;k++) { g[j][k]=min(g[j][k],g[j][i]+g[i][k]); } } } } int main() { while(scanf("%lld%lld%lld",&n,&m,&s)!=EOF) { for(int i=0;i<s;i++) scanf("%lld",&vis[i]); sort(vis,vis+s); init(); flyod(); ll ans=INF; do { ll pos=0; for(int i=0;i<s-1;i++) pos+=g[vis[i]][vis[i+1]]; ans=min(ans,pos); }while(next_permutation(vis,vis+s)); printf("%lld\n",ans); } return 0; }