3.1

· · 个人记录

T738006 前缀子序列

考察知识点:

同向双指针

正确思路:

用双指针计算出k最大的位置,然后输出。

正确代码:

#include<bits/stdc++.h>
using namespace std;
int t,n,m;
string s1,s2;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>t;
    while(t--){
        cin>>n>>m;
        cin>>s1>>s2;
        int l=0,r=0;
        while(l<n and r<m){
            if(s1[l]==s2[r])l++,r++;
            else r++;
        }
        cout<<l<<'\n';
    }
    return 0;
}

T738011 子串与子序列

考察知识点:

同向双指针

正确思路:

遍历字符串s2,找出最短的长度。

正确代码:

#include<bits/stdc++.h>
using namespace std;
int t,n,m;
string s1,s2;
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>t;
    while(t--){
        cin>>s1>>s2;
        int ans=0;
        int n=s1.size(),m=s2.size();
        for(int i=0;i<m;i++){
            int l=0,r=i;
            while(l<n and r<m){
                if(s1[l]==s2[r])l++,r++;
                else l++;
            }
            ans=max(ans,r-i);
        }
        cout<<n+m-ans<<'\n';
    }
    return 0;
}

P12342 [蓝桥杯 2025 省 B/Python B 第二场] 数列差分

考察知识点:

同向双指针

正确思路:

先把数组排序,再组个进行比较,最后输出最少操作数。

正确代码:

#include<bits/stdc++.h>
using namespace std;
int n;
int a[100005],b[100005];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];
    for(int i=1;i<=n;i++)cin>>b[i];
    sort(a+1,a+1+n);
    sort(b+1,b+1+n);
    int l=1,r=1,cnt=0;
    while(l<=n and r<=n){
        if(a[l]>b[r])l++,r++;
        else cnt++,l++;
    }
    cout<<cnt;
    return 0;
}

P12257 [蓝桥杯 2024 国 Java B] 分组

考察知识点:

同向双指针

正确思路:

先给数组排序,然后用双指针计算出最少可以分多少租。

正确代码:

#include<bits/stdc++.h>
using namespace std;
int n;
int a[100005];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];
    sort(a+1,a+1+n);
    int h=n/2+1,cnt=0;
    int l=1,r=h;
    while(l<=n/2 and r<=n){
        if(a[r]>=a[l]*2)cnt++,l++,r++;
        else r++;
    }
    cout<<cnt;
    return 0;
}

P1748 H 数

考察知识点:

同向双指针

正确思路:

输入后计算出a数组的所有值,最后输出a[n]。

正确代码:

#include<bits/stdc++.h>
using namespace std;
long long n;
long long a[10005];
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>n;
    a[1]=1;
    int l2=1,l3=1,l5=1,l7=1;
    for(int i=2;i<=n;i++){
        long long x=min(a[l2]*2,min(a[l3]*3,min(a[l5]*5,a[l7]*7)));
        a[i]=x;
        if(x==a[l2]*2)l2++;
        if(x==a[l3]*3)l3++;
        if(x==a[l5]*5)l5++;
        if(x==a[l7]*7)l7++;
    }
    cout<<a[n];
    return 0;
}