【题目描述】:
农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1<=N<=500)只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。
农夫John很狡猾。像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
【输入描述】:
第一行: 三个数:奶牛数N,牧场数P,牧场间道路数C。
第二行到第N+1行: 1到N头奶牛所在的牧场号。
第N+2行到第N+C+1行:每行有三个数:相连的牧场A、B,两牧场间距,当然,连接是双向的。
【输出描述】:
一行 输出奶牛必须行走的最小的距离和。
【样例输入】:
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
【样例输出】:
8
【样例说明】:
P2
P1 @–1--@ C1
\ |
\ |
5 7 3
\ |
| \ C3
C2 @–5--@
P3 P4
【时间限制、数据范围及描述】:
时间:1s 空间:128M
2<=P<=800; 1<=C<=1450; 1<=D<=255;
【解题思路】:
多源最短路径模板题。这道题要使用Dijkstra+堆优化不然会超时。枚举假设每个牧场为终点,用Dijkstra算法计算出牛到这个牧场的最短总距离,最后的最小值即为答案。
【AC代码】:
#include<bits/stdc++.h>
#define M(a,b) memset(a,b,sizeof(a))
using namespace std;
const int M=10005;
const int oo=1<<30;
int N,P,C,i,j,ansz=oo,sum=0;
int next[M],head[M],to[M],adj[M],val[M];
int dist[M],ans[M],wz[M],wz2[M];
struct node{
int id,d;
bool operator> (const node b) const {return d>b.d;}
}a[M];
priority_queue <node,vector<node>,greater<node> > Q;
int tot=0;
inline void read(int &x){
char ch=getchar(),c=ch;
x=0;
while(ch<'0' || ch>'9'){
c=ch;
ch=getchar();
}
while(ch>='0' && ch<='9'){
x=(x<<1)+(x<<3)+ch-'0';
ch=getchar();
}
if(c=='-')x=-x;
}
void add(int u,int v,int w){
next[++tot]=head[u];
head[u]=tot;
to[tot]=v;
adj[tot]=w;
return;
}
void Dijkstra(int s){
for(int i=1;i<=P;i++){dist[i]=oo;ans[i]=oo;}
dist[s]=0;
ans[s]=0;
Q.push((node){s,0});
while (!Q.empty()){
node x=Q.top();
Q.pop();
for(int i=head[x.id];i;i=next[i])
if(x.d+adj[i]<dist[to[i]] || x.d+adj[i]==dist[to[i]]){
dist[to[i]]=x.d+adj[i];
Q.push((node){to[i],dist[to[i]]});
}
}
return;
}
int main(){
read(N),read(P),read(C);
M(head,0);
M(dist,0);
M(ans,0);
int x;
for(i=1;i<=N;i++){
read(wz[i]);
wz2[wz[i]]++;
}
for(i=1;i<=C;i++){
int u,v,w;
read(u),read(v),read(w);
add(u,v,w);
add(v,u,w);
}
for(i=1;i<=P;i++){
sum=0;
Dijkstra(i);
for(j=1;j<=N;j++){
sum+=dist[wz[j]];
}
ansz=min(sum,ansz);
}
cout<<ansz<<'\n';
return 0;
}