题解:洛谷 AT_abc464_a Decisive Battle
【题目来源】
洛谷:AT_abc464_a [ABC464A] Decisive Battle - 洛谷
【题目描述】
The Eastern Army and the Western Army are at war in a certain capital.
Takahashi recorded information about the fighting forces as a string \(S\).
\(S\) contains only the characters E and W, and the number of Es in \(S\) equals the number of soldiers in the Eastern Army, and the number of Ws equals the number of soldiers in the Western Army.
Given the string \(S\) that Takahashi recorded, output East if the Eastern Army has more soldiers than the Western Army, or West if the Western Army has more soldiers than the Eastern Army.
The length of \(S\) is guaranteed to be odd. Thus, it can be proved that exactly one of the two armies strictly outnumbers the other (that is, the two armies cannot have the same number of soldiers).
某都城内,东军与西军正在交战。
高橋将交战双方兵力信息记录为字符串 \(S\)。
\(S\) 仅包含字符 E 和 W,其中 E 的数量等于东军士兵人数,W 的数量等于西军士兵人数。
给定高橋记录的字符串 \(S\),若东军士兵人数多于西军,输出 East;若西军士兵人数多于东军,输出 West。
保证 \(S\) 的长度为奇数。因此可以证明,两支军队中恰好有一支严格多于另一支(即两支军队人数不可能相同)。
【输入】
The input is given from Standard Input in the following format:
\(S\)
【输出】
Output the answer.
【输入样例】
EEWEW
【输出样例】
East
【核心思想】
-
问题分析:给定一个仅由字符
E和W组成的字符串 \(S\),其中E的数量代表东军士兵数,W的数量代表西军士兵数。由于 \(|S|\) 为奇数,两支军队人数不可能相等,只需比较两种字符出现次数的大小关系即可判定胜负。 -
算法选择:
- 直接计数:遍历字符串一次,分别统计
E和W的出现次数 - 一次比较:比较两个计数器的大小,输出对应结果
- 直接计数:遍历字符串一次,分别统计
-
关键步骤:
- 初始化:计数器 \(\text{cnt}_E = 0\),\(\text{cnt}_W = 0\)
- 遍历统计:对字符串 \(S\) 的每个字符 \(S_i\):
- 若 \(S_i = \texttt{`E'}\),则 \(\text{cnt}_E \leftarrow \text{cnt}_E + 1\)
- 若 \(S_i = \texttt{`W'}\),则 \(\text{cnt}_W \leftarrow \text{cnt}_W + 1\)
- 判定输出:
- 若 \(\text{cnt}_E > \text{cnt}_W\),输出
East - 否则输出
West
- 若 \(\text{cnt}_E > \text{cnt}_W\),输出
-
时间/空间复杂度:
- 时间复杂度:\(O(|S|)\),一次遍历完成统计
- 空间复杂度:\(O(1)\),仅使用两个计数器
-
字符串入门计数的核心思想:
- 字符映射:将问题抽象为对有限字符集(仅
E和W)的频率统计,避免复杂的字符串处理 - 奇数长度保证:\(|S|\) 为奇数确保了 \(\text{cnt}_E \neq \text{cnt}_W\),无需处理平局情况,简化判定逻辑
- 单次扫描原则:字符串问题中,若只需统计信息而无需保留完整结构,一次线性扫描是最优策略
- 适用于字符频率比较、简单投票统计等基础字符串处理问题
- 字符映射:将问题抽象为对有限字符集(仅
【算法标签】
入门 #字符串入门
【代码详解】
#include <bits/stdc++.h>
using namespace std;
string s; // 输入字符串,仅包含'E'和'W'
int cnt1, cnt2; // cnt1: 'E'的数量(东军士兵数), cnt2: 'W'的数量(西军士兵数)
int main()
{
cin >> s; // 读入字符串
// 遍历字符串,统计'E'和'W'的数量
for (int i = 0; i < s.size(); i++)
{
if (s[i] == 'E')
cnt1++; // 东军士兵数+1
else
cnt2++; // 西军士兵数+1
}
// 比较两支军队的人数
if (cnt1 > cnt2)
cout << "East" << endl; // 东军人数更多
else
cout << "West" << endl; // 西军人数更多(题目保证不会相等)
return 0;
}
【运行结果】
EEWEW
East
浙公网安备 33010602011771号