51nod 1460 连接小岛

> 1 460 连接小岛

> 题目来源: CodeForces 基准时间限制:1.5 秒 空间限制:131072 KB 分值: 40 难度:4级算法题

有n个小岛,每一个小岛是直线型的,他们不相互相交,第i个小岛所占的区间是[li, ri],而且, ri < li+1 对于所有的 1 ≤ i ≤ n-1。现在要将相邻的小岛用桥连接起来。现在有一条桥的长度是a,第i个岛和第i+1个岛能够连接的条件是,存在x,y使得 li ≤ x ≤ ri, li+1 ≤ y ≤ ri+1 且 y - x = a成立。现在有m条桥,每条桥最多被使用一次,问能否把这些岛连接起来。

样例解释:在这个样例中,把第2条桥两个端点放在3和8,把第三条桥两个端点放在7和10,把第一条桥的端点放在10和14。
Input
单组测试数据。 第一行有两个整数n (2 ≤ n ≤ 2*10^5) 和 m (1 ≤ m ≤ 2*10^5),表示岛的数目和桥的数目。
接下来n行,每行有两个整数 li 和 ri (1 ≤ li ≤ ri ≤ 10^18),表示岛的两个端点。 接下来一行有m个整数 a1,
a2, …, am (1 ≤ ai ≤ 10^18),表示每一条桥的长度。

Output

如果能够将n座岛连接起来输出YES,否则输出NO。

Input示例

4 4 1 4 7 8 9 10 12 14 4 5 3 8

Output示例

YES

首先看n的范围,n^2很明显爆时间了,所以要采取优化措施,怎么优化?二分,分治?其实这里采用了multiset(一个能够有重复项的set)进行了优化,set的查询时间是log2n,所以时间就是nlog2n。

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<queue>
#include<stack>
#include<map>
#include<stdlib.h>
#include<set>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
#define Pi acos(-1.0)
#define EXP 1e-9
#define up(i,x,y) for(int i=x;i<=y;i++)
#define down(i,x,y) for(int i=x;i>=y;i--)
#define w(x) while(x)
#define Mod 1000000007
const int maxn = 200010;
struct node{
    LL mi;
    LL ma;
}a[maxn];

bool cmp(node a,node b){
    if(a.ma == b.ma)
        return a.mi < b.mi;
    else
        return a.ma < b.ma;
}
int main()
{
    ios::sync_with_stdio(false);
    int n,m;
    LL x,y;
    cin>>n>>m>>x>>y;
    for(int i=1;i<n;i++){
        LL newx,newy;
        cin>>newx>>newy;
        a[i].mi=newx-y;
        a[i].ma=newy-x;
        x=newx;
        y=newy;
    }
    sort(a+1,a+n,cmp);
    multiset<LL> bridge;
    for(int i=1;i<=m;i++){
        LL b;
        cin>>b;
        bridge.insert(b);
    }
    int cnt = 0;
    multiset<LL>::iterator iter;
    for(int i=1;i<n;i++){
        iter = bridge.lower_bound(a[i].mi);
        if( iter == bridge.end() || *iter > a[i].ma)
            break;
        else{
            cnt++;
            bridge.erase(iter);
            if(cnt == n-1)
                break;
        }
    }
    if(cnt == n-1)
        cout<<"YES"<<endl;
    else
        cout<<"NO"<<endl;
    return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值