重庆城里有 nn 个车站,mm 条 双向 公路连接其中的某些车站。
每两个车站最多用一条公路连接,从任何一个车站出发都可以经过一条或者多条公路到达其他车站,但不同的路径需要花费的时间可能不同。
在一条路径上花费的时间等于路径上所有公路需要的时间之和。
佳佳的家在车站 11,他有五个亲戚,分别住在车站 a,b,c,d,ea,b,c,d,e。
过年了,他需要从自己的家出发,拜访每个亲戚(顺序任意),给他们送去节日的祝福。
怎样走,才需要最少的时间?
输入格式
第一行:包含两个整数 n,mn,m,分别表示车站数目和公路数目。
第二行:包含五个整数 a,b,c,d,ea,b,c,d,e,分别表示五个亲戚所在车站编号。
以下 mm 行,每行三个整数 x,y,tx,y,t,表示公路连接的两个车站编号和时间。
输出格式
输出仅一行,包含一个整数 TT,表示最少的总时间。
数据范围
1≤n≤500001≤n≤50000,
1≤m≤1051≤m≤105,
1<a,b,c,d,e≤n1<a,b,c,d,e≤n,
1≤x,y≤n1≤x,y≤n,
1≤t≤1001≤t≤100输入样例:
6 6 2 3 4 5 6 1 2 8 2 3 3 3 4 4 4 5 5 5 6 2 1 6 7
输出样例:
21
解题思路:
1:先对原点1以及她的5个亲戚做一遍dijkstra最短路;
2:然后用dfs枚举访问所有亲戚的所有顺序取最小值即可;
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 50010, M = 200010;
int n, m;
int id[6];
bool st[N];
int dist[6][N];
int ans = 0x3f3f3f3f;
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx;
idx ++ ;
}
void dijkstra(int start, int dist[])//对原点以及他的五个亲戚做最短路
{ //start是起点;
memset(st, false, sizeof st);
memset(dist, 0x3f, (N * 4));//一个int表示4个字节,共有N个int
dist[start] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({dist[start], start});
while (heap.size())
{
auto t = heap.top();
heap.pop();
int ver = t.y, distance = t.x;
if (st[ver]) continue;
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
if (!st[j]) heap.push({dist[j], j});
}
}
}
}
void dfs(int u, int start, int distance)//依次枚举访问顺序,u当前访问可几个亲戚,
{ //start当前正走到哪个亲戚, distance当前以及访问的亲戚的距离
if (u == 5)
{
ans = min(ans, distance);
return ;
}
for (int i = 1; i <= 5; i ++ )
{
if (!st[i])
{
st[i] = true;
dfs(u + 1, i, distance + dist[start][id[i]]);
st[i] = false;
}
}
}
int main()
{
cin >> n >> m;
id[0] = 1;
for (int i = 1; i <= 5; i ++ ) cin >> id[i];
memset(h, -1, sizeof h);
while (m -- )
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
for (int i = 0; i <= 5; i ++ ) dijkstra(id[i], dist[i]);
memset(st, false, sizeof st);
dfs(0, 0, 0);
printf("%d\n", ans);
return 0;
}