[启发式合并]#516. 「LibreOJ β Round #2」DP 一般看规律
来源:互联网 发布:vscode xp版本 编辑:程序博客网 时间:2024/06/03 12:10
[启发式合并]#516. 「LibreOJ β Round #2」DP 一般看规律
题目梗概
给定一个长度为 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
- #516. 「LibreOJ β Round #2」DP 一般看规律 set启发式合并
- [启发式合并]#516. 「LibreOJ β Round #2」DP 一般看规律
- 【并查集+平衡树启发式合并】LibreOJ β Round #2[DP一般看规律]题解
- 「LibreOJ β Round #2」DP 一般看规律
- 516. 「LibreOJ β Round #2」DP 一般看规律 [set/SPLAY] 【STL/数据结构】
- #516. 「LibreOJ β Round #2」DP 一般看规律 stl容器
- [分块+并查集按秩合并]#519. 「LibreOJ β Round #2」数学上来先打表
- #515. 「LibreOJ β Round #2」贪心只能过样例 (简单dp+bitset优化)
- #507. 「LibreOJ NOI Round #1」接竹竿 dp
- 【LibreOJ】6177 「美团 CodeM 初赛 Round B」送外卖2 状压DP
- [状压DP]LibreOJ #6177. 「美团 CodeM 初赛 Round B」送外卖2 题解
- LibreOJ #505.「LibreOJ β Round」ZQC 的游戏 网络流
- LibreOJ #504. 「LibreOJ β Round」ZQC 的手办 线段树+堆
- [结论] LibreOJ #520. 「LibreOJ β Round #3」绯色 IOI(开端)
- [匹配+拓扑] LibreOJ #521. 「LibreOJ β Round #3」绯色 IOI(抵达)
- [数学杂题] LibreOJ #530「LibreOJ β Round #5」最小倍数
- [数学杂题] LibreOJ#532. 「LibreOJ β Round #5」随机数列
- loj#526. 「LibreOJ β Round #4」子集
- C++ GUI Programming with Qt4 Second Edition 之 引语
- Redis INFO CPU 信息详解
- 内存映射mmap
- Java方向学习路线建议
- Java类和对象
- [启发式合并]#516. 「LibreOJ β Round #2」DP 一般看规律
- webapp实现蓝牙串口通讯
- 关于MacOS升级10.13系统eclipse菜单灰色无法使用解决方案
- pat 1099
- hdu 2586 How far away? LCA 解题报告
- 最短路 (floyed)
- Vue+cordova camera插件采用dataurl格式导致内存问题的解决方案
- 字符串next函数求值
- 使用Spring + quartz集群持久化时注意事项