template<class T>
class LCIS
{
private:
static const short maxLength = 501; //序列的最大長度
unsigned short length1,length2; //分別表示seq1,seq2的長度
T seq1[maxLength],seq2[maxLength]; //源序列
unsigned short dp[maxLength][maxLength]; //dp[i][j]表示子串seq1[1,2,...i]和以seq2[j]結尾的子串seq2[1,2,...j]的LCIS
unsigned short lastindex; //LCIS的seq2的結尾下標,即若最後的LCIS串爲seq = {s1,s2,...st},那麼seq[st] = seq2[lastindex]
short path[maxLength][maxLength]; //路徑記錄,path[i][j] = y表示(i - 1,y) -> (i,y)
void copyArray(T num1[],int& l1,T num2[],int l2);
public:
LCIS(){};
LCIS(T num1[],int l1,T num2[],int l2);
void init(T num1[],int l1,T num2[],int l2);
int getLCIS(); //計算LCIS,path並返回LCSI的值
int getLastindex(); //返回組成LCIS串的seq2串的結尾下標
void printPath(int x,int y); //打印路徑,注意,入口處的參數y必須是LCIS的相應結尾lastindex
};
template<class T>
void LCIS<T>::copyArray(T num1[],int& l1,T num2[],int l2)
{
l1 = l2;
for(int i = 1;i <= l1;i++)
num1[i] = num2[i];
}
template<class T>
LCIS<T>::LCIS(T num1[],int l1,T num2[],int l2)
{
init(num1,l1,num2,l2);
}
template<class T>
void LCIS<T>::init(T num1[],int l1,T num2[],int l2)
{
copyArray(seq1,length1,num1,l1);
copyArray(seq2,length2,num2,l2);
memset(dp,0,sizeof(dp));
memset(path,0,sizeof(path));
}
template<class T>
int LCIS<T>::getLCIS()
{
for(int i = 1;i <= length1;i++)
{
int maxj = 0;
for(int j = 1;j <= length2;j++)
{
if(seq1[i] > seq2[j] && dp[i - 1][maxj] < dp[i - 1][j])
maxj = j;
if(seq1[i] != seq2[j])
{
dp[i][j] = dp[i - 1][j];
path[i][j] = j;
}
else if(seq1[i] == seq2[j])
{
dp[i][j] = dp[i - 1][maxj] + 1;
path[i][j] = maxj;
}
}
}
lastindex = 1;
for(int i = 1;i <= length2;i++)
if(dp[length1][lastindex] < dp[length1][i])
lastindex = i;
return dp[length1][lastindex];
}
template<class T>
int LCIS<T>::getLastindex()
{
return lastindex;
}
template<class T>
void LCIS<T>::printPath(int x,int y)
{
if(x < 1 || y < 1)
return;
while(x >= 1 && path[x][y] == y)
x--;
if(x >= 1)
{
printPath(x,path[x][y]);
if(!path[x][y])
printf("%d",seq2[y]);
else
printf(" %d",seq2[y]);
}
}
LCIS類模板
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.