HDU Problem - 5101 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 < 2 31 ).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 ), vi

Output

For each test case, output a single integer.

Sample Input

1
3 1
1 2
1 2
2 1 1

Sample Output

5

AC

  • 刚开始写的时候是开了3个for TLE
  • 先将所有IQ存在一起,然后二分找每个数字可能的情况,然后在同一个班级里找可能的情况,消除不符合条件的
  • 手写二分超时。。。
#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
#include <algorithm>
#define N 100005
#define ll long long
using namespace std;
int a[1004][104];
int b[1000005];
int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    int t;
    scanf("%d", &t);
    while (t--) {
        int n, k;
        scanf("%d%d", &n, &k);
        int now = 0;
        for (int i = 0; i < n; ++i) {
            scanf("%d", &a[i][0]);
            for (int j = 1; j <= a[i][0]; ++j) {
                scanf("%d", &a[i][j]);
                b[now++] = a[i][j];
            }
            sort(a[i] + 1, a[i] + 1 + a[i][0]);
        }
        sort(b, b + now);
        ll ans = 0;
        // 统计所有人的可能情况 
        for (int i = 0; i < now - 1; ++i) {
            ans += now - (upper_bound(b + i + 1, b + now, k - b[i]) - b);
        } 
        // 减去每个班级重复的 
        for (int i = 0; i < n; ++i) {
            for (int j = 1; j < a[i][0]; ++j) {
                ans -= a[i][0] - (upper_bound(a[i] + 1 + j, a[i] + a[i][0] + 1, k - a[i][j]) - a[i]) + 1;
            }
        }
        printf("%lld\n", ans);
    }

    return 0;
} 

猜你喜欢

转载自blog.csdn.net/henuyh/article/details/81744830