UVA10192 Vacation
题意
给你两个字符串,求满足每个字符都在两个字符串中存在的字符串最长长度。
思路
其实没必要理解我上面写的那串文字,这个问题的实质就是求这两个字符串的最长公共子序列的长度。
对于本题,字符串最长大小只有 \(100\),考虑 \(O(n^2)\) 的 dp 做法。
设 \(dp_{i,j}\) 为 \(a_{1-i}\) 和 \(b_{1-j}\) 的最长公共子序列。
对于所有情况,我们都需考虑 \(dp_{i,j}=\max(dp_{i-1,j},dp_{i,j-1})\)。
且在 \(a_i=b_j\) 时,考虑 \(dp_{i,j}=\max(dp_{i,j},dp_{i-1,j-1}+1)\)。
于是整个代码就出来了,注意 UVa 特有的输入输出方式。
代码
代码中的 \(f\) 数组为上文中的 \(dp\) 数组。
#include<bits/stdc++.h>
using namespace std;
int f[110][110];
char a[110],b[110];
int n,m,cnt;
int max(int x,int y){return x>y?x:y;}
int main(){
while(gets(a+1),gets(b+1)){
if(a[0]=='#') break;
n=strlen(a+1);
m=strlen(b+1);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
f[i][j]=max(f[i-1][j],f[i][j-1]);
if(a[i]==b[j]) f[i][j]=max(f[i][j],f[i-1][j-1]+1);
}
}
cnt++;
printf("Case #%d: you can visit at most %d cities.\n",cnt,f[n][m]);
}
return 0;
}

浙公网安备 33010602011771号