题解:UVA1062 Containers

UVA 1062

原题链接

题目大意

已知集装箱到达顺序,它们需按字母顺序(A 到 Z)装船,且只能取堆顶集装箱。求在不移动压在上方集装箱的前提下,将所有集装箱顺利装船所需的最少堆栈数量。

解题思路

容易看出,题目要求的是将一个字符串分为若干个单调不升子串,而答案就是子串的最小数量。利用贪心的思路不难想到,我们要让每一个子串尽可能长。

下面提供两个算法。

算法一:O(nlog⁡n)O(n \log n)

可以维护一个列表,记录下每个子串的末位字符。我们按照从左到右的顺序依次读输入串的每个字符,并遍历上述列表。为了使得每个子串尽可能长,贪心地选择那个末位字符大于等于当前字符且最小的子串,然后把当前字符放到它的末尾;如果找不到,则新建一个子串。这一过程可用二分查找。

值得一提的是,第二个样例 CBACBACBACBACBA,一种显而易见的分割方式是 CCCCC、BBBBB、AAAAA,而用上述思路得到的是 CBAAAAA、CBBBB、CCC,答案是正确的。

char s[1005];
vector<char> lastChar;
int len;
int kase;

signed main() {
	while (1) {
		scanf("%s", s);
		if (s[0] == 'e')
			break;
		lastChar.clear();
		len = strlen(s);
		for (int i = 0; i < len; i++) {
			char now = s[i];
			auto it = lower_bound(lastChar.begin(), lastChar.end(), now);
			if (it != lastChar.end()) {
				*it = now;
			} else {
				lastChar.push_back(now);
			}
		}
		printf("Case %d: %d\n", ++kase, (int)lastChar.size());
	}
	return 0;
}

算法二:O(n)O(n)

考虑到字符集只有 26 个字母,可以直接用数组记录以每个字母结尾的子串的数量,每次遍历即可。

char s[1005];
int cntOfSubstr['Z' + 5];
int len, ans;
int kase;
bool found;

signed main() {
	while (1) {
		scanf("%s", s);
		if (s[0] == 'e')
			break;
		memset(cntOfSubstr, 0, sizeof cntOfSubstr);
		len = strlen(s);
		ans = 0;
		for (int i = 0; i < len; i++) {
			char now = s[i];
			found = false;
			for (int j = now; j <= 'Z'; j++) {
				if (cntOfSubstr[j]) {
					cntOfSubstr[j]--;
					cntOfSubstr[now]++;
					found = true;
					break;
				}
			}
			if (!found) {
				ans++;
				cntOfSubstr[now]++;
			}
		}
		printf("Case %d: %d\n", ++kase, ans);
	}
	return 0;
}

有趣的是,在当前的数据范围下,O(n)O(n) 算法可能还没有 O(nlog⁡n)O(n \log n) 算法跑得快(不考虑 vector 等的常数)。


题解:UVA1062 Containers
https://pvbelln.me/2026/07/22/sol-uva1062/
作者
PvbeLLN
发布于
2026年7月22日
许可协议