最近等对 51Nod - 1571

https://www.51nod.com/Challenge/Problem.html#!#problemId=1571

妈的垃圾51nod 总是卡输入输出

把所有线段按左端点排序 作为第一维 右端点为第二维 cdq分治

 

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=0x3f3f3f3f3f3f3f3f;
const int maxn=5e5+10;

struct node
{
    int tp,id,l,r;
};

node order[2*maxn],tmp[2*maxn];
ll ans[maxn],ary[maxn],gou[maxn];
int book[maxn];
int n,q,tot;

template <class T>
inline void _cin(T &ret)		//读正负整数 (int, long long)
{
    char ch;
    int flag = 0;
    while((ch = getchar()) < '0' || ch > '9')
    {
        if(ch == '-') flag = 1;
    }
    for(ret = 0; ch >= '0' && ch <= '9'; ch = getchar())
    	ret = ret * 10 + ch - '0';
    if(flag) ret *= -1;
}

template <class T>
inline void print_d(T x)
{
    if (x > 9)
    {
        print_d(x / 10);
    }
    putchar(x % 10 + '0');
}

bool cmp(node n1,node n2)
{
    if(n1.l==n2.l){
        if(n1.r==n2.r) return n1.tp>n2.tp;
        else return n1.r>n2.r;
    }
    else return n1.l<n2.l;
}

void cdq(int l,int r)
{
    ll minn;
    int m,i,p,q;
    if(l==r) return;
    m=(l+r)/2;
    cdq(l,m),cdq(m+1,r);
    i=l,p=l,q=m+1,minn=N;
    while(p<=m&&q<=r){
        if(order[p].r>=order[q].r){
            if(order[q].tp==1) minn=min(minn,(ll)(order[q].r-order[q].l));
            tmp[i++]=order[q++];
        }
        else{
            if(order[p].tp==2) ans[order[p].id]=min(ans[order[p].id],minn);
            tmp[i++]=order[p++];
        }
    }
    while(p<=m){
        if(order[p].tp==2) ans[order[p].id]=min(ans[order[p].id],minn);
        tmp[i++]=order[p++];
    }
    while(q<=r){
        tmp[i++]=order[q++];
    }
    for(i=l;i<=r;i++) order[i]=tmp[i];
}

int main()
{
    int i,val,l,r;
    _cin(n),_cin(q);
    for(i=1;i<=n;i++){
        _cin(val);
        ary[i]=val,gou[i]=val;
    }
    sort(gou+1,gou+n+1);
    tot=unique(gou+1,gou+n+1)-gou-1;
    for(i=1;i<=n;i++) ary[i]=lower_bound(gou+1,gou+tot+1,ary[i])-gou;
    for(i=1;i<=n;i++){
        if(book[ary[i]]!=0){
            tot++;
            order[tot].tp=1,order[tot].l=book[ary[i]],order[tot].r=i;
        }
        book[ary[i]]=i;
    }
    for(i=1;i<=q;i++){
        _cin(l),_cin(r);
        tot++;
        order[tot].tp=2,order[tot].id=i,order[tot].l=l,order[tot].r=r;
    }
    sort(order+1,order+tot+1,cmp);
    for(i=1;i<=q;i++) ans[i]=N;
    cdq(1,tot);
    for(i=1;i<=q;i++){
        if(ans[i]==N) puts("-1");
        else{
            print_d(ans[i]);
            puts("");
        }
    }
    return 0;
}

/*
5 3
1 2 3 1 2
1 1
2 2
1 5
*/

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值