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)(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 nnn (1≤n≤2⋅105)(1\le n\le 2 \cdot 10^5)(1≤n≤2⋅105) — 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)(0≤ai,bi<n).
It is guaranteed that the sum of nnn over all test cases doesn’t exceed 2⋅1052 \cdot 10^52⋅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) // 邀请人数已足够,返回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;
}


被折叠的 条评论
为什么被折叠?



