ZOJ - 4120 Tokens on the Segments 第十届山东ACM省赛H题

探讨在二维平面上放置令牌以最大化覆盖段落数量的问题,通过按右端点排序并使用集合数据结构来实现最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Consider segments on a two-dimensional plane, where the endpoints of the -th segment are and . One can put as many tokens as he likes on the integer points of the plane (recall that an integer point is a point whose and coordinates are both integers), but the coordinates of the tokens must be different from each other.

What's the maximum possible number of segments that have at least one token on each of them?

Input

The first line of the input contains an integer (about 100), indicating the number of test cases. For each test case:

The first line contains one integer (), indicating the number of segments.

For the next lines, the -th line contains 2 integers (), indicating the coordinates of the two endpoints of the -th segment.

It's guaranteed that at most 5 test cases have .

Output

For each test case output one line containing one integer, indicating the maximum possible number of segments that have at least one token on each of them.

Sample Input

2
3
1 2
1 1
2 3
3
1 2
1 1
2 2

Sample Output

3
2

Hint

For the first sample test case, one can put three tokens separately on (1, 2), (2, 1) and (3, 3).

For the second sample test case, one can put two tokens separately on (1, 2) and (2, 3).

 

比赛的时候卡这题卡了两个多小时,结果是发现要按右端点从小到大排序,不能按左端点,比赛的时候硬是没举出反例QAQ

比如我自己找了一个样例

4

2  2

1  5

3  6

1  3

如果按左端点从小到大排的话,那么这个样例会输出3,如果按右端点从小到大排的话那么会输出4,具体为什么大家可以画一画图就明白了

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int l;
    int r;
}s[100005];
bool cmp(node a,node b)//好好理解
{
    if(a.l==b.l) return a.r<b.r;
    return a.l<b.l;
}
set<int>se;//用set方便一些
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        se.clear();
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d %d",&s[i].l,&s[i].r);
        }
        sort(s,s+n,cmp);
        for(int i=0;i<n;i++)
        {
            for(int j=s[i].r;j>=s[i].l;j--)
            {
                if(!se.count(j))
                {
                    se.insert(j);
                    break;
                }
            }
        }
        int ans=se.size();
        printf("%d\n",ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值