T1:竖着读
给n个数字字符串,每个字符串长度都为m,然后按照每一列从上往下读构成m个字符串,求这m个排序后的字符串,去掉前导0,排序输出。
例子:
输入:
3
01234
12345
01234
输出:
10 121 232 343 454
此题比较简单,就是直接把列序列用字符串存起来,然后使用stoi将字符串转成整数,接着再进行排序就可以A了。
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
vector<string> res;
while(n--){
string s;
cin>>s;
res.push_back(s);
}
vector<int> tmp;
for(int i = 0; i < res[0].size(); i++){
string cur = "";
for(int j = 0; j < res.size(); j++){
cur += res[j][i];
}
tmp.push_back(stoi(cur));
}
sort(tmp.begin(), tmp.end());
for(int i = 0; i < tmp.size() - 1; i++){
cout<<tmp[i]<<" ";
}
cout<<tmp[tmp.size() - 1]<<endl;
return 0;
}
T2: 删除非质数下标后的最终元素
给一个数组,下标从1-n,每次淘汰下标非质数的数字,但是题目给的让我很迷惑,题目删除的即说ai且i为非质数的,让我好一顿纠结!最后就是循环删除,问最后剩下的一个数字是什么?
使用质数筛法进行处理。
class Solution {
public:
const int MAXN = 1e5+10;
int prime[MAXN+1];
void getPrime(){
memset(prime, 0, sizeof(prime));
for(int i = 2; i <= MAXN; i++){
if(!prime[i]) prime[++prime[0]] = i;
for(int j = 1; j <= prime[0] and prime[j] <= MAXN /i; j++){
prime[prime[j]*i] = 1;
if(i % prime[j] == 0) break;
}
}
}
int getNumber(vector<int>& a) {
getPrime();
//将所有素数存入set中
unordered_set<int> st;
for(int i = 1; i <= prime[0]; i++) {
st.insert(prime[i]);
}
//这里使用两个交替数组,用来存储剩余数字
vector<int> pre = a, cur;
while(cur.size() != 1){
cur.clear();
for(int i = 1; i <= pre.size(); i++){
if(st.count(i)) cur.push_back(pre[i-1]);
}
pre = cur;
}
return cur[0];
}
};
T3:防御攻击最小距离
给一堆字符串代表一排士兵,士兵编号1~n,字符串中’0’的士兵代表进攻性的,‘1’的代表防御性的,每个士兵的攻击力或守备力为其下标值。将士兵分组,0~pos的是进攻组,只算攻击力,pos+1~n的是防御组,只算防御力。pos可以取0~n。求攻击组的攻击力和防御组的防御力的差的绝对值的最小值。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int n;
string str;
cin >> n >> str;
int len = n;
vector<ll> attack(n+2, 0), protect(n+2, 0);
//攻击做前缀
for(int i = 1; i <= len; i++){
attack[i] = attack[i-1];
if(str[i-1] == '0') attack[i] += i;
}
//防御做后缀
for(int i = len; i >= 1; i--){
protect[i] = protect[i+1];
if(str[i-1] == '1') protect[i] += i;
}
ll value = INT_MAX;
for(int i = 0; i <= len; i++){
ll cur = abs(attack[i] - protect[i+1]);
if(cur < value) value = cur;
}
cout << value;
return 0;
}