vinayak7989

Untitled

Sep 21st, 2022
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | Source Code | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. /*
  4. floor will be zero if 2^x > len
  5. therefore 2^x <= len (i.e. n)
  6. 2^x <= n
  7. there x <= 9
  8. there binary representation of x can set bit only in first 4 bits
  9. so when taking xor or two substring only last 4 bits can differ rest all
  10. have to be same
  11.  
  12. we can brute force those last atmost 4 length substring and then maximize length
  13. to the left of these substring as long as s[i] == t[i] .. store this max length in dp
  14. */
  15. int MaxProfit(int N, string s, string t) {
  16.       int ans = 0;
  17.       int dp[N][N] = {};
  18.       for(int i = 0; i < N; i++) {
  19.             for(int j = 0; j < N; j++) {
  20.                   if(s[i] != t[j]) continue;
  21.                   if(i && j) dp[i][j] = 1 + dp[i-1][j-1];
  22.             }
  23.       }
  24.       for(int i = 0; i < N; i++) {
  25.             for(int j = 0; j < N; j++) {
  26.                   int val = 0;
  27.                   for(int k = 0; k < 4 && i+k < N && j + k < N; k++) {
  28.                         val *= 2;
  29.                         val += s[i+k] != t[j+k];
  30.                         int len = k+1 + (i && j ? dp[i-1][j-1] : 0);
  31.                         ans = max(ans, len / (1 << val));
  32.                   }
  33.             }
  34.       }
  35.       return ans;
  36. }
  37.  
  38. int main() {
  39.       int t;
  40.       cin >> t;
  41.       while(t--) {
  42.             int n;
  43.             string s, t;
  44.             cin >> n >> s >> t;
  45.             cout << MaxProfit(n, s, t) << "\n";
  46.       }
  47. }
Tags: C++
Add Comment
Please, Sign In to add comment