[CSP-J 2025]T1拼数题解
2026-08-19 14:48:51
发布于:浙江
0阅读
0回复
0点赞
[CSP-J 2025]T1拼数题解
题意解答:
这题我认为比19年的第一题简单,不过也属于CSP-J的T1中的简单档,这题简单来说就是将输入的字符串中的数字组装出最大的数字
思路&代码:
本体思路有很多,我能想出2种
1.桶标记数组:
就是创建一个大小为10的数组,在输入后统计每个数字字符的数量,遇到数字字符就将它的数量+1
代码如下
#include <bits/stdc++.h>
using namespace std;
int cnt[10]; // 创建桶标记数组
signed main(){
string s;
cin >> s;
for (auto &it : s){ // 遍历字符串
if (it >= '0' && it <= '9')cnt[it - '0']++; // 当遍历到的字符为数字字符,桶数组中的统计量+1
}
for (int i = 9;i >= 0;i--){ // 从大到小输出
for (int j = 1;j <= cnt[i];j++){
cout << i;
}
}
return 0;
}
2.按照字符串输出
对输入的字符串进行从大到小的排序,因为ASCII码值,数字会排到后面,所以要创建一个标志即已经进入数字区域,如果进入就输出,代码如下
#include <bits/stdc++.h>
using namespace std;
string s;
bool num_part = false;
signed main(){
cin >> s;
sort (s.begin(), s.end(), greater<int>());
for (auto &it : s){
if (it >= '0' && it <= '9')num_part = true;
if (num_part)cout << it;
}
return 0;
}
这里空空如也








有帮助,赞一个