暑假集训.4 (LIS LCS)

LIS  最长上升子序列

例如 ;1 2 6 5 7 9 8 9 求该串的 最长上升子序列

结果应该为  1 2 5 7 8 9 ;

例题:G - Bridging signals

'Oh no, they've done it again', cries the chief designer at the Waferland chip factory. Once more the routing designers have screwed up completely, making the signals on the chip connecting the ports of two functional blocks cross each other all over the place. At this late stage of the process, it is too 
expensive to redo the routing. Instead, the engineers have to bridge the signals, using the third dimension, so that no two signals cross. However, bridging is a complicated operation, and thus it is desirable to bridge as few signals as possible. The call for a computer program that finds the maximum number of signals which may be connected on the silicon surface without rossing each other, is imminent. Bearing in mind that there may be housands of signal ports at the boundary of a functional block, the problem asks quite a lot of the programmer. Are you up to the task? 

Figure 1. To the left: The two blocks' ports and their signal mapping (4,2,6,3,1,5). To the right: At most three signals may be routed on the silicon surface without crossing each other. The dashed signals must be bridged. 

A typical situation is schematically depicted in figure 1. The ports of the two functional blocks are numbered from 1 to p, from top to bottom. The signal mapping is described by a permutation of the numbers 1 to p in the form of a list of p unique numbers in the range 1 to p, in which the i:th number pecifies which port on the right side should be connected to the i:th port on the left side. 
Two signals cross if and only if the straight lines connecting the two ports of each pair do.

Input

On the first line of the input, there is a single positive integer n, telling the number of test scenarios to follow. Each test scenario begins with a line containing a single positive integer p<40000, the number of ports on the two functional blocks. Then follow p lines, describing the signal mapping: On the i:th line is the port number of the block on the right side which should be connected to the i:th port of the block on the left side.

Output

For each test scenario, output one line containing the maximum number of signals which may be routed on the silicon surface without crossing each other.

Sample Input

4
6  4 2 6 3 1 5
10 2 3 4 5 6 7 8 9 10 1
8  8 7 6 5 4 3 2 1
9  5 8 9 2 3 1 7 4 6

Sample Output

3
9
1
4

代码如下:

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include <algorithm>
using namespace std;
int arr[50500],ans[50500],len;
//int binary_search(int i)//手写二分法
//{
//    int left,right,mid;
//    left=0,right=len;
//    while(left<right)
//    {
//        mid = left+(right-left)/2;
//        if(ans[mid]>=arr[i]) right=mid;
//        else left=mid+1;
//    }
//    return left;
//}
int main()
{
    int n,T;
    scanf("%d",&T);
    while(T--)
    {
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d",&arr[i]);
    ans[0] = arr[1];
    len=0;
    for(int i=2; i<=n; i++)
    {
        if(arr[i]>ans[len])
            ans[++len]=arr[i];
        else
        {
//            int pos=binary_search(i);//二进制
            int pos=lower_bound(ans,ans+len,arr[i])-ans;//也可直接使用STL库里的函数
            ans[pos] = min(ans[pos],arr[i]);
        }
    }

    printf("%d\n",len+1);//数组大小就是最长上升子序列的个数

}
return 0;
}

LCS  最长公共子序列

            在解决最长公共子序列(LCS)问题,即求字符串A,B的公共子序列LCS(注意:LCS不一定连续,但和原始序列的元素顺序有关)中长度最长的公共子序列时,因为最长公共子序列不唯一,但是最长公共子序列长度是一定的,所以先把问题简化,如何求两个序列的最长公共子序列长度?                                    

    我们首先想到的肯定是暴力枚举法。       先来看看:假设序列A有n 个元素,序列B有 m 个元素,那么A,B分别有2^n,2^m个子序列,如果任意两个子序列一一比较,比较的的子序列高达2^(m+n)对,这还没有算具体的复杂度。

    所以我们可以试试动态规划,把这个问题分解成子问题:求A的前i个元素和B的前j个元素之间的最长公共子序列长度。这时的空间复杂度为o(m+n)。

 

算法思想 

1、定义dp [i][j]:表示字符串序列A的前i个字符组成的序列Ax和字符串序列B的前j个字符组成的序列By之间的最长                   公共子序列L(i,j )的长度(m ,n分别为Ax和By的长度,i<=m,j<=n)

2、如果Ax [i] =By [j],那么Ax与By之间的最长公共子序列L( i,j )的最后一项一定是这个元素,

   所以dp [i][j] = dp[i-1][j-1] + 1。

3、如果Ax[i] != By[j],设LCS(i-1,j-1)是L( i -1, j-1 )的最后一个元素,或者L(i-1,j-1)是空序列,

   则 t!= Ax[i]和t!=By[j]至少有一个不成立。

   (1)    当 LCS(i-1,j-1) != Ax[i] 时,dp[i][j]= dp[i-1][j];

   (2)    当 LCS(i-1,j-1) != By[j] 时,ap[i][j]= dp[i][j-1];

   所以dp[i][j]= max ( dp[i-1][j],dp[i][j-1] )。                         

4、初始值为:dp[0][j] = dp[i][0] = 0.

