本文主要是介绍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 n n n friends. His i i i-th friend has i i i dollars.
If you invite the i i i-th friend to the party, he will be happy only if at most a i a_i ai people in the party are strictly richer than him and at most b i b_i bi 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 t t t ( 1 ≤ t ≤ 1 0 4 ) (1\le t\le 10^4) (1≤t≤104) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n n n ( 1 ≤ n ≤ 2 ⋅ 1 0 5 ) (1\le n\le 2 \cdot 10^5) (1≤n≤2⋅105) — the number of Keshi’s friends.
The i i i-th of the following n n n lines contains two integers a i a_i ai and b i b_i bi ( 0 ≤ a i , b i < n ) (0 \le a_i, b_i < n) (0≤ai,bi<n).
It is guaranteed that the sum of n n n over all test cases doesn’t exceed 2 ⋅ 1 0 5 2 \cdot 10^5 2⋅105.
输出描述
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) // 邀请人数已足够,返回1return 1;}return 0;};// 二分答案,确定上下界为1和nint l = 1, r = n;while (l < r){int mid = (l + r + 1) / 2;if (check(mid))l = mid;elser = 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;
}
这篇关于Codeforces Global Round 17 C. Keshi Is Throwing a Party 题解 二分答案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!