笔试练习四

第一题:最长回文子序列
题目思想大概是这样: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值