# 官方题解|欢乐赛#46
2025-05-07 12:31:33
发布于:浙江
官方题解|欢乐赛#46
1.字典序最小
思路分析
字典序列比较方法:
- 逐字符比较:从左到右依次比较两个字符串的对应字符
- ASCII值决定顺序:比较字符的ASCII码值
- 小写字母 > 大写字母 > 数字
- 例如:'a'(97) > 'A'(65) > '0'(48)
- 长度规则:如果所有对应字符相同,则较短的字符串较小
所以在这三个字符串中 "C++"的字典序最小。
代码分析
#include <bits/stdc++.h>
using namespace std;
int main(){
cout << "C++";
return 0;
}
2.消息数量
思路分析
本题考查分支语句。对于消息数量不超过99的,直接输出消息数量;对于消息数量超过99的输出"99+"。用if - else 判断一下即可。
代码分析
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
if(n > 99) cout << "99+";
else cout << n;
return 0;
}
3.输出平方数
思路分析
本题考查对for循环的理解。本题可以for循环从1 ~n,每次循环的时候输出 即可。
代码分析
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
for(int i = 1; i <= n; i ++ ){
cout << i * i << ' ';
}
cout << endl;
}
4. 激活密钥
思路分析
本题又考排序了。只需要将数组进行倒序,然后输出前m大的即可。将数组倒序,可以采用C++中的sort,写一个cmp函数即可。
代码分析
#include <bits/stdc++.h>
using namespace std;
int a[1000010], n, m;
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++ ){
cin >> a[i];
}
sort(a + 1, a + 1 + n, [&](int A, int B){
return A > B;
});
for(int i = 1; i <= m; i ++ ){
cout << a[i] << ' ';
}
cout << endl;
return 0;
}
5. 揭示预言
思路分析
本题要求结果是十进制,那么可以先将 x 和 y转十进制,然后直接相乘即可。
代码分析
#include <bits/stdc++.h>
using namespace std;
int main(){
string s1, s2;
cin >> s1 >> s2;
long long x = 0, y = 0, mi8 = 1, mi2 = 1;
reverse(s1.begin(), s1.end());
for(auto it : s1){
x += mi8 * (it - '0');
mi8 *= 8;
}
reverse(s2.begin(), s2.end());
for(auto it : s2){
y += mi2 * (it - '0');
mi2 *= 2;
}
cout << x * y << endl;
return 0;
}
6.不同的数
思路分析
本题可以采用深度优先搜索 或者 二进制枚举,枚举所有的合法方案,然后利用set来维护一下不同的数的数量即可。
代码分析
#include <bits/stdc++.h>
using namespace std;
const int N = 25;
int a[N], n, m;
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i ++ ){
cin >> a[i];
}
set<int>s;
for(int i = 0; i < 1 << n; i ++){
int sum = 0, cnt = 0;
for(int j = 0; j < n; j ++ ){
if(i >> j & 1){
sum += a[j + 1];
cnt ++;
}
}
if(cnt == m) s.insert(sum);
}
cout << s.size() << endl;
}
int main(){
int t;
cin >> t;
while(t -- ){
solve();
}
return 0;
}
全部评论 1
好
2025-05-07 来自 广东
0
有帮助,赞一个