[Usaco2017 Feb]Why Did the Cow Cross the Road II (Gold)

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


网上有题解说求最长公共上升序列,一脸懵逼,反正我只会DP。设f[i][j]表示A序列选到第i个,B序列选到第j个的最大连线数,转移就十分明显了

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline int read(){
	int x=0,f=1;char ch=getchar();
	for (;ch<'0'||ch>'9';ch=getchar())	if (ch=='-')    f=-1;
	for (;ch>='0'&&ch<='9';ch=getchar())	x=(x<<1)+(x<<3)+ch-'0';
	return x*f;
}
inline void print(int x){
	if (x>=10)     print(x/10);
	putchar(x%10+'0');
}
const int N=1e3;
int f[N+10][N+10],A[N+10],B[N+10];
int main(){
	int n=read();
	for (int i=1;i<=n;i++)	A[i]=read();
	for (int i=1;i<=n;i++)	B[i]=read();
	for (int i=1;i<=n;i++)
		for (int j=1;j<=n;j++){
			f[i][j]=max(f[i-1][j],f[i][j-1]);    //要么不选
			if (abs(A[i]-B[j])<=4)	f[i][j]=max(f[i][j],f[i-1][j-1]+1);    //可以的话就选
		}
	printf("%d\n",f[n][n]);
	return 0;
}
posted @ 2018-02-04 21:35  Wolfycz  阅读(146)  评论(0编辑  收藏  举报