10.11总结

· · 个人记录

T678243 最佳方案 (plan)

简化题意

给定一个正整数 n ,求在最少经过几次 n\div2 或 n-x 运算后,n 变为负数的方案数。

思路

1.模拟

  • 使用贪心策略,每次选择使 n 尽可能减小的操作。

2.复杂度分析

  • 时间复杂度:O(\log n),每次操作都将 n 减小。
  • 空间复杂度:O(1),只使用了少量变量

代码实现

#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个),让火箭从 (0,0) 按剩余指令(U/D/R/L对应上下左右移动)最终抵达目标位置 (P_x,P_y) 。

思路

1. 贪心

  • 首先,我们可以得知火箭需要向右移动 P_x 次,向上移动 P_y 次。
  • 因此,我们需要在指令串中找到足够的 R 和 U 指令。
  • 其次,如果 P_x 为负数,则需要足够的 L 指令;如果 P_y 为负数,则需要足够的 D 指令。
  • 遍历指令串,统计各个方向的指令数量。
  • 如果需要的字符数量都能满足,则输出 "YES";否则输出 "NO"。

2. 复杂度分析

  • 时间复杂度:O(n),其中 n 是指令串的长度。
  • 空间复杂度:O(1),只使用了常数个变量。

代码实现

#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. 模拟

  • 对于每次修改操作,直接修改字符串并使用双指针判断是否为回文串。
  • 时间复杂度O(n^2),每次修改后检查字符串,会超时。

2. 优化

  • 使用一个计数器记录字符串中不匹配的字符对数。
  • 每次修改时,只需检查修改位置及其对称位置的字符是否匹配,更新计数器。
  • 时间复杂度O(n+m),其中n为字符串长度,m为修改次数。

3. 复杂度分析

  • 时间复杂度:O(n+m)
  • 空间复杂度:O(1)

代码实现

#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;
}