农夫John发现了做出全威斯康辛州最甜的黄油的方法:糖。
把糖放在一片牧场上,他知道 N 只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。
当然,他将付出额外的费用在奶牛上。
农夫John很狡猾,就像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。
他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。
给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
数据保证至少存在一个牧场和所有牛所在的牧场连通。
输入格式
第一行: 三个数:奶牛数 N,牧场数 P,牧场间道路数 C。
第二行到第 N+1 行: 1 到 N 头奶牛所在的牧场号。
第 N+2 行到第 N+C+1 行:每行有三个数:相连的牧场A、B,两牧场间距 D,当然,连接是双向的。
输出格式
共一行,输出奶牛必须行走的最小的距离和。
数据范围
1≤N≤500
2≤P≤800
1≤C≤1450
1≤D≤255
输入样例:
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
输出样例:
8
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 810, M = 1450 * 2 + 10,INF=0x3f3f3f3f;
int n, m, k;
int h[N], e[M], w[M], ne[M], idx;
int dist[N], q[N];
bool st[N];
int a[510];
int ans=INF;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int spfa(int S)
{
memset(dist, 0x3f, sizeof dist);
dist[S] = 0;
int hh = 0, tt = 1;
q[0] = S, st[S] = true;
while (hh != tt)
{
int t=q[hh++];
if(hh==N)hh=0;
st[t]=false;
for(int i=h[t];~i;i=ne[i]){
int j=e[i];
if(dist[t]+w[i]<dist[j]){
dist[j]=dist[t]+w[i];
if(!st[j]){
q[tt++]=j;
if(tt==N)tt=0;
st[j]=true;
}
}
}
}
int res=0;
for (int i = 1; i <= n; i ++ ){
if(dist[a[i]]==INF)return INF;//有点没到达
res+=dist[a[i]];
}
return res;
}
int main()
{
cin >> n >> m >> k;
memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++ )cin>>a[i];//奶牛数
for (int i = 0; i < k; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
for (int i = 1; i <= m; i ++ ){
ans=min(ans,spfa(i));//每个点当作原点求
}
cout << ans << endl;
return 0;
}