【洛谷】P8686 [蓝桥杯 2019 省 A] 修改数组 的题解
题目传送门
思路
数据量还是蛮大的,直接暴力 1 1 1 秒跑不完,主要的时间都花费在读入一个数,查找没有出现过的第一个数上,考虑利用并查集优化这个过程。
将出现过的连续数字都构造到一棵树里,然后将每一个数的父节点直接标记为与它连续的且前面出现过的最大数。
那么在之后读入数据的时候如果这个数已经出现过,就可以直接找它的父节点,将这个数修改为父节点的数字加一输出。
但是两个问题:
-
树不是直接就构造成这样的,这涉及到了并查集的路径压缩。
-
在读入元素修改过后,还要判断修改数的前后数字是否出现过,也就是看树能不能合并。
思路
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <climits>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <ctime>
#include <string>
#include <cstring>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int fa[1000005];
bool vis[1000005];
int find(int x) {
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main() {
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
memset(vis,false, sizeof(vis));
for(int i = 1; i <= 1000000; i++) fa[i] = i;
int n, x;
cin >> n;
for(int i = 1; i <= n; i ++) {
cin >> x;
if(vis[x]) x = find(x) + 1;
cout << x << " ";
vis[x] = true;
if(vis[x - 1] && x != 1) fa[x - 1] = x;
if(vis[x + 1]) fa[x] = x + 1;
}
return 0;
}