1.最长公共子序列
chara[
1005];
charb[
1005];
intans[
1005][
1005];
int mmp(){
int
lena=
strlen(a);
for
(
inti=
0;i<=lena;i++)
ans[i][
1]=
0;
int
lenb=
strlen(b);
for
(
inti=
0;i<=lenb;i++)
ans[
1][i]=
0;
for
(
inti=
1;i<=lena;i++){
for
(
intj=
1;j<=lenb;j++){
if
(a[i
-1]==b[j
-1])
ans[i][j]=ans[i
-1][j
-1]+
1;
else
ans[i][j]=max(ans[i
-1][j],ans[i][j
-1]);
}
}
return
ans[lena][lenb];
}
2.最长公共子序列(最长上升子序列写法)
void jie(){
int
n,p,q,dp,right,left,mid;
scanf
(
"%d%d%d",&n,&p,&q);
p++;
q++;
int
m;
int
top;
memset
(a,
0,
sizeof(a));
for
(
inti=
1;i<=p;i++){
scanf
(
"%d",&m);
a[m]=i;
}
ans[
0]=top=
0;
for
(
inti=
1;i<=q;i++){
scanf
(
"%d",&m);
dp=a[m];
if
(!dp)
continue;
if
(dp>ans[top]){
ans[++top]=dp;
}
else
{
left=
0;
right=top;
mid;
while
(
1){
mid=(right+left)/
2;
if
(mid==left)
break;
if
(dp>ans[mid])
left=mid;
else
right=mid;
}
ans[mid+
1]=dp;
}
}
printf
(
"%d\n",top);
}
3.最长上升子序列
#include<stdio.h>
#include<string.h>
#include<algorithm>
usingnamespace
std
;
inta[
100000];
intchang[
100000];
int main(){
int
n;
scanf
(
"%d",&n);
int
sum=
1;
int
cnt=
0;
int
flag;
for
(
inti=
0;i<n;i++){
scanf
(
"%d",&a[i]);
chang[i]=
1;
}
for
(
inti=
1;i<n;i++){
for
(
intj=
0;j<i;j++){
if
(a[i]>a[j]){
chang[i]=max(chang[i],chang[j]+
1);
}
if
(chang[i]>sum)sum=chang[i];
}
}
printf
(
"%d\n",sum);
return
0
;
}
4.最长上升子序列(二分)
#include<stdio.h>
inta[
100000];
intans[
100000];
int main(){
int n;
scanf(
"%d",&n);
for(
inti=
1;i<=n;i++)
{
scanf
(
"%d",&a[i]);
}
inttop=
1;
ans[
1]=a[
1];
for(
inti=
2;i<=n;i++){
if
(ans[top]<a[i])
ans[++top]=a[i];
else
{
int
mid;
int
left=
1;
int
right=top;
while
(left<=right){
mid=(left+right)/
2;
if
(a[i]>ans[mid])
left=mid+
1;
else
right=mid
-1;
}
ans[left]=a[i];
}
}
printf(
"%d\n",top);
return0
;
}
时间: 2024-11-05 12:25:53