我的个人博客:[个人博客](https://aurexare.github.io/)
转载于信息学奥赛一本通
【题目描述】
农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1≤N≤500)只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。
农夫John很狡猾。像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
【输入】
第一行: 三个数:奶牛数N,牧场数P(2≤P≤800),牧场间道路数C(1≤C≤1450)。
第二行到第N+1行: 1到N头奶牛所在的牧场号。
第N+2行到第N+C+1行:每行有三个数:相连的牧场A、B,两牧场间距(1≤D≤255),当然,连接是双向的。
【输出】
一行 输出奶牛必须行走的最小的距离和。
【输入样例】
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
【输出样例】
8
【提示】
说明:放在4号牧场最优。
【参考程序】
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n, p, c, i, j, x, y, t, minl, head, tail, tot, u;
int a[801][801], b[501], dis[801], num[801], w[801][801], team[1601];
bool exist[801];
int main()
{
cin >> n >> p >> c;
for (i = 1; i <= p; i++)
{
b[i] = 0;
num[i] = 0;
for (j - 1; j <= p; j++)
w[i][j] = 0xfffffff / 3;
}
for (i = 1; i <= n; i++)cin >> b[i];
for (i = 1; i <= c; i++)
{
cin >> x >> y >> t;
w[x][y] = w[y][x] = t;
a[x][++num[x]] = y;
a[y][++num[y]] = x;
}
minl = 0x7fffffff / 3;
for (i = 1; i <= p; i++)
{
for (j = 1; j <= p; j++)dis[j] = 0xfffffff / 3;
memset(team, 0, sizeof(team));
memset(exist, false, sizeof(exist));
dis[i] = 0; team[1] = i; head = 0; tail = 1; exist[i] = true;
do
{
head++;
head = ((head - 1) % 1601) + 1;
u = team[head];
exist[u] = false;
for (j = 1; j <= num[n]; j++)
{
if (dis[a[u][j]] > dis[u] + w[u][a[u][j]])
{
dis[a[u][j]] = dis[u] + w[u][a[u][j]];
if (!exist[a[u][j]])
{
tail++;
tail = ((tail - 1) % 1601) + 1;
team[tail] = a[u][j];
exist[a[u][j]] = true;
}
}
}
} while (head != tail);
tot = 0;
for (j = 1; j <= n; j++)
tot += dis[b[j]];
if (tot < minl)minl = tot;
}
cout << minl;
return 0;
}