P1828
[USACO3.2]香甜的黄油 Sweet Butter
题目描述
Farmer John 发现了做出全威斯康辛州最甜的黄油的方法:糖。
把糖放在一片牧场上,他知道 \(N\) 只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。
Farmer John 很狡猾。像以前的 Pavlov,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
Farmer John 知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
输入格式
第一行包含三个整数 \(N,P,C\),分别表示奶牛数、牧场数和牧场间道路数。
第二行到第 \(N+1\) 行,每行一个整数,其中第 \(i\) 行的整数表示第 \(i-1\) 头奶牛所在的牧场号。
第 \(N+2\) 行到第 \(N+C+1\) 行,每行包含三个整数 \(A,B,D\),表示牧场号为 \(A\) 和 \(B\) 的两个牧场之间有一条长度为 \(D\) 的双向道路相连。
输出格式
输出一行一个整数,表示奶牛必须行走的最小的距离和。
样例 #1
样例输入 #1
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
样例输出 #1
8
提示
数据范围
对于所有数据,\(1 \le N \le 500\),\(2 \le P \le 800\),\(1 \le A,B \le P\),\(1 \le C \le 1450\),\(1 \le D \le 255\)。
样例解释
作图如下:
P2
P1 @--1--@ C1
|
|
5 7 3
|
| C3
C2 @--5--@
P3 P4
把糖放在4号牧场最优。
直接Floyd即可
先Floyd预处理出各个牧场间的距离
再枚举放置点取minn即可
虽说复杂度并不优秀 但加一点剪枝开个O2也能过
要注意最后枚举时若到某头奶牛无路要特判
点击查看代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read()
{
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0' && ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*f;
}
int n,p,c,a[805][805],b[505];
int dis[805][805];
signed main()
{
n=read(),p=read(),c=read();
for(register int i=1;i<=n;++i)b[i]=read();
memset(dis,0x3f,sizeof(dis));
for(register int i=1;i<=c;i++)
{
int x,y,z;
x=read(),y=read(),z=read();
a[x][y]=z,a[y][x]=z;
dis[x][y]=dis[y][x]=z;
}
for(int i=1;i<=p;i++)dis[i][i]=0;
for(int k=1;k<=p;k++)
for(int i=1;i<=p;i++)
{
if(i==k)continue;
for(int j=1;j<=i;j++)
{
if(i==j||j==k)continue;
dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
dis[j][i]=dis[i][j];
}
}
int minn=LONG_MAX;
for(int i=1;i<=p;i++)
{
int tot=0;
for(int j=1;j<=n;j++)
{
if(dis[i][b[j]]<0)break;
tot+=dis[i][b[j]];
if(tot>=minn)break;
}
if(tot>=0)
minn=min(minn,tot);
}
cout<<minn<<"\n";
return 0;
}
/*
3 5 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
*/
此生无悔入OI 来生AK IOI

浙公网安备 33010602011771号