Codeforces Global Round 17 C. Keshi Is Throwing a Party 题解 二分答案

Keshi Is Throwing a Party

题目描述

Keshi is throwing a party and he wants everybody in the party to be happy.

He has nnn friends. His iii-th friend has iii dollars.

If you invite the iii-th friend to the party, he will be happy only if at most aia_iai people in the party are strictly richer than him and at most bib_ibi people are strictly poorer than him.

Keshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.

输入描述

The first line contains a single integer ttt (1≤t≤104)(1\le t\le 10^4)(1t104) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer nnn (1≤n≤2⋅105)(1\le n\le 2 \cdot 10^5)(1n2105) — the number of Keshi’s friends.

The iii-th of the following nnn lines contains two integers aia_iai and bib_ibi (0≤ai,bi<n)(0 \le a_i, b_i < n)(0ai,bi<n).

It is guaranteed that the sum of nnn over all test cases doesn’t exceed 2⋅1052 \cdot 10^52105.

输出描述

For each test case print the maximum number of people Keshi can invite.

样例输入 #1

3
3
1 2
2 1
1 1
2
0 0
0 1
2
1 0
0 1

样例输出 #1

2
1
2

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++)
        cin >> a[i] >> b[i];
    auto check = [&](int x) -> bool
    {
        int cnt = 0;
        for (int i = 0; i < n; i++)
        {
            if (cnt <= b[i] && x - cnt - 1 <= a[i]) // 贪心策略,每找到一个满足条件的朋友,邀请他
                cnt++;
            if (cnt >= x) // 邀请人数已足够,返回1
                return 1;
        }
        return 0;
    };
    // 二分答案,确定上下界为1和n
    int l = 1, r = n;
    while (l < r)
    {
        int mid = (l + r + 1) / 2;
        if (check(mid))
            l = mid;
        else
            r = mid - 1;
    }
    cout << l << '\n';
    return;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;
    while (t--)
        solve();

    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值