T637642 比较数字
分析:找到第一个0,再将0后所有数字换成1
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string s;
bool f;
int main(){
cin >> s;
int n = s.size();
for(int i = 0;i < n;i++){
if(s[i] == '0'){//找到第一个0
for(int j = i;j < n;j++){
cout << '1';
}
return 0;
}
cout << s[i];
}
return 0;
}
错误代码
错因:只是将所有0换成1,并不是最小值
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string s;
bool f;
int main(){
cin >> s;
int n = s.size();
for(int i = 0;i < n;i++){
if(s[i] == '0'){
cout << '1';
}
else cout << s[i];
}
return 0;
}T637627 张的弓
分析:根据图可得:
-
- [前面是步数,后面是距离] 1 1
-
- 2 2
- 3 3
- 4 2
- 5 1
- 6 2
- 7 3
- 8 4
- 9 5
- 10 4
- 11 3
根据以上样例可得,每2n - 1可分为一组,第k步可在这一组中寻找,可将k / n设为x,当x为偶数时横坐标为k % n, 奇数使横坐标为n - (k % n + 1)
#include<bits/stdc++.h>
using namespace std;
long long t,n,m,k;
int main(){
cin >> t;
while(t--){
cin >> n >> m >> k;
long long x = k / n,sum = 0;//x是第纵坐标,sum是横坐标
if(x % 2 == 0){//偶数
sum = k % n;
}else sum = n - (k % n + 1);//y往左走时
cout << x + sum << '\n';
}
return 0;
}
T637602 可可口乐
分析:出现“最少”故使用广搜
#include<bits/stdc++.h>
using namespace std;
struct node{
string s;
int step;
};
map<string,bool> mp;
string s,ed = "cocacola";
void bfs(){
queue<node>q;
q.push({s,0});
mp[s] = 1;//用map作为标记数组
while(q.size()){
node f = q.front();
q.pop();
if(f.s == ed){
cout << f.step;
return ;
}
for(int i = 0;i < s.size();i++){//数据量只有8,直接双重循环
for(int j = 0;j < s.size();j++){
string ss = f.s;//避免直接修改原数组
swap(ss[i],ss[j]);
if(mp.count(ss) == 0){
mp[ss] = 1;
q.push({ss,f.step + 1});
}
}
}
}
cout << -1;
return ;
}
int main(){
cin >> s;
bfs();
return 0;
}
错误代码
没别的,就是想太简单了,下次会注意关于搜索的字眼
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string s,ed = "cocacola";
int ans;
int main(){
cin >> s;
for(int i = 0;i < s.size();i++){
if(ed[i] != s[i]) ans++;
}
cout << ceil(ans / 2);
return 0;
}
T637561 小梦的守卫
分析:
1.依据题意,僵尸从两边同时进攻,所以要求出正序前缀和和倒叙前缀和
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,q,t,ans;
ll a[200005],s[200005],rs[200005],b[200005];
int main(){
cin >> n >> q;
for(int i = 1;i <= n;i++){
cin >> a[i];
s[i] = s[i - 1] + a[i];//正序前缀和
b[n - i + 1] = a[i];
}
for(int i = 1;i <= n;i++) rs[i] = rs[i - 1] + b[i];//倒叙前缀和
while(q--){
cin >> t;
ll sum = n,i = 1,j = n;
int l = upper_bound(s + 1,s + n + 1,t) - s - 1;//定义l和r查找s和rs的左右边界,即查找左右僵尸能吃的范围
int r = lower_bound(rs + 1,rs + 1 + n,t) - rs - 1;
if(l + r > n) cout << "Zombies ate your brain!" << '\n'; //可理解为左右僵尸的范围出现了“重合”,也就是被吃光了
else cout << n - l - r << '\n';//剩余士兵的数量
}
return 0;
}