HDU 6695 Welcome Party 贪心
有个学生,每个人有两个值,每人必须且只能选择一个。
求选出的的最小值。
以每个学生的为关键字降序排序,和数组分别记录当前学生之前和之后的所有值。枚举学生,求出以该学生为的结果。显然,我们可以贪心地去找在后与之差最小的,判断该能否构成答案(是否比已经选择的大),大的话就更新答案。由于是递减的,所以里的值都是已经选择了值的。
修改和查询用到了STL里的和二分。
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<string>
#include<cstring>
#include<algorithm>
#define ll long long
#define inf 0x7fffffffffffffff
#define mem(a, x) memset(a,x,sizeof(a))
#define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
typedef std::pair<int, int> Pii;
typedef std::pair<ll, ll> Pll;
ll power(ll a, ll b,ll p) { ll res = 1; for (; b > 0; b >>= 1) { if (b & 1) res = res * a % p; a = a * a % p; } return res; }
ll gcd(ll p, ll q) { return q == 0 ? p : gcd(q, p % q); }
ll _abs(ll x){return x < 0 ? -x : x;}
using namespace std;
const int N = 1e6 + 10;
struct node{
ll x, y;
bool operator < (const node & rhs)const{
return x > rhs.x;
}
}a[N];
int main(){
//freopen("/Users/gabriel/Desktop/data.in","r",stdin);
int T,n;cin >> T;
while (T--)
{
multiset<ll>pre, suf;
cin >> n;
for (int i = 0; i < n; i++)
scanf("%lld%lld", &a[i].x, &a[i].y), suf.insert(a[i].y);
sort(a , a + n);
ll ans = inf;
for (int i = 0; i < n; i++)
{
suf.erase(suf.find(a[i].y));
if (!pre.empty())
ans = min(ans, _abs(*pre.rbegin() - a[i].x));
if (!suf.empty()){
multiset<ll>::iterator it = suf.lower_bound(a[i].x);
if (it == suf.end()) it--;
ll tmp = _abs(*it - a[i].x);
if (pre.empty() || *it > *pre.rbegin())
ans = min(ans,tmp);
if (it != suf.begin()){
it--;
tmp = _abs(*it - a[i].x);
if (pre.empty() || *it > *pre.rbegin())
ans = min(ans,tmp);
}
}
pre.insert(a[i].y);
}
cout << ans << endl;
}
return 0;
}
浙公网安备 33010602011771号