Bamboo and the Ancient spell analysis
may be more difficult to read English, but only see the full capital of "the longest COMMON subsequence!" It should be clear that this is a test or something.
Longest common subsequence: can be discontinuous. When the sequence length is very large, the violent method is very time-consuming, which is a more classical dynamic programming problem in the introduction of algorithms.
to set a longest common subsequence z= of sequence x= and y= , then:
If Xm=yn, then Zk=xm=yn and Zk-1 are the longest common subsequence of Xm-1 and Yn-1;
If Xm≠yn and ZK≠XM, then Z is the longest common subsequence of Xm-1 and y;
If Xm≠yn and Zk≠yn, Z is the longest common sub-sequence of x and Yn-1.
Core :
C[I,J] = c[i,j]=0 (if i=0 or j=0)
C[I,J] = c[i-1,j-1]+1 (i,j>0 and Xi=yj)
C[I,J] = max (C[i,j-1],c[i-1,j]) (I,j>0 and Xi!=yj)
Special : #?
How to deal with #: delete; replace; conditional judgment
? : Plus equals when comparing equal? The conditions
Where to delete: A string with a erase function, or a for loop. Be aware of the change in string length
The code is as follows:
#include <cstdio>#include <iostream>#include <string>#include <cstring>using namespaceStd;string s1,s2;intc[ Max][ Max];intMain () { while(CIN>>S1>>S2) {intLen1 = S1.length ();intLen2 = S2.length (); Memset (c,0,sizeof(c)); for(inti =1; i<=len1;i++) for(intj =1; j<=len2;j++) {if(S1[i-1]!='#'&&s2[j-1]!='#'&& (s1[i-1]==s2[j-1]|| S1[i-1]=='?'|| S2[j-1]=='?')) C[i][j]=c[i-1][j-1]+1;ElseC[i][j]=max (c[i-1][j],c[i][j-1]); } printf ("%d\n", C[len1][len2]); }}
Attach a simple char array to delete # code:
void Prepro () {int i,j; for (i = 1 ; S1[i]!= " \0 ; i++) if (S1[i]== ' # ' ) {for (j=i; S1[j]!= " \0 ' ; j + +) s1[j]=s1[j< Span class= "DV" >+1 ]; i--; } for (i = 1 ; S2[i]!= \0 "; i++) if (S2[i]== ' # ' ) {for (j=i; S2[j]!= " \0 ' ; j + +) s2[j]=s2[j< Span class= "DV" >+1 ]; i--; }}
2016-level algorithm fourth time Machine-e.bamboo and the Ancient Spell