欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Division and Union 贪心!

程序员文章站 2022-06-03 13:58:10
...

Division and Union 贪心!

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;
}

 

相关标签: 思维 贪心