蓝桥杯真题:修改数组

本文探讨了暴力搜索和并查集两种解决特定问题的方法,重点介绍了如何通过优化并查集结构,如直接将父节点指向最后一个元素,以减少查找时间,从而解决代码超时问题。作者分享了实际操作中的优化技巧,并展示了优化后的代码片段,帮助读者理解并应用在实际编程中。
摘要由CSDN通过智能技术生成

 

1.暴力思路

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define N 1000005
int exist[N]={0};
int main()
{
  // 请在此输入您的代码
  int n;
  cin>>n;
  vector<int> arr(n,0);
  for(int i=0;i<n;++i)
  {
    int x;
    cin>>x;
    while(exist[x]==1) ++x;
    exist[x]=1;
    arr.push_back(x);
  }
  for(int &x:arr)
  {
    cout<<x<<" ";
  }
  return 0;
}

2.并查集

#include<bits/stdc++.h>
using namespace std;
const int N=2*1e6+5;
vector<int> father(N,-1); 
int find_father(int x){
    while(father[x]!=-1){
        x=father[x];
    }
    return x;
}
void Union(int a,int b){
    int roota=find_father(a);
    int rootb=find_father(b);
    if(roota!=rootb)
        father[roota]=rootb;
}
int main()
{
    int n;
    cin>>n;
    vector<int> arr(n,0);
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        arr[i]=find_father(x);
        Union(arr[i],arr[i]+1);
    }
    for(int i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }
    return 0;
}

不过都超过时间限制了,可能还要优化一下并查集啥的

例如在查找的过程中直接把父节点指向最后的那个:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int Max = 1000010;

int f[Max];
int N;
int getf(int n)
{
    if(f[n] == 0)
        return n;
    return  f[n] = getf(f[n]+1);
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> N;
    int d;
    for(int i = 1; i <= N; ++i)
    {
        cin >> d;
        int fd = getf(d);
        cout << fd << " ";
        f[d] = fd;
        f[fd] = fd;  // 这句不能漏掉,否则不能跳过已经使用过的数字
    }

    return 0;
}

这样就AC了,感谢众大佬教我写题~

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值