P8686 [蓝桥杯 2019 省 A] 修改数组 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
这题首先想到的是80%的暴力解法O(N^2),普通的模拟一个数一个数的往后推就好了(如果蓝桥杯上没有那么多时间,暴力也是一种不错的选择)以下是暴力代码:
#include<iostream>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<cstring>
#include<unordered_map>
#define int long long
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
unordered_map<int,int> mp;
int n,a[200005],b[200005];
signed main()
{
cin>>n;
for (int i = 1; i <= n; ++i)
{
cin>>a[i];
if (!mp.count(a[i])) mp[a[i]] = a[i],b[i]=a[i];
else
{
b[i] = a[i];
while(mp.count(b[i]))
{
mp[b[i]]++;
b[i] = mp[b[i]];
}
mp[b[i]] = b[i];
}
}
for (int i = 1; i <= n; ++i) cout<<b[i]<<" ";
return 0;
}
但是不知道为什么开了O2优化(氧气优化bushi) 能混过去,有无佬能给我这个小菜鸡解答一下。orz
接着是满分做法,用并查集做,之前我对于并查集的理解单单停留在将两个数合并成一个集合,判断他们是否在同一个集合里,也就导致了这题我想不到并查集这种解法,我们会想找这个数是否重复,以及这个数+1是否重复(不重复就变成他),否则就往后跳,这就希望会有预处理来减少时间复杂度,而并查集正是这道题的巧妙解法(当然也可以set+二分)
以下是并查集解法的代码:
#include<iostream>
#include<cmath>
#define int long long
#define endl '\n'
using namespace std;
int fa[100100];
int find(int x) //并查集
{
if (fa[x] == x) return x;
else
{
fa[x] = find(fa[x]); //记忆化路径压缩
return fa[x];
}
}
signed main()
{
int n,x;
cin>>n;
for (int i = 1; i <= 100010; ++i) fa[i] = i; //初始化
for (int i = 1; i <= n; ++i)
{
cin>>x;
x = find(x); //找x的祖宗,如果没出现过就是x ,
//出现过就会找到+1的数的祖宗(一定会找到没有出现过的数)
fa[x] = find(x) + 1; // +1 预处理
cout<<x<<" ";
}
return 0;
}
这是本菜鸡第一次发题解,请佬们多多指教Orz