Select
Problem Description
One day, Dudu, the most clever boy, heard of ACM/ICPC, which is a very interesting game. He wants to take part in the game. But as we all know, you can't get good result without teammates.
So, he needs to select two classmates as his teammates.
In this game, the IQ is very important, if you have low IQ you will WanTuo. Dudu's IQ is a given number k. We use an integer v[i] to represent the IQ of the ith classmate.
The sum of new two teammates' IQ must more than Dudu's IQ.
For some reason, Dudu don't want the two teammates comes from the same class.
Now, give you the status of classes, can you tell Dudu how many ways there are.
Input
There is a number T shows there are T test cases below. ( T≤20 )
For each test case , the first line contains two integers, n and k, which means the number of class and the IQ of Dudu. n ( 0≤n≤1000 ), k( 0≤k<231 ).
Then, there are n classes below, for each class, the first line contains an integer m, which means the number of the classmates in this class, and for next m lines, each line contains an integer v[i], which means there is a person whose iq is v[i] in this class. m( 0≤m≤100 ), v[i]( 0≤v[i]<231 )
Output
For each test case, output a single integer.
Sample Input
1 3 1 1 2 1 2 2 1 1
Sample Output
5
题意就是在所有集合里面找出不再同一集合的满足和大于k的两个数的种数。
答案=从所有数中选择的两个加和大于k的数的方案数-在同一个集合中选择的两个加和大于k的数的方案数
而对于同一个集合中选择的两个加和大于k的方案数是可以直接排序然后利用单调性快速统计出来的。
然后我们可以想到,可以二分查找,但是更简单的是,我们拍好序之后,找个指针指向队尾,从第一个元素开始,只要队尾的元素与当前元素加起来大于k那么pos往前移一位,直到不大于k,那么该元素对应的种数就是ans+=m-pos+1,然后第二个元素再找,这是由于第二个元素比第一个大,那么满足第一个的肯定满足第二个,那么pos只需一直往前移就行了。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <cstring>
#define Max(a, b) ((FASTBUFFER = ((a) - (b)) >> 31), ((b) & FASTBUFFER | (a) & ~FASTBUFFER))
#define Min(a, b) ((FASTBUFFER = ((a) - (b)) >> 31), ((a) & FASTBUFFER | (b) & ~FASTBUFFER))
#define Swap(a, b) (a ^= b, b ^= a, a ^= b)
#define OO 2147483647
#define priority_queue PQ
using namespace std;
int n, k, m;
int a[1005][105], temp[200005], now[200005];
void work()
{
scanf("%d %d", &n, &k);
long long ans = 0;
int tot = 0;
for (int i = 1; i <= n; i++)
{
scanf("%d", &m);
for (int j = 1; j <= m; j++)
{
scanf("%d", &a[i][j]);
now[j] = a[i][j];
temp[++tot] = a[i][j];
}
sort(now + 1, now + m + 1);
int pos = m + 1;
for (int j = 1; j <= m; j++)
{
while (pos > 1 && k - now[j] < now[pos - 1])
{
pos--;
}
ans -= (m - pos + 1);
if (k - now[j] < now[j])
{
ans++;
}
}
}
sort(temp + 1, temp + tot + 1);
int pos = tot + 1;
for (int i = 1; i <= tot; i++)
{
while (pos > 1 && k - temp[i] < temp[pos - 1])
{
pos--;
}
ans += (tot - pos + 1);
if (k - temp[i] < temp[i])
{
ans--;
}
}
cout << ans / 2 << endl;
}
int test;
int main()
{
scanf("%d", &test);
while (test--)
{
work();
}
return 0;
}