T^T ONLINE JUDGE 2592

 

题目地址:http://www.fjutacm.com/Problem.jsp?pid=2592

查询队列

TimeLimit:2500MS  MemoryLimit:32MB
64-bit integer IO format:%lld
已解决 | 点击收藏
Problem Description

初始时,一个队列中有n个数,分别为1,2,……n

接下来有m个操作,每次操作删去队列中在数值范围内[l,r]内最小的数

 

Input

每个测试文件只有一组数据

第一行是两个整数n,m

接下m行,每行有两个整数l,r

其中n<=1e6,m<=1e6

1<l<=r<=n

其中20%的数据

n <=10000

m<=10000

其中80%的数据

n <= 100000

m<=1000000

其中100%的数据

n <=1000000

m<=1000000

 

Output

对于每次操作输出被删去的数,若不存在数值在[l,r]内的数则输出-1

SampleInput
10 10
2 10
3 5
1 6
1 6
4 9
4 4
3 3
5 5
6 10
4 5
SampleOutput
2
3
1
4
5
-1
-1
-1
6
-1

【思路】:
一开始我们建一个并查集:
如图

 

是一堆散开的点,他们的pre【i】=i

即自己是自己的父节点

他要删除的是【l,r】的最小值

那么我们可以采用并查集将其连接起来

如我删去【1,8】的最小值

肯定是1,那么我们改变1的父节点即可

如图

这样每次查询1,就会得到2

再删去【1,8】的最小节点

那么我们就pre【find(x)】=find(x+1)

即可

如图:

你可以通过压缩路径:

变成

 

 附上代码:

/**
rid: 179815
user: 136155330
time: 2018-04-15 22:13:12
result: Accepted 
*/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;
const int maxn = 1000000+7;

int pre[maxn],n,m;

void init()
{
    for(int i = 1; i <= n+1; i++) {
        pre[i] = i;
    }
}

int findx(int x)
{
    return pre[x] == x ? pre[x] : pre[x] = findx(pre[x]);
}

void join(int x,int y)
{
    int fx = findx(x);
    int fy = findx(y);
    if(fx != fy ) {
        pre[fx] = fy ;
    }
}

bool same (int x, int y)
{
    return findx(x) == findx(y);
}

int main()
{
    int l,r,root;
    while(~scanf("%d%d",&n,&m))
    {
        init();
        for( int i = 1; i <= m; i++) {
            scanf("%d%d",&l,&r);
            root = findx(l);
            if(root > r) {
                puts("-1");
            }
            else {
                printf("%d\n",root);
                pre[root] = root + 1;
            }
        }
    }
    return 0;
}

 

 


posted @ 2018-07-30 11:18  moxin0509  阅读(195)  评论(0编辑  收藏  举报