Codeforces Round #627 (Div. 3) D. Pair of Topics(思维)(构造cmp)

Pair of Topics:

题目大意:(文末有原题)

分别给出连个数组a[n] 和 b[n],判断a中有几对整数使a[i] + a[j] > b[i] + b[j];

思路:

另外一个数组v[n],v[i]来保存a[i] - b[i],此时,只需判断v中有几个整数对的和大于0;

首先 正数 + 正数 > 0、正数 + 0 > 0,所以 分别记录整数的个数k 和 零的个数m,一定会有

(k * (k - 1)) / 2(即C_{k}^{2} ) + m * k;

其次就是 一个负数 + 绝对值比他大的正数,我们主要要解决的就是这个问题;(直接暴力会TLE)

我们可以将v按照绝对值的大小从大到小进行排序,然后如果v[i] < 0,就再加上他之前 绝对值比他大的正数 的个数;因为我们有可能相同有的负数,会造成重复操作,所以我们拿一个map来记录每个负数的出现次数,并且只让一个该负数进入v;

代码:

#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;

bool cmp(ll x, ll y) {
	if(abs(x) != abs(y) )
		return abs(x) > abs(y);
	else
		return x > y;
}

const ll maxn = 2e5 + 10;
ll a[maxn], z[maxn], v[maxn];

int main() {
	ll n, s = 0, k = 0, l = 0, m = 0, c = 0;
	cin >> n;
	map vis;
	
	for(ll i = 0; i < n; i++) cin >> a[i];
	for(ll i = 0; i < n; i++) {
		ll b; cin >> b;
		
		if(a[i] - b > 0) k++;
		else if(a[i] == b) m++;
		
		if(!vis[a[i] - b] || a[i] - b > 0) 	//如果这个负数首次出现或者是个正数,就进入v 
			v[c++] = a[i] - b;
		vis[a[i] - b]++;	//储存有几个a[i] - b; 
	}
	
	sort(v, v + c, cmp);	
	s = (k * (k - 1)) / 2 + m * k;
	
	for(ll i = 0; i < c && c; i++, l++) {
		if(v[i] < 0) {
			for(int j = 1; 1; j++) {	//计算之前有几个绝对值相等的正数; 
				if(abs(v[i]) != abs(v[i - j])) { 
					s = s - (j - 1) * vis[v[i]];
					break;
				}
			}
			s += l * vis[v[i]];
			l--;	//l用来统计v[i]之前有几个正数,此处l--是减去负数的个数; 
		}
	}
	
	cout << s << endl;
	return 0;
} 

原题:

题目:

The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by ai units for the teacher and by bi units for the students.

The pair of topics i and j (ibi+bj (i.e. it is more interesting for the teacher).

Your task is to find the number of good pairs of topics.

输入:

The first line of the input contains one integer nn (2≤n≤2⋅10^5) — the number of topics.

The second line of the input contains nn integers a1,a2,…,an (1≤ai≤10^9), where ai is the interestingness of the i-th topic for the teacher.

The third line of the input contains n integers b1,b2,…,bn (1≤bi≤10^9), where bi is the interestingness of the i-th topic for the students.

输出:

Print one integer — the number of good pairs of topic.

样例:

Input:

5
4 8 2 6 2
4 5 4 1 3

Output:

7

Input:

4

1 3 2 4

1 3 2 4

Output:

0

你可能感兴趣的:(思维)