香甜的黄油
//还是求最短路,但是需要根据牛所在位置计算最小和。 注意有的牧场一头牛去不了,所以要注意极端的距离0x3f3f3f3f
// 香甜的黄油.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*
https://www.acwing.com/problem/content/1129/
农夫John发现了做出全威斯康辛州最甜的黄油的方法:糖。
把糖放在一片牧场上,他知道 N 只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。
当然,他将付出额外的费用在奶牛上。
农夫John很狡猾,就像以前的巴甫洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。
他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。
给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。
数据保证至少存在一个牧场和所有牛所在的牧场连通。
输入格式
第一行: 三个数:奶牛数 N,牧场数 P,牧场间道路数 C。
第二行到第 N+1 行: 1 到 N 头奶牛所在的牧场号。
第 N+2 行到第 N+C+1 行:每行有三个数:相连的牧场A、B,两牧场间距 D,当然,连接是双向的。
输出格式
共一行,输出奶牛必须行走的最小的距离和。
数据范围
1≤N≤500,
2≤P≤800,
1≤C≤1450,
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
3 5 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
*/
//注意建图的时间复杂度
#include <iostream>
#include <queue>
#include <memory.h>
#include <algorithm>
using namespace std;
const int N = 810;
const int M = 1500 * 2;
int h[N], e[M], ne[M], w[M], idx;
int cowInWhere[N];
int dist[N];
bool st[N];
int n, p, cnt;
void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
void dijkstra(int start) {
memset(st, 0, sizeof st);
memset(dist, 0x3f, sizeof dist);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
q.push({ 0, start });
dist[start] = 0;
while (q.size()) {
auto t = q.top();
q.pop();
int ver = t.second;
if (st[ver]) continue;
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[ver] + w[i]) {
dist[j] = dist[ver] + w[i];
q.push({ dist[j], j });
}
}
}
}
int CalcTotalen(int u) {
int ret = 0;
for (int i = 1; i <= n; i++) {
ret += dist[cowInWhere[i]];
}
if (ret < 0) ret = 0x3f3f3f3f;
return ret;
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> p >> cnt;
for (int i = 1; i <= n; i++) {
cin >> cowInWhere[i];
}
for (int i = 1; i <= cnt; i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c); add(b, a, c);
}
int ans = 0x3f3f3f3f;
for (int i = 1; i <= p; i++) {
dijkstra(i);
ans = min(ans, CalcTotalen(i));
}
cout << ans << endl;
return 0;
}
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力

