Division and Union 贪心!

题意: 给定一堆线段,是否能把所有线段分成两组,满足在两组各任意选择一条线段,使这一对线段不存在交集。若存在则输出每一条线段所在的组号(1或2),若有多种答案,则输出任意一种,若不能分成两组,则输出-1

有端点,肯定得排序,这部分思路没错,但是在确定能否分成两组的时候,需要确定当前组达到的右边界限,不能用当前线段右端点小与下一个线段的左端点来判断,因为当前线段的右端点并不一定是当前组的最右界限!

#include <cstdio>
#include <iostream>
#include <cstring>
#include <sstream>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;
typedef long long LL;
int dis[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
struct Segment
{
    int id;
    int L, R, c;
} seg[maxn];
bool cmp_1(Segment a, Segment b)
{
    if (a.L != b.L)
        return a.L < b.L;
    return a.R < b.R;
}
bool cmp_2(Segment a, Segment b)
{
    return a.id < b.id;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T, n;
    cin >> T;
    while (T--)
    {
        cin >> n;
        for (int i = 1; i <= n; i++)
        {
            cin >> seg[i].L >> seg[i].R;
            seg[i].id = i;
            seg[i].c = 0;
        }
        sort(seg + 1, seg + n + 1, cmp_1);
        int range = seg[1].R;
        seg[1].c = 1;
        int p = -1;
        for (int i = 2; i <= n; i++)
        {
            seg[i].c = 1;
            if (seg[i].L > range)
            {
                p = i;
                seg[i].c = 0;
                break;
            }
            else
            {
                range = max(range, seg[i].R);
            }
        }
        if (p == -1)
        {
            cout << -1;
        }
        else
        {
            sort(seg + 1, seg + n + 1, cmp_2);
            for (int i = 1; i <= n; i++)
            {
                if (seg[i].c == 1)
                    cout << 1 << " ";
                else
                    cout << 2 << " ";
            }
        }
        cout << endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值