跳到正文

题解

【CYEZOI】星云俱乐部测试2:T5题解

AC_Leather约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年6月18日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 3 分钟

版本

  1. v1当前

很显然可以联想到最短路算法,无非就是加了一个磨损度,直接考虑分层图。

考虑分两个维度 xx 和 kk,分别为当前所在的节点编号和剩余船板厚度。于是就:

设disx,kdis_{x,k} 为在 xx 号点剩余船板厚度为 kk 时的最短时间。

那么答案就是:

min⁡1≤k≤KdisB,k\min_{1\le k \le K} dis_{B,k}

所以后面简单套一个堆优化Dijkstra即可。

具体实现(代码+注释):

C++
#include <iostream>
#include <cstring> 
#include <queue>
#include <vector>
using namespace std;

int n, m, k;
vector<int> v[2005], t[2005], h[2005];
int dis[2005][205]; // 第一维是节点编号(x),第二维是剩余厚度(k)
struct node{
	int x, y, d;
	friend bool operator < (const node x, const node y){
		return x.d > y.d; // 堆优化算法重载运算符
	}
};
priority_queue<node> q;
int dij(int st, int ed){
	memset(dis, 0x3f, sizeof(dis));
	dis[st][k] = 0;
	q.push(node{st, k, 0});
	while (!q.empty()){
		int x = q.top().x, y = q.top().y; // 避免重名使用的y代替k
		q.pop();
		if (x == ed) return dis[x][y]; // 直接就是最小的一个(利用dij的特性)
		for (int i = 0; i < v[x].size(); i++)
			if (y > h[x][i] && dis[v[x][i]][y - h[x][i]] > dis[x][y] + t[x][i]){
				dis[v[x][i]][y - h[x][i]] = dis[x][y] + t[x][i];
				q.push(node{v[x][i], y - h[x][i], dis[v[x][i]][y - h[x][i]]});
			}
	}
	return -1; // 无解直接 -1
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> k >> n >> m;
	for (int i = 1; i <= m; i++){
		int x, y, tt, hh;
		cin >> x >> y >> tt >> hh;
		v[x].push_back(y);
		v[y].push_back(x);
		h[x].push_back(hh);
		h[y].push_back(hh);
		t[x].push_back(tt);
		t[y].push_back(tt);
	}
	int a, b;
	cin >> a >> b;
	cout << dij(a, b) << '\n'; // 有返回值函数避免最后循环min求答案(因为我懒)
	return 0;
}
原文