BZOJ4991: [Usaco2017 Feb]Why Did the Cow Cross the Road III

Time Limit: 10 Sec  Memory Limit: 128 MB

Description

Farmer John is continuing to ponder the issue of cows crossing the road through his farm, introduced
 in the preceding two problems. He realizes now that the threshold for friendliness is a bit more su
btle than he previously considered — breeds aa and bb are now friendly if |a-b|≤K, and unfriendly
otherwise.Given the orderings of fields on either side of the road through FJ’s farm, please count t
he number of unfriendly crossing pairs of breeds, where a crossing pair of breeds is defined as in t
he preceding problems.

Input

The first line of input contains N (1≤N≤100,000) and K (0≤K<N).
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 number of unfriendly crossing pairs of breeds.

Sample Input

4 1
4
3
2
1
1
4
2
3

Sample Output

2
In this example, breeds 1 and 4 are unfriendly and crossing, as are breeds 1 and 3.

HINT

Source

Platinum

Solution

CDQ分治

设ci为奶牛ID,ai为路的一旁的奶牛ID为ci的位子,bi为路的另一旁的奶牛ID为ci的位子。

即找i,j满足以下条件的对数:

ai>aj bi<bj abs(ci-cj)>k

下面是用归并排序的代码:

下面是左右两个区间分别排序的代码:

 

点赞

发表评论

您的电子邮箱地址不会被公开。