跳到正文

题解

题解:B4156 [厦门小学生 C++ 2023] 太空旅行

Sunset_afterglow约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月31日
篇幅
约 2 分钟
题目
B4156

版本

  1. v1当前

这道题目虽然很简单,但小学放紫就过分了哈,陈哲的题目最厉害了。

思路

一眼贪心,我们考虑此题贪心的组成,即排序和记录答案。

记录答案

如果在排序最优的情况下,到达 ii 飞船时的答案应等于所有前面所有飞船,第二段航线的时间之和,与到达 i−1i - 1 飞船时的答案,中的最大值,加上飞船 ii 走第二段航线的时间。具体如下式。

answeri=max⁡(∑j=1iV(j),answeri−1)+U(i)answer_i=\max(\sum_{j=1}^i V(j) ,answer_{i-1})+U(i)

最终的答案为 answernanswer_n。

排序

第一段航线应该把花时间短的飞船安排在前面,第二段航线应该让花的时间长的飞船排在前面,优先第一段航线用时,比第二段航线用用时短的飞船。

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
inline int read() {
	int x = 0 ,f = 1;
	char ch = getchar();
	while('0' > ch || ch > '9'){
		if(ch == '-') f = -1;
		ch = getchar();
	}
	while('0' <= ch && ch <= '9') {
		x = (x << 1) + (x << 3) + (ch & 15);
		ch = getchar();
	}
	return x * f;
}
const int N = 25005;
struct point {
	int u ,v;
	bool operator <(const point &a)const {
		if(u < v) {
			if(a.u < a.v)return u < a.u;
			else return true;
		}
		else {
			if(a.u > a.v)return v > a.v;
			else return false;
		}
	}
}val[N];
int answer ,n ,tp;
signed main(){
	n = read();
	for(int i = 1 ,u ,v;i <= n;++ i) {
		u = read() ,v = read();
		val[i] = point{u ,v};
	}
	sort(val + 1 ,val + n + 1);
	for(int i = 1;i <= n;++ i) {
		tp += val[i].u;
		answer = max(tp ,answer) + val[i].v;
	}
	cout << answer;
	return 0;
}

完结撒花

原文