[BZOJ4990][Usaco2017 Feb]Why Did the Cow Cross the Road II dp
4990: [Usaco2017 Feb]Why Did the Cow Cross the Road II
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 93 Solved: 64
[Submit][Status][Discuss]
Description
Farmer John is continuing to ponder the issue of cows crossing the road through his farm, introduced
in the preceding problem. He realizes that interaction between some pairs of breeds is actually acc
eptable if the breeds are friendly, a property that turns out to be easily characterized in terms of
breed ID: breeds aa and bb are friendly if |a-b|≤4, and unfriendly otherwise. It is ok for cows to
wander into fields designated for other breeds, as long as they are friendly.Given the ordering of
N fields on both sides of the road through FJ's farm (again, with exactly one field for each breed o
n each side), please help FJ determine the maximum number of crosswalks he can draw over his road, s
uch that no two intersect, and such that each crosswalk joins a pair of fields containing two breeds
that are friendly. Each field can be accessible via at most one crosswalk (so crosswalks don't meet
at their endpoints).
上下有两个长度为n、位置对应的序列A、B,
其中数的范围均为1~n。若abs(A[i]-B[j]) <= 4,
则A[i]与B[j]间可以连一条边。现要求在边与边不相交的情况下的最大的连边数量。
n <= 10^5。
Input
The first line of input contains N (1≤N≤100,0000).
The next N lines describe the order, by breed ID, of fields on one side of the road;
each breed ID is an integer in the range 1…N
The last N lines describe the order, by breed ID, of the fields on the other side of the road.
Each breed ID appears exactly once in each ordering.
注意:两个序列都是全排列
Output
Please output the maximum number of disjoint "friendly crosswalks" Farmer John can draw across the road.
Sample Input
6
1
2
3
4
5
6
6
5
4
3
2
1
1
2
3
4
5
6
6
5
4
3
2
1
Sample Output
5
HINT
Source
把最长公共子序列转换成最长上升子序列。
对于每一个bi,我们找到他可以配对的ai的位置,从大到小放到数组c里,对c这个新序列跑一次最长上升子序列就是答案了 。
1 #include<iostream> 2 #include<cstring> 3 #include<cstdlib> 4 #include<cstdio> 5 #include<cmath> 6 #include<algorithm> 7 #include<queue> 8 #define LL long long 9 using namespace std; 10 int read() { 11 char ch=getchar();int x=0,f=1; 12 while(!isdigit(ch)){ch=getchar();} 13 while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();} 14 return x; 15 } 16 int n; 17 int a[1000005],b[1000005]; 18 int pos[1000005]; 19 int c[10000005],cnt; 20 int ans=0,d[10000005]; 21 int main() { 22 n=read(); 23 for(int i=1;i<=n;i++) {a[i]=read();pos[a[i]]=i;} 24 for(int i=1;i<=n;i++) b[i]=read(); 25 for(int i=1;i<=n;i++) { 26 int s[10]={},sum=0; 27 for(int j=0;j<=4;j++) { 28 if(j==0){s[++sum]=pos[b[i]];continue;} 29 if(b[i]-j>0) s[++sum]=pos[b[i]-j]; 30 if(b[i]+j<=n) s[++sum]=pos[b[i]+j]; 31 } 32 sort(s+1,s+sum+1); 33 for(int j=sum;j>=1;j--) c[++cnt]=s[j]; 34 } 35 for(int i=1;i<=cnt;i++) { 36 int now=lower_bound(d+1,d+ans+1,c[i])-d; 37 ans=max(ans,now); 38 d[now]=c[i]; 39 } 40 printf("%d",ans); 41 }
O(∩_∩)O~ (*^__^*) 嘻嘻…… O(∩_∩)O哈哈~