You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 810; // 牧场数 上限800
const int M = 3000; // 牧场间道路数 上限1450无向图开双倍
const int INF = 0x3f3f3f3f;
// 邻接表
int h[N], e[M], w[M], ne[M], idx;
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int n, p, m; // 三个数:奶牛数 ,牧场数 ,牧场间道路数
int id[N]; // 每只奶牛在哪个牧场
int dis[N]; // 记录起点到任意点的最短路径
bool st[N]; // 标识每个牧场是否入过队列
int dijkstra(int S) {
memset(st, 0, sizeof st);
memset(dis, 0x3f, sizeof dis);
dis[S] = 0;
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({0, S});
while (q.size()) {
PII t = q.top();
q.pop();
int u = t.second;
if (st[u]) continue;
st[u] = true;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (dis[v] > dis[u] + w[i]) {
dis[v] = dis[u] + w[i];
q.push({dis[v], v});
}
}
}
int res = 0;
for (int i = 1; i <= n; i++) { // 遍历每只奶牛
int j = id[i]; // j号牧场
if (dis[j] == INF) return INF; // 如果j号牧场失联了则无法获得结果
res += dis[j]; // 累加一个最小距离
}
return res; // 整体的最小距离
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> p >> m; // 奶牛数,牧场数,牧场间道路数
for (int i = 1; i <= n; i++) cin >> id[i]; // 1 到 N 头奶牛所在的牧场号
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
int ans = INF;
// 枚举每个牧场为出发点,计算它的最短距离和 中的最小值
for (int i = 1; i <= p; i++) ans = min(ans, dijkstra(i));
printf("%d\n", ans);
return 0;
}