求助!!!怎么用二分改!!!玄关!!!

P1439 【模板】最长公共子序列

135791a @ 2024-08-01 10:32:23

#include<bits/stdc++.h>
using namespace std;
int s[100005],s1[100005];
int n;
int dp[100005];
int main() {
    cin>>n;
    for (int i=0;i<n;i++) cin>>s[i];
    for (int i=0;i<n;i++) cin>>s1[i];
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=n;j++) {
            dp[j]=max(dp[j],dp[j-1]);
            if (s[i-1]==s1[j-1]) dp[j]=max(dp[j],dp[j-1]+1);
        }
    }
    cout<<dp[n];
    return 0;
}

by Ahws_rwhy @ 2024-08-19 08:59:54

@135791a

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 2;
int read() {
    int t = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-') f = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        t = t * 10 + c - '0';
        c = getchar();
    }
    return t * f;
}
int n;
int a[N], b[N];
int dp[N];
int num[N];
int ans;
int midsearch(int x , int l , int r) {
    int mid = 0;
    while(l < r) {
        mid = (l + r) >> 1;
        if(dp[mid] > x) r = mid;
        else l = mid + 1;
    }
    return l;
}
int main() {
    n = read();
    for (int i = 1; i <= n; i++) a[i] = read();
    for (int i = 1; i <= n; i++) b[i] = read();
    for(int i = 1; i <= n; i++) num[a[i]] = i;
    for(int i = 1; i <= n; i++) {
        if(num[b[i]] > dp[ans]) {
            dp[++ans] = num[b[i]];
//          cout << ans << " A";
        }
        else {
            int sum = midsearch(num[b[i]] , 1 , ans);
//          cout << sum << " S";
            dp[sum] = min(dp[sum] , num[b[i]]);
        }
    }
//    for(int i = 1; i <= n; i++) {
//      for(int j = 1; j <= n; j++) {
//          if(a[i] == b[j]) {
//              dp[i][j] = dp[i - 1][j - 1] + 1;
//          }
//          else {
//              dp[i][j] = max(dp[i - 1][j] , dp[i][j - 1]);
//          }
//      }
//  }
    cout << ans;
    return 0;
}

by 135791a @ 2024-08-19 13:12:01

@rwhy OK


|