跳到正文

题解

题解:P13455 [GCJ 2008 Qualification] Train Timetable

hashing约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月26日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 4 分钟
获赞
2
题目
P13455

版本

  1. v1当前

题目大意

求出在两站早上分别需要多准备多少列车才能满足给定的时刻表运行需求。

题目思路

用贪心做即可。首先把给的字符串转换成时间并统一成分钟数,随后排序所有事件,时间少的优先,这样才能确保最后答案是最优解。最后模拟列车行驶过程计算各站点所需的最少准备列车数‌(详细模拟过程请看代码部分)。

代码

C++
#include<bits/stdc++.h>
using namespace std;
const int M = 1e4+10;  // 定义最大事件数量常量
struct node {
	int time;      // 事件时间(分钟数)
	bool flag;     // 事件类型:true=出发事件,false=可用事件
	bool from_a;   // 事件所属车站:true=A站,false=B站
} nodes[M*2];      // 存储所有事件的数组

// 将给定的字符串转换为时间
int check(string s) {
	return stoi(s.substr(0,2))*60+stoi(s.substr(3,2));
}

bool cmp(node x, node y) {
	if(x.time != y.time) return x.time < y.time;
	return !x.flag;
}

int main() {
	int T;
	cin >> T;
	for(int x = 1; x <= T; x ++) {
		int cnt, na, nb;  // cnt=周转时间,na=A→B车次,nb=B→A车次
		cin >> cnt >> na >> nb;
		int res = 0;
		// 处理A→B方向车次
		for(int i = 0; i < na; i ++) {
			string dep, arr;  // 出发/到达时间字符串
			cin >> dep >> arr;
			nodes[res ++] = {check(dep), true, true};   // A站出发事件
			nodes[res ++] = {check(arr)+cnt, false, false}; // B站可用事件,这里+cnt是因为还要再周转
		}
		// 处理B→A方向车次
		for(int i = 0; i < nb; i ++) {
			string dep, arr;
			cin >> dep >> arr;
			nodes[res++] = {check(dep), true, false};  // B站出发事件
			nodes[res++] = {check(arr)+cnt, false, true};  // A站可用事件
		}
		// 排序所有事件, 时间优先
		sort(nodes, nodes+res, cmp);
		
		int c_a = 0, s_a = 0;  // c_a=A站可用列车数,s_a=A站需要多准备的列车
		int c_b = 0, s_b = 0;  // c_b=B站可用列车数,s_b=B站需要多准备的列车

		for(int i = 0; i < res; i ++) {
			if(nodes[i].flag) {
				if(nodes[i].from_a) {
					if(c_a) c_a--;  // A站有可用列车则消耗
					else s_a++;     // 否则增加
				} else {
					if(c_b) c_b--;  // B站同理
					else s_b++;
				}
			} else {
				if(nodes[i].from_a) c_a++;  // A站增加可用列车
				else c_b++;                 // B站增加可用列车
			}
		}
		cout << "Case #" << x << ": " << s_a << " " << s_b << '\n';
	}
	return 0;
}

AC记录

希望这篇题解能够帮助到你。

原文