- 时间限制 2000ms
- 空间限制 262144K
There are n points in an array with index from 1 to n, and there are two operations to those points.
1: 1 x marking the point xx is not available
2: 2 x query for the index of the first available point after that point (including x itself) .
Input
q is the number of queries, zz is the type of operations, and xx is the index of operations. 1≤x<n<10^9,1<q<10^6 and z is 1 or 2
Output
Output the answer for each query.
样例输入复制
5 3
1 2
2 2
2 1
样例输出复制
3
1
链接:https://nanti.jisuanke.com/t/41384
题意:n个有序数,q次查询,1操作删除x,2操作查询x后面第一个数。
题解:q的值比较小,所以解题应该从q入手 用并查集模拟实现一个链表 用map模拟并查集,初始时每个点的父亲指向后面第一个可用的点。 当删除一个点i时,令x的父亲等于x+1的父亲 查询时直接输出 x 的父亲。(正解)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 100;
unordered_map<int, int> fa;
int findfa(int x) {
if (!fa.count(x)) return x;
return fa[x] = findfa(fa[x]);
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
int n, q;
scanf("%d %d", &n, &q);
int op, x;
while (q--) {
scanf("%d %d", &op, &x);
if (op == 1) {
fa[x] = findfa(x + 1);
} else {
int ans = findfa(x);
if (ans > n) ans = -1;
printf("%d\n", ans);
}
}
return 0;
}
题解:纯unordered_set操作,插入时间复杂度O(1),查询时间复杂度为线性时间,竟然可以过!
#include <iostream>
#include <cstdio>
#include <unordered_set>
#include <utility>
using namespace std;
unordered_set<int> s;
int main()
{
int n,q,z,x;
scanf("%d%d",&n,&q);
for (int i = 1; i <= q; i++)
{
scanf("%d%d", &z, &x);
if (z == 1) s.insert(x);
else if (z == 2)
{
while (s.find(x) != s.end()) x += 1;
printf("%d\n", x);
}
}
return 0;
}