AtCoder Beginner Contest 073

D - joisino's travel

Time Limit: 2 sec / Memory Limit: 256 MB

Score : 400400 points

Problem Statement

There are NN towns in the State of Atcoder, connected by MM bidirectional roads.

The ii-th road connects Town AiAi and BiBi and has a length of CiCi.

Joisino is visiting RR towns in the state, r1,r2,..,rRr1,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

  • 2N2002≤N≤200
  • 1MN×(N1)/21≤M≤N×(N−1)/2
  • 2Rmin(8,N)2≤R≤min(8,N) (min(8,N)min(8,N) is the smaller of 88 and NN.)
  • rirj(ij)ri≠rj(i≠j)
  • 1Ai,BiN,AiBi1≤Ai,Bi≤N,Ai≠Bi
  • (Ai,Bi)(Aj,Bj),(Ai,Bi)(Bj,Aj)(ij)(Ai,Bi)≠(Aj,Bj),(Ai,Bi)≠(Bj,Aj)(i≠j)
  • 1Ci1000001≤Ci≤100000
  • 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:

NN MM RR
r1r1 ...... rRrR
A1A1 B1B1 C1C1
::
AMAM BMBM CMCM

Output

Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.

 

题意:

一个人旅行,必须经过指定的r个城市,问最短的路程是多少。他可以从任意一个城市开始,任意一个城市结束。保证图是连通的。

思路:

赛上没有写出来,是因为把题给读错了,以为必须经过1和n两个点。后来经过多方问询,把题意理清楚了。首先由于n最大只有200,所以可以用floyed求出两点之间的最短距离。之后,由于r很小所以可以把r的阶乘种的情况给枚举出来,这个时候就用到了dfs,最后取一个最小值即可。

代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 const int inf = 0x3f3f3f3f;
 7 int rr[10];
 8 int mp[205][205];
 9 bool v[10];
10 
11 int n,m,r;
12 int ans;
13 
14 void dfs(int c,int las,int dis)
15 {
16     if (c == r)
17     {
18         ans  = min(ans,dis);
19         return;
20     }
21 
22     for (int i = 0;i < 8;i++)
23     {
24         if (!v[i])
25         {
26             v[i] = 1;
27 
28             if (las == -1) dfs(c + 1,i,dis);
29             else dfs(c+1,i,dis + mp[rr[las]][rr[i]]);
30 
31             v[i] = 0;
32         }
33 
34     }
35 }
36 
37 int main()
38 {
39 
40     ans = inf;
41 
42     memset(mp,inf,sizeof(mp));
43 
44     scanf("%d%d%d",&n,&m,&r);
45 
46     for (int i = 0;i < r;i++)
47         scanf("%d",&rr[i]);
48 
49     for (int i = 0;i < m;i++)
50     {
51         int x,y,z;
52 
53         scanf("%d%d%d",&x,&y,&z);
54 
55         if (mp[x][y] > z)
56             mp[x][y] = mp[y][x] = z;
57     }
58 
59     for (int k = 1;k <= n;k++)
60         for (int i = 1;i <= n;i++)
61             for (int j = 1;j <= n;j++)
62                 mp[i][j] = min(mp[i][j],mp[i][k] + mp[k][j]);
63 
64     dfs(0,-1,0);
65 
66     printf("%d\n",ans);
67 
68     return 0;
69 }

 

posted @ 2017-09-10 10:54  qrfkickit  阅读(175)  评论(0编辑  收藏  举报