[COGS309] [USACO 3.2] 香甜的黄油

★★   输入文件:butter.in   输出文件:butter.out   简单对比
时间限制:1 s   内存限制:128 MB

描述

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

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

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

格式

INPUT FORMAT:

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

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

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

OUTPUT FORMAT:

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

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号牧场最优 }

思路

最短路算法暴算;

我用的SPFA;

代码实现

 1 #include<cstdio>
 2 #include<cstring>
 3 const int maxn=1e4;
 4 const int maxm=1e5;
 5 int n,p,c,now,ans=1e9;
 6 int a,b,u,v,w;
 7 int s[maxn],d[maxn];
 8 int h[maxm],hs,et[maxm],ew[maxm],en[maxm];
 9 void add(int u,int v,int w){
10     ++hs,et[hs]=v,ew[hs]=w,en[hs]=h[u],h[u]=hs;
11     ++hs,et[hs]=u,ew[hs]=w,en[hs]=h[v],h[v]=hs;
12 }
13 int q[maxn],head,tail;
14 bool f[maxn];
15 void SPFA(int s){
16     memset(d,0x7f,sizeof(d));
17     head=tail=d[s]=0;
18     q[head++]=s;
19     while(head>tail){
20         a=q[tail++],f[a]=0;
21         for(int i=h[a];i;i=en[i])
22         if(0ll+ew[i]+d[a]<d[et[i]]){
23             d[et[i]]=ew[i]+d[a];
24             if(!f[et[i]]) q[head++]=et[i],f[et[i]]=1;
25         }
26     }
27 }
28 int main(){
29     freopen("butter.in","r",stdin);
30     freopen("butter.out","w",stdout);
31     scanf("%d%d%d",&n,&p,&c);
32     for(int i=1;i<=n;i++){
33         scanf("%d",&a);
34         ++s[a];
35     }
36     for(int i=1;i<=c;i++){
37         scanf("%d%d%d",&u,&v,&w);
38         add(u,v,w);
39     }
40     for(int i=1;i<=p;i++){
41         SPFA(i);
42         for(int j=1;j<=p;j++) now+=s[j]*d[j];
43         ans=ans<now?ans:now,now=0;
44     }
45     printf("%d
",ans);
46     return 0;
47 }
原文地址:https://www.cnblogs.com/J-william/p/7073734.html