D - Pair of Topics
Posted vetsama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D - Pair of Topics相关的知识,希望对你有一定的参考价值。
The next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiaiunits for the teacher and by bibi units for the students.
The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.
The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.
The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input5 4 8 2 6 2 4 5 4 1 3Output7Input4 1 3 2 4 1 3 2 4Output0
这个题需要一点思路,ai+aj>bi+bj可以转换成ai-bi+aj-bj>0,也就是c[i]=a[i]-b[i],只需要找c[i]+c[j]大于0
一开始的想法是枚举i和j,但是很显然会超时
a和b数组内部的顺序不会影响正确答案个数,所以可以排序
从两头缩进,如果a[r]加上比较小的a[l]大于0,那么就有l-r种方法,因为比a[l]大的数加上a[r]也会大于0,这样就能保证方法没有遗漏
当a[l]+a[r]不大于0的时候,说明a[l]太小了,l向右移来找一个更大的a[l]
#include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <algorithm> using namespace std; int main() { int t; scanf("%d", &t); int a[200001] = { 0 }; for (int i = 0; i < t; i++) { scanf("%d", &a[i]); } for (int i = 0; i < t; i++) { int k; scanf("%d", &k); a[i] -= k; } sort(a, a + t); int l = 0; int r = t - 1; long long sum = 0; while (l < r && a[r]>0) { if (a[l] + a[r] > 0) { if (l >= r)break; sum += (r - l); r--; } else { l++; } } cout << sum << endl; return 0; }
以上是关于D - Pair of Topics的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces - 1324D - Pair of Topics(尺取)
Codeforces Round #627 (Div. 3) D. Pair of Topics(二分/直接遍历)