1345:【例4-6】香甜的黄油
题目:
【题目描述】
时间限制:1s 空间限制:64mb
农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1≤N≤500)
只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。
农夫John很狡猾。像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的
牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧
场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
【输入】
第一行: 三个数:奶牛数N,牧场数P(2≤P≤800),牧场间道路数C(1≤C≤1450)。
第二行到第N+1行: 1到N头奶牛所在的牧场号。
第N+2行到第N+C+1行:每行有三个数:相连的牧场A、B,两牧场间距(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<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=1000;
const int maxm=1e5+10;
int num[maxn],dis[maxn],cnt,head[maxn];
bool s[maxn];
int N,n,m;
struct node{
int v;
int w;
int next;
}edge[maxm];
void add_edge(int u, int v, int w){
edge[++cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
void spfa(int S){
memset(dis,0x3f,sizeof(dis));
memset(s,0,sizeof(s));
queue<int> q;
s[S]=true; dis[S] = 0; q.push(S);
while(!q.empty()){
int u = q.front();
q.pop();
s[u] = false;
for(int i=head[u];i;i=edge[i].next){
int v = edge[i].v;
int w = edge[i].w;
if (dis[u]+w < dis[v]){
dis[v] = dis[u]+w;
if (!s[v]){
q.push(v);
s[v] = true;
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);
cin >> N >> n >> m;
for(int i=1;i<=N;i++) cin>>num[i];
int u, v, w;
for(int i=1;i<=m;i++){
cin >> u >> v >> w;
add_edge(u, v, w);
add_edge(v, u, w);
}
int minn = INF;
for(int i=1;i<=n;i++){
spfa(i);
int sum = 0;
for(int j=1;j<=N;j++){
sum += dis[num[j]];
}
minn = min(minn, sum);
}
cout<<minn;
return 0;
}