2038 香甜的黄油

USACO

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 钻石 Diamond
 查看运行结果
 
 
题目描述 Description

农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1<=N<=500)只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。

农夫John很狡猾。他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。

农夫John知道每只奶牛都在各自喜欢的牧场呆着(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。

输入描述 Input Description

第一行: 三个数:奶牛数N,牧场数P(2<=P<=800),牧场间道路数C(1<=C<=1450).

第二行到第N+1行: 1到N头奶牛所在的牧场号.

第N+2行到第N+C+1行: 每行有三个数:相连的牧场A、B,两牧场间距(1<=D<=255),当然,连接是双向的.

输出描述 Output Description

一行 输出奶牛必须行走的最小的距离和.

样例输入 Sample Input
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
样例图形
         P2
P1 @--1--@ C1
\ |\
\ | \
5 7 3
\ | \
\| \ C3
C2 @--5--@
P3 P4
样例输出 Sample Output
8
{说明: 放在4号牧场最优. }
数据范围及提示 Data Size & Hint

见描述

思路:

  spfa;

来,上代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm> #define INF 0x7ffffff using namespace std; struct EdgeType {
int to,dis,next;
};
struct EdgeType edge[]; int n,p,m,bel[],cnt,ans=INF;
int head[],dis[],que[]; bool if_[]; char Cget; inline void in(int &now)
{
now=,Cget=getchar();
while(Cget>''||Cget<'') Cget=getchar();
while(Cget>=''&&Cget<='')
{
now=now*+Cget-'';
Cget=getchar();
}
} int main()
{
in(n),in(p),in(m);int u,v,w;
for(int i=;i<=n;i++) in(bel[i]);
for(int i=;i<=m;i++)
{
in(u),in(v),in(w);
edge[++cnt].to=v,edge[cnt].next=head[u],edge[cnt].dis=w,head[u]=cnt;
edge[++cnt].to=u,edge[cnt].next=head[v],edge[cnt].dis=w,head[v]=cnt;
}
for(int s=;s<=p;s++)
{
for(int i=;i<=p;i++) dis[i]=INF;
int he=,ta=;if_[s]=true,dis[s]=;
que[ta++]=s;
while(he<ta)
{
int pos=que[he];he++;
for(int i=head[pos];i;i=edge[i].next)
{
if(dis[edge[i].to]>dis[pos]+edge[i].dis)
{
dis[edge[i].to]=dis[pos]+edge[i].dis;
if(!if_[edge[i].to])
{
if_[edge[i].to]=true;
que[ta++]=edge[i].to;
}
}
}
if_[pos]=false;
}
int tot=;
for(int i=;i<=n;i++) tot+=dis[bel[i]];
if(tot<ans) ans=tot;
}
cout<<ans;
return ;
}
05-11 22:03