单源最短路解决多源汇最短路问题,1127. 香甜的黄油

编程入门 行业动态 更新时间:2024-10-26 18:27:27

单源最短路解决多源汇最短路问题,1127. 香甜的<a href=https://www.elefans.com/category/jswz/34/1718553.html style=黄油"/>

单源最短路解决多源汇最短路问题,1127. 香甜的黄油

1127. 香甜的黄油 - AcWing题库

农夫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

解析: 

使用spfa算法求解多源汇最短路问题:
这道题看似是一道多源最短路问题,但它实际上可以使用单源最短路问题解决,可以使用spfa和堆优化版Dijkstra来解决,这里我选择spfa算法

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
using namespace std;
typedef long long LL;
const int N = 505, P = 805, M = 1450 * 2 + 5,INF=0x3f3f3f3f;
int n, p, c;
int id[N], h[P], e[M], ne[M], w[M], idx;
int q[P],d[P];
bool v[P];void add(int a, int b, int c) {e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}int spfa(int start) {memset(d, INF, sizeof d);q[0] = start;int hh = 0, tt = 1;d[start] = 0;while (hh != tt) {int t = q[hh++];if (hh == P)hh = 0;v[t] = 0;for (int i = h[t]; ~i; i = ne[i]) {int j = e[i], dd = w[i];if (d[j] > d[t] + dd) {d[j] = d[t] + dd;if (!v[j]) {q[++tt] = j;v[j] = 1;}}}}int sum = 0;for (int i = 1; i <= n; i++) {//cout << d[id[i]] << " ";if (d[id[i]] == INF) {return INF;}sum += d[id[i]];}//cout << endl;return sum;
}int main() {scanf("%d%d%d", &n, &p, &c);for (int i = 1,a; i <= n; i++) {scanf("%d", &a);id[i] = a;}memset(h, -1, sizeof h);for (int i = 1,a,b,C; i <= c; i++) {scanf("%d%d%d", &a, &b, &C);add(a, b, C), add(b, a, C);}int ans = INF;for (int i = 1; i <= p; i++) {ans = min(ans, spfa(i));}cout << ans << endl;return 0;
}

更多推荐

单源最短路解决多源汇最短路问题,1127. 香甜的黄油

本文发布于:2023-11-15 04:31:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593701.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:黄油   香甜   单源   多源汇最

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!