4993: [Usaco2017 Feb]Why Did the Cow Cross the Road II
Time Limit: 10 Sec Memory Limit: 256 MB
Description
上下有两个长度为n、位置对应的序列A、B,
其中数的范围均为1~n。若abs(A[i]-B[j])<= 4,则A[i]与B[j]间可以连一条边。
现要求在边与边不相交的情况下的最大的连边数量。
n <= 10^3
Sample Input
6
1
2
3
4
5
6
6
5
4
3
2
1
Sample Output
5
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int n;
int a[1010], b[1010], f[1010][1010];//f[i][j]表示第一行到i,第二行到j的最大匹配
int main(){
scanf("%d", &n);
for(int i=1; i<=n; i++) scanf("%d", &a[i]);
for(int i=1; i<=n; i++) scanf("%d", &b[i]);
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++)
if(abs(a[i] - b[j]) <= 4) f[i][j] = max(f[i][j], f[i-1][j-1] + 1);
for(int j=2; j<=n; j++) f[i][j] = max(f[i][j], max(f[i][j-1], f[i-1][j]));
}
printf("%d", f[n][n]);
return 0;
}