农夫John发现了做出全威斯康辛州最甜的黄油的方法:糖。
把糖放在一片牧场上,他知道 N 只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。
当然,他将付出额外的费用在奶牛上。
农夫John很狡猾,就像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。
他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。
给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
数据保证至少存在一个牧场和所有牛所在的牧场连通。
输入格式
第一行: 三个数:奶牛数 N,牧场数 P,牧场间道路数 C。
第二行到第 N+1 行: 1 到 N 头奶牛所在的牧场号。
第 N+2 行到第 N+C+1 行:每行有三个数:相连的牧场A、B,两牧场间距 D,当然,连接是双向的。
输出格式
共一行,输出奶牛必须行走的最小的距离和。
数据范围
1≤N≤5001≤N≤500,
2≤P≤8002≤P≤800,
1≤C≤14501≤C≤1450,
1≤D≤2551≤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 <bits/stdc++.h>
using namespace std;
const int N = 810,M=3100;
int n,p,C;
int h[N], w[M], e[M], ne[M], idx;
int dist[N],a[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int spfa(int b)
{
fill(dist,dist+N,0x3f3f3f3f);
memset(st,false,sizeof(false));
queue<int> q;
q.push(b);
dist[b]=0;
st[b] = true;
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
int res=0;
for(int i=0;i<n;i++ ){
int j = a[i];
if(dist[j]==0x3f3f3f3f)return 0x3f3f3f3f;
res += dist[j];
}
return res;
}
int main()
{
scanf("%d%d%d", &n, &p,&C);
for(int i=0;i<n;i++){
cin>>a[i];
}
memset(h, -1, sizeof h);
while (C--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
add(b, a, c);
}
int maxn=0x3f3f3f3f;
for(int i=1;i<=p;i++) maxn=min(maxn,spfa(i));
printf("%d",maxn);
return 0;
}