T1:竖着读
给定n个字符串,每个字符串长度都为m,然后从上到下获取字符串,不同字符串之间用空格分开,收集到的字符串的前导0要去除,且排序。
思路
- 先for循环遍历第一个字符串:
[i]
- 第二个for循环从上往下遍历:
[j][i]
,并收集得到的字符串 - 将结果去除前导0,并存储在结果中
/*
3
0123
1234
2345
4
0000
0101
1011
0111*/
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
vector<string> nums(n);
while(n--)
cin >> nums[i];
vector<int> res;
for(int i = 0; i < nums[0].size(); i++){
string tmp;
for(int j = 0; j < nums.size(); j++){
tmp += nums[j][i];
}
res.push_back(stoi(tmp));
}
sort(nums.begin(), nums.end());
for(int i = 0; i < res.size(); i++){
cout << res[i];
if(i != res.size() - 1)
cout << " "; // 此处' '不知道可不可以
}
return 0;
}
知识点
- 竖着遍历(记忆中是力扣14最长公共前缀的纵向扫描方式)
- 去除前导0:stoi(说是C++11的新特性) 、stringstream、vector逆序删除
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string str = "00001001";
cout << stoi(str) << endl;
stringstream ss;
int a = 0;
ss << str;
ss >> a;
cout << a << endl;
vector<int> res;
for(int i = str.size() - 1; i >= 0; i--){
res.push_back(str[i] - '0');
}
while(res.size() > 1 && res.back() == 0)
res.pop_back();
for(int i = res.size() - 1; i >= 0; i--){
cout << res[i];
if(i != 0)
cout << " ";
}
return 0;
}
本人犯错的点
- 前导0自己写了个while循环去除,但是sort排序错误
- 10 101 11 111的排序结果不是 10 11 101 111(题目给定)
T2:质数下标
给定一个数组,下标从1~n,将数组中下标为非质数对应的元素删除,得到新数组,循环删除返回数组中的最后留着的元素值。
- 将素数全部存在一个bool数组中,每次循环删除的时候判断是否为质数
- 使用赋值构造函数将原数组替换为新数组
- 循环结束条件:数组元素个数为1
/*
[3 1 1 4 5 6]
[1 1 5]
[5]
*/
#include <iostream>
using namespace std;
const int maxn = 1e5 + 10;
bool is[maxn];
void isPrim(int n){ // 质数筛,优化版本
memset(is, true, sizeof(maxn));
for(int i = 2; i * i < n; i++){
if(is[i]){
for(int j = i * i; j < n; j += i){
is[j] = false;
}
}
}
}
int getNumber(vector<int>& a){
while(true){
vector<int> res;
for(int i = 0; i < a.size(); i++){
if(is[i + 1])
res.push_back(a[i]);
}
if(res.size() == 1)
return res[0];
a = res; // 赋值构造函数
}
}
int main(){
vector<int> a{3,1,1,4,5,6}; // C++11新特性, 列表初始化
isPrim(maxn);
is[1] = false; // 1不是质数
int ans = getNumber(a);
cout << ans << endl;
return 0;
}
犯错点:看错题目(以为是下标和元素值都不是质数才删除)和 1不是质数
知识点
- 质数筛
- 滚动数组的思想
- 认真学习语文