计算机机试指南之动态规划

4.Coincidence问题描述:find a longest common subsequence of two strings.(找到两个字符串的最长公共子序列)输入:first and second line of each input case contain two strings of lowercase character a...z. there are no space
摘要由CSDN通过智能技术生成

4.Coincidence

问题描述:find a longest common subsequence of two strings.(找到两个字符串的最长公共子序列)

输入:first and second line of each input case contain two strings of lowercase character a...z. there are no spaces before, inside or after the strings. length of the strings do not exceed 100.(第一行第二行分别输入两个包含a...z的字符串,不包含空格,字符串长度不超过100)

输出:for each case, output k--the length of a longest common subsequence in one line(每一种情况,输出最长公共子序列 的长度)

//最长公共子序列长度
#include<stdio.h>
#include<string.h>
int buf[101][101];
int max(int a, int b){return a>b?a:b;}
char first[101],second[101];
int main(){
	while(scanf("%s%s",first,second)!=EOF){
		int l1=strlen(first);
		int l2=strlen(second);
		for(int i=0;i<l1;i++)buf[i][0]=0;
		for(int j=0;j<l2;j++)buf[0][j]=0;
		for(int i=1;i<l1;i++){
			for(int j=1;j<l2;j++){
				if(first[i]==second[j])buf[i][j]=buf[i-1][j-1]+1;
				else buf[i][j]=max(buf[i-1][j],buf[i][j-1]);
			}
		}
		printf("最长公共字符串长度为:%d\n",buf[l1-1][l2-1]);
	}
	return 0;
} 

背包问题——0-1背包、完全背包、多重背包
5.采药问题(0-1背包问题:每种草药有两种状态,在背包中;不在背包中)

问题描述:在固定的时间里采一些草药,使得草药的价值最大

输入:输入的第一行有两个整数T(1<=T<=1000)和M(1<=M<=100),T代表总共能够用来采药的时间,M代表山洞里草药的数目。接下来的M行每行包括两个在1到100之间的整数,分别表示采摘某株草药的时间和这株草药的价值。

输出:可能有多组测试数据,对于每组数据,输出只包括一行,这一行只包含一个整数,表示在规定的时间内,可以采到的草药的最大总价值。

//0-1背包问题
#include<stdio.h>
int buf[101][1001];//总时间不超过j的情况下前i个草药所能达到的最大价值
/*
若第一棵草药所需时间超过总时间则不采,若某一棵草药时间
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值