5、题意要求求出任意一个最长公共子序列,这点要如何实现呢?

   仍然考虑上面的递推式,L(i,j)的最后一个元素LCS( i,j )的来源有三种情况,定义数组flag[MAXN][MAXN]用    以标记来的方向:

  (1) dp[i][j] = dp[i-1][j-1] + 1,对应字符LCS( i-1,j-1)接上LCS( i,j),flag[i][j] = 1,表示从斜向上      左方来;

  (2) dp[i][j] = dp[i-1][j],对应字符LCS(i-1,j)接上LCS(i,j),flag[i][j] = 2,表示从上方过来;

  (3) dp[i][j] = dp[i][j-1],对应字符LCS(I,j-1)接上LCS(i,j),flag[i][j] = 3,表示从左方过来。

   

   我们只要在计算dp[i][j]时根据来源进行不同的标记,回溯就可以找到一个最长公共子序列。

 

   

递归写法

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include <algorithm>
using namespace std;
int dp[1005][1005];
char s1[1005],s2[1005];
void F(int i,int j)
{
    if(!i||!j)
        return ;
    if(s1[i-1]==s2[j-1])
    {
        F(i-1,j-1);
        printf("%c",s1[i-1]);
    }
    else if(dp[i-1][j]>dp[i][j-1])
        F(i-1,j);
    else
        F(i,j-1);
}
int main()
{

    while(scanf(" %s",s1)!=EOF)
    {
        scanf(" %s",s2);
        int len1=0,len2=0;
        memset(dp,0,sizeof(dp));
        len1=strlen(s1);
        len2=strlen(s2);
        for(int i=1;i<=len1;i++)
        {
            for(int j=1;j<=len2;j++)
            {
                if(s1[i-1]==s2[j-1])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                {
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        F(len1,len2);
//        printf("%d\n;",dp[len1][len2]);
    }
}

动态规划写法

​
<span style="font-size:14px;">#include<stdio.h>
#include<string.h>
char a[1010],b[1010];
int dp[1010][1010];  //记录最大公共子序列的长度 
int flag[1000][1000];//记录来的方向 
int main()
{
	while(gets(a))
	{
		gets(b);
		memset(dp,0,sizeof(dp));
		memset(flag,0,sizeof(flag));
		int m = strlen(a);
		int n = strlen(b);
		int i,j;
		for(i = 1;i <= m;i++)
		  for(j = 1;j <= n;j++)
		  {
		  	if(a[i-1] == b[j-1]){
		  		
		  		dp[i][j] = dp[i-1][j-1] + 1;
		  		flag[i][j] = 1; //上一步(i-1,j-1),斜向左上 
			}
		  	else if(dp[i-1][j] > dp[i][j-1]){
		  		
		  		dp[i][j] = dp[i-1][j];
		  		flag[i][j] = 2; //上一步(i-1,j),上方 
			  }
			else {
				
		  		dp[i][j] = dp[i][j-1];
		  		flag[i][j] = 3;//上一步(i,j-1),左方 
			  }
		  }
		//如何构造最长公共子序列?
		int  k = 0;
		char c[1010];
		while(m > 0 && n > 0)//从终点按标记的方向反方向往回走 
		{
			if(flag[m][n] == 1){ //这个方向来的元素包含在最长公共子序列中
				c[k++] = a[m - 1];
				m--; n--;
			}
			else if(flag[m][n] == 2)
				m--;
			else if(flag[m][n] == 3)
				n--;
		}
		for(i = k-1;i >= 0;i--)
		    printf("%c",c[i]);
		printf("\n");
	}
	return 0;
}</span>

​

例题小变形;

E - Advanced Fruits

The company "21st Century Fruits" has specialized in creating new sorts of fruits by transferring genes from one fruit into the genome of another one. Most times this method doesn't work, but sometimes, in very rare cases, a new fruit emerges that tastes like a mixture between both of them. 
A big topic of discussion inside the company is "How should the new creations be called?" A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn't sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, "applear" contains "apple" and "pear" (APPLEar and apPlEAR), and there is no shorter string that has the same property. 

A combination of a cranberry and a boysenberry would therefore be called a "boysecranberry" or a "craboysenberry", for example. 

Your job is to write a program that computes such a shortest name for a combination of two given fruits. Your algorithm should be efficient, otherwise it is unlikely that it will execute in the alloted time for long fruit names. 

Input

Each line of the input contains two strings that represent the names of the fruits that should be combined. All names have a maximum length of 100 and only consist of alphabetic characters. 

Input is terminated by end of file. 

Output

For each test case, output the shortest name of the resulting fruit on one line. If more than one shortest name is possible, any one is acceptable. 

Sample Input

apple peach
ananas banana
pear peach

Sample Output

appleach
bananas
pearch

代码如下:

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include <algorithm>
using namespace std;
int dp[1005][1005];
char s1[1005],s2[1005];
void F(int i,int j)
{
    if(dp[i][j]==0)
    {
        for(int k=0;k<i;k++)
            printf("%c",s1[k]);
       for(int k=0;k<j;k++)
            printf("%c",s2[k]);
        return ;
    }

    if(s1[i-1]==s2[j-1])
    {
        F(i-1,j-1);
        printf("%c",s1[i-1]);
    }
    else if(dp[i-1][j]>dp[i][j-1])
    {
        F(i-1,j);
        printf("%c",s1[i-1]);
    }

    else
    {
        F(i,j-1);
        printf("%c",s2[j-1]);
    }

}
int main()
{
while(~scanf(" %s",s1))
{
        scanf(" %s",s2);
        int len1=0,len2=0;
        memset(dp,0,sizeof(dp));
        len1=strlen(s1);
        len2=strlen(s2);
        for(int i=1;i<=len1;i++)
        {
            for(int j=1;j<=len2;j++)
            {
                if(s1[i-1]==s2[j-1])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                {
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        F(len1,len2);
        printf("\n");
}
//        printf("%d\n;",dp[len1][len2]);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值