文章
454
粉丝
0
获赞
1
访问
10.3k
求两个数组的最长公共连续子数组长度,n,m ≤ 1000。
设 dp[i][j] 为以 a[i]、b[j] 结尾的最长公共连续长度。
a[i]==b[j] 时 dp[i][j]=dp[i-1][j-1]+1,否则为 0。
答案取所有 dp 的最大值。
O(nm)。
C++:
#include <cstdio>
#include <algorithm>
using namespace std;
int a[1005], b[1005];
int dp[1005][1005]; // 以 i、j 结尾的最长公共连续子数组长度
int main() {
int n, m;
if (scanf("%d %d", &n, &m) != 2) return 0;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= m; i++) scanf("%d", &b[i]);
int ans = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (a[i] == b[j]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > ans) ans = dp[i][j];
} else dp[i][j] = 0;
}
printf("%d\n", ans);
return 0;
}
登录后发布评论
暂无评论,来抢沙发