【问题描述】
农夫John发现做出全威斯康辛州最甜的黄油的方法:把糖放在一片牧场上,他知道N(1<=N<=500)只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。
农夫John很狡猾。像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
【输入格式】
第 1 行: 三个数:奶牛数 N,牧场数 P,牧场间道路数 C。
第 2 行到第 N+1 行: 1 到 N 头奶牛所在的牧场号。
第 N+2 行到第 N+C+1 行: 每行有三个数:相连的牧场A、B,两牧场间距 D,当然,连接是双向的。
【输出格式】
一行 输出奶牛必须行走的最小的距离和。
【输入样例】
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
放在4号牧场最优。
【数据范围】
2 <= P <= 800
1 <= C <= 1450
1 <= D <= 255
这道题思路就是枚举每一个牧场为起点,用SPFA(用Dijstra算法不优化会超时)找出起点到牧场间的最短路径,然后计算奶牛到牧场的距离和,取最小值。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int maxn=1002,inf=1000000000;
int n,p,c,a,b,d,t,dist[maxn],s1[maxn],inq[maxn];
vector<int>g[maxn],w[maxn];
void spfa(int s)
{
queue<int>a;
for(int i=1;i<=p;i++)
dist[i]=inf;
memset(inq,0,sizeof(inq));
dist[s]=0;
a.push(s);
inq[s]=1;
while(!a.empty())
{
int i=a.front(); a.pop();
inq[i]=0;
for(int k=0;k<g[i].size();k++)
{
int j=g[i][k];
if(dist[i]+w[i][k]<dist[j])
{
dist[j]=dist[i]+w[i][k];
if(inq[j]) continue;
inq[j]=1;
a.push(j);
}
}
}
}
int main()
{
//freopen("1.txt","r",stdin);
scanf("%d%d%d",&n,&p,&c);
memset(s1,0,sizeof(s1));
for(int i=1;i<=n;i++)
{
scanf("%d",&t);
s1[t]++;
}
for(int i=1;i<=c;i++)
{
scanf("%d%d%d",&a,&b,&d);
g[a].push_back(b);
g[b].push_back(a);
w[a].push_back(d);
w[b].push_back(d);
}
int ans=inf;
for(int i=1;i<=p;i++) //枚举每一个牧场为起点
{
spfa(i);
int sum=0;
for(int j=1;j<=p;j++)
{
if(!s1[j]) continue;
sum+=dist[j]*s1[j]; //计算奶牛到牧场的距离和
}
ans=min(sum,ans); //取最小值
}
printf("%d",ans);
return 0;
}