B. Buying gifts(贪心)

Problem - B - Codeforces

#include <iostream>
#include <bits/stdc++.h>
#include <cstring>
#include <vector>
#include <algorithm>
#define x first
#define y second
#define fu(i,a,b) for(int i=a;i<=b;i ++ )
#define fd(i,a,b) for(int i=a;i>=b;i -- )
#define endl '\n'
#define ms(x,y) memset(x,y,sizeof x)
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
typedef pair<double,int> PDI;
typedef pair<char,int> PCI;
typedef pair<string,int> PSI;
typedef pair<int,string> PIS;
typedef pair<LL,LL> PLL;
//typedef __int128 i128;
typedef unsigned long long ULL;
const int N = 1e5+ 10,M = 1e5 + 10,INF = 0x3f3f3f3f ;
const int mod = 1e9;
const double eps = 1e-8;

int n;
// 第一个人只能从 第一个商店买东西 。。 
inline void solve()
{
    cin >> n;
    int ans = 1e9;
    
    vector<PII>a(2 * n );
    
    fu(i,0,n-1)
    {
        int x,y;cin >> x >> y ;
        a[2 * i ] = {x,2 * i};
        a[2 *i + 1 ] = {y,2 * i+1};
    }
//  第二维的奇偶性是 对应两个人,偶数->第一个人,奇数 -> 第二个人 
    
    sort(a.begin(),a.end());
    
    PII mx[2][2];
    // i偶数->第一个人,奇数 -> 第二个人 
    // j 当前的 0 最大值  1 次大值 
    ms(mx,-1);
    
    
    vector<bool> st(n);
    int bad = n;
    
    for(auto t : a)
    {
        int u = t.y % 2 ;
        // 当前是第一个商店还第二个商店 
        mx[u][1] = mx[u][0];
        mx[u][0] = t;
        bad -= !st[t.y/2]; 
        // 如果当前部门还没有买东西 就-1 
        st[t.y/ 2 ] = 1; // 当前部门已经选择了 
        
        for(int i=0 ;i < 2; i++ )
        if(!bad && mx[!u][i].y != -1 && mx[!u][i].y != (t.y ^ 1 ) ) 
// 当前 已经考虑完所有部门  且当前人的 另一个人 最大值或次大值已经有商店的选择了,
//且选择的不是和当前这个人同一个商店 
        ans = min(ans,t.x - mx[!u][i].x); 
        // 当前这个人的 值 和 另一个人的最大值和次大值的差取最小    
    }
    
    cout << ans << endl;
            
    
}



signed main()
{
//  freopen("1.txt","w",stdout);
     ios

    int t=1;
    cin>>t;
    int now = 1;
    while(t -- )
    {
//      cout<<"Case "; 
//      cout<<"Case #"; 
//      cout<< now ++ <<": ";
        solve();
    }


    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值