列表

详情


NC24070. [USACO 2017 Feb P]Why Did the Cow Cross the Road II

描述

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 acceptable 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 | ab4, 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 on each side), please help FJ determine the maximum number of crosswalks he can draw over his road, such 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).

输入描述

The first line of input contains N (1≤N≤100,000). 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.

输出描述

Please output the maximum number of disjoint "friendly crosswalks" Farmer John can draw across the road.

示例1

输入:

6
1
2
3
4
5
6
6
5
4
3
2
1

输出:

5

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(clang++11) 解法, 执行用时: 53ms, 内存消耗: 1912K, 提交时间: 2021-01-19 19:19:03

#include<bits/stdc++.h>
#define lowbit(x) x&-x
using namespace std;
const int N=1e5+11;
int f[N],n,m,a[N],t[N],b[N];
int ask(int x){int res=0;for(;x;x-=lowbit(x))res=max(res,t[x]);return res;}
void add(int x,int k){for(;x<=n;x+=lowbit(x))t[x]=max(t[x],k);return;}
int main(){
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;++i)cin>>a[i];
	for(int i=1;i<=n;++i){int x;cin>>x;b[x]=i;}
	for(int i=1;i<=n;++i){
		int lef=max(1,a[i]-4),rig=min(n,a[i]+4);
		for(int j=lef;j<=rig;++j)f[j]=ask(b[j]-1);
		for(int j=lef;j<=rig;++j)add(b[j],f[j]+1);
	}
	cout<<ask(n);
	return 0;
} 

上一题