重庆OI 2005 新年好
题意
有 n n n个车站, m m m条双向边,给你指定的 5 5 5个车站 a , b , c , d , e a, b, c, d, e a,b,c,d,e,问你从 1 1 1号车站出发,经过所有指定车站的路径之和最短为多少。
数据范围
1 ⩽ n ⩽ 50000 1 \leqslant n \leqslant 50000 1⩽n⩽50000
1 ⩽ m ⩽ 1 0 5 1 \leqslant m \leqslant 10^5 1⩽m⩽105
1 < a , b , c , d , e ⩽ n 1 < a, b, c, d, e \leqslant n 1<a,b,c,d,e⩽n
思路
暴力枚举所有的行走路线一共 5 ! 5! 5!种方案,我们可以先预处理出这 6 6 6个车站(包括第一个车站)之间的最短距离,然后暴力跑所有的行走路线,取路径之和的最小值。
时间复杂度
用
d
i
j
k
s
t
r
a
dijkstra
dijkstra跑,
O
(
m
∗
log
n
∗
5
!
)
O(m * \log{n} * 5!)
O(m∗logn∗5!)
代码
#include <bits/stdc++.h>
#define PII pair<int,int>
#define LL long long
#define fi first
#define se second
#define debug(a) cout<<#a<<"="<<a<<endl;
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define Yes puts("Yes");
#define No puts("No");
#define sz(x) (int)x.size()
using namespace std;
template <typename T> void read(T &t) {
t=0; char ch=getchar(); int f=1;
while (ch<'0'||ch>'9') { if (ch=='-') f=-1; ch=getchar(); }
do { (t*=10)+=ch-'0'; ch=getchar(); } while ('0'<=ch&&ch<='9'); t*=f;
}
template <typename T> void write(T t) {
if (t<0) { putchar('-'); write(-t); return; }
if (t>9) write(t/10);
putchar('0'+t%10);
}
template <typename T> void writeln(T t) { write(t); puts(""); }
const int N = 50010, M = 200010;
int n, m, sum, ans = 2e9;
int a[10];//亲戚家
int h[N], ne[M], e[M], w[M], idx;
int dist[10][N];
bool st[N], vis[N];
void add(int a, int b, int c){
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
}
void dijkstra(int x, int d[]){
memset(st, false, sizeof st);
d[x] = 0;
priority_queue<PII,vector<PII>,greater<PII>>q;
q.push({0, x});
while(q.size()){
auto it = q.top();
q.pop();
int ver = it.second;
if(st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; ~i; i = ne[i]) {
int j = e[i];
if(d[j] > d[ver] + w[i]){
d[j] = d[ver] + w[i];
q.push({d[j], j});
}
}
}
}
void dfs(int pre, int cnt){
if(cnt == 6){
ans = min(ans, sum);
return;
}
for(int i = 2; i <= 6; i ++ ){
if(!vis[i]){
sum += dist[i][pre];
vis[i] = true;
dfs(a[i], cnt + 1);
vis[i] = false;
sum -= dist[i][pre];
}
}
}
int main()
{
memset(h, -1, sizeof h);
memset(dist, 127, sizeof dist);
read(n);read(m);
for(int i = 2; i <= 6; i ++ ) read(a[i]);
a[1] = 1;
while(m -- ){
int a, b, c;
read(a), read(b), read(c);
add(a, b, c);add(b, a, c);
}
for(int i = 1; i <= 6; i ++ ) dijkstra(a[i], dist[i]);
dfs(1, 1);
writeln(ans);
return 0;
}