第一题:最长回文子序列
题目思想大概是这样:cabbeaf:回文子序列有:c,a,aa,bb,,aba,abba,e,f,最长的就是abba,所以输出长度为4
#include <iostream>
#include <algorithm>
#include <string>
int dp[1000][1000];
using namespace std;
int main(){//思路就是求这个原字符串和它反转字符串的最长公共子序列
string str;
cin>>str;
string a=str;
reverse(a.begin(),a.end());
int len=str.length();
for(int i=1;i<=len;i++){
for(int j=1;j<=len;j++){
if(str[i-1]==a[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
}
else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
cout<<dp[len][len];
return 0;
}
第二题 蛇形矩阵:
题目大意是这样:
输入2
矩阵为
1 2
4 3
输出:1 2 4 3//按行打印
输入3
矩阵为
1 2 3
8 9 4
7 6 5
输出:1 2 3 8 9 4 7 6 5 //按行打印
#include<iostream>
#include<vector>
using namespace std;
void Fun(const int n)
{
vector<int > elem;
elem.resize(n);
vector<vector<int > >array(n,elem);
int topLeft[2]={0,0};
int topRigth[2] = {0,n-1};
int bottomRight[2]={n-1,n-1};
int bottomLeft[2]={n-1,0};
int row=0,col =0;
int counter = 0;
int i=0,j=0;
while(true)
{
row = topLeft[0];
col = topLeft[1];
while(col<=topRigth[1])
{
array[row][col++] = ++counter;
}
topRigth[0]+=1;
topRigth[1]-=1;
row=topRigth[0];
col = topRigth[1]+1;
while(row<=bottomRight[0])
{
array[row++][col] = ++counter;
}
bottomRight[0] -=1;
bottomRight[1]-=1;
row = bottomRight[0]+1;
col=bottomRight[1];
while(col>=bottomLeft[1])
{
array[row][col--]-=++counter;
}
bottomLeft[0]-=1;
bottomLeft[1]+=1;
row = bottomLeft[0];
col = bottomLeft[1]-1;
while(row>topLeft[0])
{
array[row--][col]=++counter;
}
topLeft[0]+=1;
topLeft[1]+=1;
if(topLeft[1]>=topRigth[1])
{
if(0!=n%2)
{
array[n/2][n/2]=++counter;
}
break;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(array[i][j]<0)
{
array[i][j]*=-1;
}
cout<<array[i][j]<<" ";
}
}
cout<<endl;
}
int main()
{
int n = 0;
cin>>n;
Fun(n);
return 0;
}