Hangdian 1080-Lcs+DP (**Use for reference**)

http://acm.hdu.edu.cn/showproblem.php?pid=1080

The first meaning:

The meaning of the title is: you must follow the value of each pair of letters in a table given. How can we find the longest substring of the two strings and get the maximum value at the same time.

The specific idea: First, get the longest substring according to the formula of LCS. Then calculate the maximum value according to the idea of ​​DP. When the ball is the maximum value, you can add "-"; to ensure the maximum value! (At the beginning of LCS) I don't understand, it's a bit difficult.

See the code for specific details: (some reference);

#include<iostream>
#include<cstdio>
#include<map>//map头文件
#include<string>//这里必须注意下,因为要利用到(map<string,int>m),所以不可以写出(#include<cstring>),否则就会出错。
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=110;
int dp[maxn][maxn];
char str1[maxn],str2[maxn];
map<string,int>m;//这是值得转化,将对应的字符转化为对应的值。
int main()
{
    int i,j;
    m["AA"]=5;
    m["CC"]=5;
    m["GG"]=5;
    m["TT"]=5;
    m["AC"]=m["CA"]=-1;
    m["AG"]=m["GA"]=-2;
    m["AT"]=m["TA"]=-1;
    m["A-"]=m["-A"]=-3;
    m["CG"]=m["GC"]=-3;
    m["CT"]=m["TC"]=-2;
    m["C-"]=m["-C"]=-4;
    m["GT"]=m["TG"]=-2;
    m["G-"]=m["-G"]=-2;
    m["T-"]=m["-T"]=-1;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int len1,len2;
       // memset(str1,0,sizeof(str1));
       // memset(str2,0,sizeof(str2));
        //getchar();
        scanf("\n%d%s \n%d%s",&len1,str1+1,&len2,str2+1);//输入时也要注意,应为数组一般默认是i的值都为0;如果输入时用直接为(str1,str2)的话就会在第二个字符会找不到。
        //memset(dp,0,sizeof(dp));
        for(i=0;i<=len1;i++)//对应的以下两个for必须注意下i的初值,
        {
           // cout<<str1[i]<<endl;
            if(i==0)dp[0][0]=0;
            else
            {
                string s("-");//将s赋值为(“-”);
                s+=str1[i];
                dp[i][0]=dp[i-1][0]+m[s];
            }
        }
        for(i=1;i<=len2;i++)
        {
            //cout<<str2[i]<<endl;
            string s("-");
            s+=str2[i];
            dp[0][i]=dp[0][i-1]+m[s];
        }
        for(i=1;i<=len1;i++)
        {
            for(j=1;j<=len2;j++)
            {
                string s1="-",s2="-",s3="";//给s1,s2,s3赋值,是否该加“-”还是不加“”;
                s1+=str1[i];
                s2+=str2[j];
                s3=s3+str1[i]+str2[j];//不加是对应的值。
                dp[i][j]=dp[i][j-1]+m[s2];//只是str2所对应的。
                dp[i][j]=max(dp[i-1][j]+m[s1],dp[i][j]);//进行DP状态分析。
                dp[i][j]=max(dp[i-1][j-1]+m[s3],dp[i][j]);//同理。
            }
        }
        printf("%d\n",dp[len1][len2]);
    }
    return 0;
}


Guess you like

Origin blog.csdn.net/u010200793/article/details/14005353