香甜的黄油

题目描述

  https://www.luogu.org/problem/show?pid=1828

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

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

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

输入输出格式

输入格式:

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

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

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

输出格式:

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

输入输出样例

输入样例#1:
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
输出样例#1:
8

说明

{样例图形

          P2  
P1 @--1--@ C1
         |
         | 
       5  7  3
         |   
         |     C3
       C2 @--5--@
          P3    P4

} {说明:

放在4号牧场最优

}

【题目分析】

  裸题SPFA

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int INF=1e9+5;
const int maxn=3000;
int n,m,p;
int a[maxn];
int cnt,head[maxn];
int dis[maxn],in[maxn];
int sum,ans;
bool vis[maxn];
struct node{
    int pre,to,w;
}e[maxn];
void Add(int from,int to,int v)
{
    e[++cnt].pre=head[from];
    e[cnt].to=to;
    e[cnt].w=v;
    head[from]=cnt;
}
bool spfa(int s)
{
    int i,t,temp;
    queue<int>Q;
    memset(dis,127/3,sizeof dis);
    memset(in,0,sizeof in);
    memset(vis,0,sizeof vis);
    Q.push(s);
    vis[s]=true;
    dis[s]=0;
    while (!Q.empty())
    {
        t=Q.front();Q.pop();vis[t]=false;
        for(i=head[t];i;i=e[i].pre)
        {
            temp=e[i].to;
            if(dis[temp]>dis[t]+e[i].w)
            {
                dis[temp]=dis[t]+e[i].w;
                if(vis[temp]==0)
                {
                    Q.push(temp);
                    vis[temp]=true;
                    if(++in[temp]>p) return false;
                }
            }
        }
    }
    return true;
}
int main()
{
    cin>>n>>p>>m;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        cin>>x>>y>>z;
        Add(x,y,z);
        Add(y,x,z);
    }
    sum=INF;
    for(int i=1;i<=p;i++)
    {
        ans=0;
        if(spfa(i))
            for(int j=1;j<=n;j++)
                ans+=dis[a[j]];
        sum=min(ans,sum);
    }
    cout<<sum;
    return 0;
}

 

posted @ 2016-11-14 19:31  [lemon]  阅读(272)  评论(0编辑  收藏  举报
……