【题解】JZOJ6578 / 洛谷P5201[USACO2019Jan]Shortcut G

洛谷 P5201 [USACO19JAN] Shortcut G

题意

在一个带权无向连通图上,每个点有 a i a_i ai 只奶牛,奶牛会走最短路径到 1 1 1,如果有多条路径,选择字典序最小的,定义移动总时间为所有奶牛走到 1 1 1 的时间之和。你可以修建一条从任意一点到 1 1 1 的边权为 t t t 的边,奶牛只有在平时走到 1 1 1 的路上看到这条边才会走。求最多能减少多少移动总时间。

题解

题目保证了对于每个点都有唯一的路径走到 1 1 1,那么可以建出一棵树,根节点为 1 1 1。

然后统计一下子树中奶牛数量总和,对于每个点尝试建时间为 t t t 的新边,可以 O ( 1 ) O(1) O(1) 求出减少的移动总时间。设 j j j 为 i i i 的子树中的节点,则减少的时间为 ( d i s i − t ) ∑ j a j (dis_i-t)\sum\limits_{j}a_j (disi−t)j∑aj。

时间复杂度 O ( n ) O(n) O(n)。

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 50005;
int n, m, t, a[N], vis[N];
LL dis[N], cnt[N], ans = 0;
int cn1 = 0, fi1[N], nx1[N << 1], to1[N << 1], va1[N << 1], cn2 = 0, fi2[N], nx2[N << 1], to2[N << 1];
void ad1(int u, int v, int w) {
	cn1++, nx1[cn1] = fi1[u], fi1[u] = cn1, to1[cn1] = v, va1[cn1] = w; 
	cn1++, nx1[cn1] = fi1[v], fi1[v] = cn1, to1[cn1] = u, va1[cn1] = w;
}
void ad2(int u, int v) { cn2++, nx2[cn2] = fi2[u], fi2[u] = cn2, to2[cn2] = v; }
struct node {
	int r;
	LL dis;
	bool operator < (const node &T) const { return dis > T.dis; }
};
priority_queue<node> pq;
void dij(int r) {
	memset(dis, 0x3f, sizeof(dis)), dis[r] = 0;
	pq.push((node){r, 0});
	while (!pq.empty()) {
		node h = pq.top();
		pq.pop();
		if (vis[h.r]) continue;
		vis[h.r] = 1;
		for (int i = fi1[h.r]; i; i = nx1[i])
			if (dis[to1[i]] > dis[h.r] + va1[i])
				dis[to1[i]] = dis[h.r] + va1[i], pq.push((node){to1[i], dis[to1[i]]});
	}
}
void dfs(int r) {
	cnt[r] = a[r];
	for (int i = fi2[r]; i; i = nx2[i]) dfs(to2[i]);
	for (int i = fi2[r]; i; i = nx2[i]) cnt[r] += cnt[to2[i]];
	if (t < dis[r]) ans = max(ans, (dis[r] - t) * cnt[r]);
}
int main() {
	scanf("%d%d%d", &n, &m, &t);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
	for (int i = 1, u, v, w; i <= m; i++) scanf("%d%d%d", &u, &v, &w), ad1(u, v, w);
	dij(1);
	for (int i = 2; i <= n; i++) {
		int x = n;
		for (int j = fi1[i]; j; j = nx1[j])
			if (dis[i] == dis[to1[j]] + va1[j])
				x = min(x, to1[j]);
		ad2(x, i);
	}
	dfs(1);
	printf("%lld", ans);
	return 0;
}
相关推荐
努力学算法的蒟蒻7 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495647 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦7 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
2401_841495647 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli7 小时前
优选算法-字符串
算法
qq7422349847 小时前
APS系统与OR-Tools完全指南:智能排产与优化算法实战解析
人工智能·算法·工业·aps·排程
A尘埃8 小时前
超市购物篮关联分析与货架优化(Apriori算法)
算法
.小墨迹8 小时前
apollo学习之借道超车的速度规划
linux·c++·学习·算法·ubuntu
不穿格子的程序员8 小时前
从零开始刷算法——贪心篇1:跳跃游戏1 + 跳跃游戏2
算法·游戏·贪心
大江东去浪淘尽千古风流人物8 小时前
【SLAM新范式】几何主导=》几何+学习+语义+高效表示的融合
深度学习·算法·slam