T678243 最佳方案 (plan)
简化题意
给定一个正整数 ,求在最少经过几次 或 运算后, 变为负数的方案数。
思路
1.模拟
- 使用贪心策略,每次选择使 尽可能减小的操作。
2.复杂度分析
- 时间复杂度:,每次操作都将 减小。
- 空间复杂度:,只使用了少量变量
代码实现
#include<bits/stdc++.h>
using namespace std;
int t;
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>t;
while(t--){
int n,x,cnt=0;
cin>>n>>x;
while(n>=0){
if(int(n/2)<n-x){
n/=2;
}
else{
n-=x;
}
cnt++;
}
cout<<cnt<<'\n';
}
return 0;
}T678244 太空旅行(space)
简化题意
判断能否通过删除指令串s中的部分字符(可删0个),让火箭从 按剩余指令(U/D/R/L对应上下左右移动)最终抵达目标位置 。
思路
1. 贪心
- 首先,我们可以得知火箭需要向右移动 次,向上移动 次。
- 因此,我们需要在指令串中找到足够的 和 指令。
- 其次,如果 为负数,则需要足够的 指令;如果 为负数,则需要足够的 指令。
- 遍历指令串,统计各个方向的指令数量。
- 如果需要的字符数量都能满足,则输出 “YES”;否则输出 “NO”。
2. 复杂度分析
- 时间复杂度:,其中 是指令串的长度。
- 空间复杂度:,只使用了常数个变量。
代码实现
#include<bits/stdc++.h>
using namespace std;
int t;
int main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>t;
while(t--){
int x,y,ans=0;
cin>>x>>y;
string s;
cin>>s;
int op1=0,op2=0;
if(x<=0) op1=1;
else op1=2;
if(y<=0) op2=1;
else op2=2;
x=abs(x);
y=abs(y);
for(int i=0;i<s.size();i++){
if(op1==1&&s[i]=='L'){
x--;
}
else if(op1==1&&s[i]=='R') ans++;
if(op1==2&&s[i]=='R'){
x--;
}
else if(op1==2&&s[i]=='L') ans++;
if(op2==1&&s[i]=='D'){
y--;
}
else if(op2==1&&s[i]=='U') ans++;
if(op2==2&&s[i]=='U'){
y--;
}
else if(op2==2&&s[i]=='D') ans++;
}
if(x>0||y>0){
cout<<"NO\n";
}
else{
cout<<"YES\n";
}
}
return 0;
}
T678245 回文串(string)
简化题意
给定一个字符串,求每次修改指定字符后是否是回文串。
思路
1. 模拟
- 对于每次修改操作,直接修改字符串并使用双指针判断是否为回文串。
- 时间复杂度,每次修改后检查字符串,会超时。
2. 优化
- 使用一个计数器记录字符串中不匹配的字符对数。
- 每次修改时,只需检查修改位置及其对称位置的字符是否匹配,更新计数器。
- 时间复杂度,其中为字符串长度,为修改次数。
3. 复杂度分析
- 时间复杂度:
- 空间复杂度:
代码实现
#include<bits/stdc++.h>
using namespace std;
int n,b,a[100010],c=-1e9;
long long sum[100010];
int main(){
cin>>n>>b;
for(int i=1;i<=n;i++){
cin>>a[i];
sum[i]=sum[i-1]+a[i];
}
for(int i=0;i<=n;i++){
int l=i,r=n,res=0;
while(l<=r){
int mid=(l+r)/2;
if(sum[mid]-sum[i]<=b){
res=mid;
l=mid+1;
}
else r=mid-1;
}
c=max(res-i,c);
}
cout<<c;
return 0;
}