[启发式合并]#516. 「LibreOJ β Round #2」DP 一般看规律

[启发式合并]#516. 「LibreOJ β Round #2」DP 一般看规律

题目梗概

Flip Flappers,番,可可娜,帕比卡,娅娅卡

给定一个长度为 n 的序列 a,一共有 m 个操作。
每次操作的内容为:给定 x,y,序列中所有 x 会变成 y。

在每次操作后,求出相同元素的最近距离是多少。

解题思路

把一个数字变成另一个数字的过程看成两个坐标集合合并的过程。

用map离散之后,用set进行启发式合并就可以了。

在合并的同时更新答案。

#include<cstdio>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
inline int _read(){
    int num=0;char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9') num=num*10+ch-48,ch=getchar();
    return num;
}
const int maxn=300005;
map<int,int> id;
set<int> a[maxn];
int n,m,ans=2147483647,tot,cx[maxn],cy[maxn];
inline int h(int x){if (!id.count(x)) id[x]=++tot;return id[x];}
int min(int x,int y){if (x<y) return x;return y;}
void Insert(int x,int y){
    a[x].insert(y);
    set<int>::iterator t=a[x].find(y);
    set<int>::iterator t1=t;
    if (t!=a[x].begin()) t1--,ans=min(ans,*t-*t1);
    t1=t;t1++;
    if (t1!=a[x].end()) ans=min(ans,*t1-*t);
}
void merge(int &x,int &y){
    if (a[x].size()>a[y].size()) swap(x,y);
    while(!a[x].empty()){
        int w=*a[x].begin();
        Insert(y,w);
        a[x].erase(w);
    }
    printf("%d\n",ans);
}
int main(){
    freopen("exam.in","r",stdin);
    freopen("exam.out","w",stdout);
    n=_read();m=_read();
    for (int i=1;i<=n;i++){int x=_read();Insert(h(x),i);}
    for (int i=1;i<=m;i++) cx[i]=_read(),cy[i]=_read(),h(cx[i]),h(cy[i]);
    for (int i=1;i<=m;i++) merge(id[cx[i]],id[cy[i]]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值