Contest 073 joisino's travel(最短路Floyd+全排列)

来源:互联网 发布:阿里移动推荐算法总结 编辑:程序博客网 时间:2024/06/03 20:32

joisino's travel


Time limit : 2sec / Memory limit : 256MB

Score : 400 points

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

  • 2N200
  • 1MN×(N1)2
  • 2Rmin(8,N) (min(8,N) is the smaller of 8 and N.)
  • rirj(ij)
  • 1Ai,BiN,AiBi
  • (Ai,Bi)(Aj,Bj),(Ai,Bi)(Bj,Aj)(ij)
  • 1Ci100000
  • Every town can be reached from every town by road.
  • All input values are integers.

Input

Input is given from Standard Input in the following format:

N M Rr1  rRA1 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

Copy
3 3 31 2 31 2 12 3 13 1 4

Sample Output 1

Copy
2

For example, if she visits the towns in the order of 123, the distance traveled will be 2, which is the minimum possible.


Sample Input 2

Copy
3 3 21 32 3 21 3 61 2 2

Sample Output 2

Copy
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

Copy
4 6 32 3 41 2 42 3 34 3 11 4 14 2 23 1 6

Sample Output 3

Copy
3

这道题开始想单纯用最短路居然做不出来,因为这并不是单源最短路问题而是规划一条路线。
所以可以先用Floyd算出任意两点之间最短距离,然后把想要去的点跑一遍全排列结果就出来了。

#include<cstdio>#include<iostream>#include<algorithm>#include<queue>#include<stack>#include<cstring>#include<string>#include<vector>#include<cmath>#include<map>using namespace std;typedef long long ll;#define mem(a,b) memset(a,b,sizeof(a))const int maxn = 1e5+5;const int ff = 0x3f3f3f3f; int n,m,r;int e[50];int dis[202][202]; int main(){cin>>n>>m>>r;for(int i = 1;i<= r;i++)cin>>e[i];mem(dis,ff);for(int i = 1;i<= m;i++){int a,b,c;cin>>a>>b>>c;dis[a][b] = c;dis[b][a] = c;}for(int k = 1;k<= n;k++)for(int i = 1;i<= n;i++)for(int j = 1;j<= n;j++)dis[i][j] = min(dis[i][j],dis[i][k]+dis[k][j]);vector<int> p;for(int i = 1;i<= r;i++)p.push_back(i);//我实在不明白为什么直接把e数组压进去生成全排列会WAint ans = ff;do{int tmp = 0;for(int i = 1;i< r;i++)tmp+= dis[e[p[i]]][e[p[i-1]]];ans = min(ans,tmp);} while(next_permutation(p.begin(),p.end()));cout<<ans<<endl;return 0;}


原创粉丝点击