202503-1 2025
题目描述
小 A 有一个整数 x,他想找到最小的正整数 y 使得下式成立:
其中 \operatorname{and} 表示二进制按位与运算,\operatorname{or} 表示二进制按位或运算。如果不存在满足条件的 y,则输出 -1。
输入格式
一行,一个整数 x。
输出格式
一行,一个整数,若满足条件的 y 存在则输出 y,否则输出 -1。
样例输入 1
1025
样例输出 1
1000
提示
对于所有测试点,保证 0 \leq x < 2025。
其中:
- \operatorname{and} 表示按位与运算,运算符为 \&。
- \operatorname{or} 表示按位或运算,运算符为 |。
代码解析
枚举法,从 1 开始枚举,找到符合条件的 i 直接结束主函数,若循环结束也没有找到则输出 -1
#include<bits/stdc++.h>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 1; i <= 2025; i++)
if ((x & i) + (x | i) == 2025) {
cout << i;
return 0;
}
cout << -1;
return 0;
}
202503-2 词频统计
题目描述
在文本处理中,统计单词出现的频率是一个常见的任务。现在,给定 n 个单词,你需要找出其中出现次数最多的单词。在本题中,忽略单词中字母的大小写(即 Apple
、apple
、APPLE
、aPPle
等均视为同一个单词)。
请你编写一个程序,输入 n 个单词,输出其中出现次数最多的单词。
输入格式
第一行,一个整数 n,表示单词的个数;
接下来 n 行,每行包含一个单词,单词由大小写英文字母组成。
输入保证,出现次数最多的单词只会有一个。
输出格式
输出一行,包含出现次数最多的单词(输出单词为小写形式)。
样例输入 1
6
Apple
banana
apple
Orange
banana
apple
样例输出 1
apple
提示
对于所有测试点,1\leq n\leq 100,每个单词的长度不超过 30,且仅由大小写字母组成。
代码解析
GESP 三级考点只有字符串以及数组,解这道题稍微麻烦一些。
解法 1:
在
words
数组中保存新的单词,在数组a
中保存对应的单词出现的次数。
#include<bits/stdc++.h>
using namespace std;
int main() {
string words[105];
int a[105] = {0}, n, cnt = 0;
cin >> n;
while (n--) {
string s;
cin >> s;
for (int i = 0; i < s.size(); i++)
if ('A' <= s[i] && s[i] <= 'Z')
s[i] += 'a'-'A';
int i = 0;
for (i = 0; i <= cnt; i++) {
// 若在数组中找到了单词,则对应的次数 a[i] 加一
if (words[i] == s) {
a[i]++;
break;
}
}
// 若上面的 for 循环正常结束,则说明单词第一次出现,做好记录,cnt是单词数
if (i > cnt) {
words[cnt] = s;
a[cnt]++;
cnt++;
}
}
int max = 0;
for (int i = 1; i < cnt; i++)
if (a[i] > a[max]) max = i;
cout << words[max];
return 0;
}
解法 2:
直接使用
words
字符串记录出现过的单词,每次使用find()
在words
中找是否记录过单词,words
中单词s
首字母的位置可以直接作为桶标记的下标。例:
words:
"apple banana orange"
a:
{2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0 ..... }
表示 2 个apple
,1 个banana
,3 个orange
#include<bits/stdc++.h>
using namespace std;
int main() {
string words;
int n, a[3005] = {0};
cin >> n;
while (n--) {
string s;
cin >> s;
for (int i = 0; i < s.size(); i++)
if ('A' <= s[i] && s[i] <= 'Z')
s[i] += 'a'-'A';
if (words.find(s) == -1)
// 若单词不在 words 中,则拼接,加空格方便最后的输出
words += s + ' ';
else
a[words.find(s)]++;
}
int max = 0;
for (int i = 1; i < 3005; i++)
if (a[i] > a[max]) max = i;
// 输出的时候以空格来区分
for (int i = max; words[i]!=' '; i++)
cout << words[i];
return 0;
}