Advertisement
VladSmirN

Наибольшая общая подпоследовательность

Oct 17th, 2020
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. vector<pair<int,int> > getNOP(string& s1, string& s2){
  2.     vector< vector<int> >dp(105,vector<int>(105,0));
  3.     vector< vector<pair<int ,int> > > prev(105,vector<pair<int ,int> >(105));
  4.  
  5.     for(int i=1;i<=s1.size();++i){
  6.         for(int j=1;j<=s2.size();++j){
  7.             if(s1[i-1] == s2[j-1]){
  8.                 dp[i][j] = dp[i-1][j-1]+1;
  9.                 prev[i][j] = {i-1,j-1};
  10.             }else if(dp[i-1][j] > dp[i][j-1]){
  11.                 dp[i][j] = dp[i-1][j];
  12.                 prev[i][j] = {i-1,j};
  13.             }else{
  14.                 dp[i][j] = dp[i][j-1];
  15.                 prev[i][j] = {i,j-1};
  16.             }
  17.         }
  18.     }
  19.  
  20.     int indexI = s1.size();
  21.     int indexJ = s2.size();
  22.     cout<<dp[indexI][indexJ]<<endl;
  23.     vector<pair<int,int> >ans;
  24.  
  25.     while(indexI > 0 || indexJ > 0){
  26.  
  27.         if(prev[indexI][indexJ].first == indexI-1 && prev[indexI][indexJ].second  ==  indexJ-1  )   {
  28.            ans.push_back({indexI,indexJ});
  29.         }
  30.         int newI = prev[indexI][indexJ].first;
  31.         int newJ = prev[indexI][indexJ].second;
  32.         indexI = newI;
  33.         indexJ =newJ;
  34.     }
  35.     return ans;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement