【洛谷P1196】[NOI2002]银河英雄传说
2024-08-29 11:54:02
银河英雄传说
并查集时记录下以i为首的队列的长度(如果存在这个队列)num[i],便于合并,
和点i到队首的距离front[i],便于查询(在find时维护)
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 30010
#define abs(x) ((x)>0?(x):-(x))
const int n=;
int m,fa[N],front[N],num[N];
inline int read(){
int x=; char c=getchar();
while(c<''||c>'') c=getchar();
while(''<=c&&c<='') { x=(x<<)+(x<<)+c-''; c=getchar(); }
return x;
}
inline int find(int x){
if(fa[x]==x) return x;
int fx=find(fa[x]);
front[x]+=front[fa[x]]; //改变fa[x]为祖先的同时要把fa[x]到祖先的长度加上
return fa[x]=fx;
}
int main()
{
for(int i=;i<=n;i++){
fa[i]=i;
front[i]=;
num[i]=;
}
scanf("%d",&m);
char type[];
int x,y;
while(m--){
scanf("%s",type);
x=read(); y=read();
int fx=find(x),fy=find(y);
if(type[]=='M'){
fa[fx]=fy;
front[fx]+=num[fy]; //fx前面多了num[fy]个元素
num[fy]+=num[fx]; //fy的队列增长了num[fx]
num[fx]=; //fx的队列不存在了
}
else{
if(fx!=fy) puts("-1");
else
printf("%d\n",abs(front[x]-front[y])-);
}
}
return ;
}
最新文章
- Struts2日期类型转换
- orcl 中decode的妙用
- SQL Server 2005 发布 订阅 (配置实例[图])(转载)
- MySql5.7-多源复制(多主单从)
- 组合——Program B
- Jfinal中定时器的初步探索(一)
- 打地鼠游戏ios源码
- 【数论】Baby Step Giant Step
- javaScript常用方法整合(项目中用到过的)
- 转:45 Useful JavaScript Tips, Tricks and Best Practices
- 【转】Android 4.0.3 CTS 测试
- Leetcode_119_Pascal&#39;s Triangle II
- Image 图片
- oracle事务的四个特性(ACID)
- 【java工具】java常用工具
- MACD:黄白线、红绿柱与0轴关系
- OpenCV——基本图形绘制(椭圆、圆、多边形、直线、矩形)
- 01: awk常用
- [Functional Programming] mapReduce over Async operations with first success prediction (fromNode, alt, mapReduce, maybeToAsync)
- 开源代码SlidingMenu的使用
热门文章
- 32位x86处理器编程导入——《x86汇编语言:从实模式到保护模式》读书笔记08
- pat00-自测5. Shuffling Machine (20)
- Thrift笔记(五)--Thrift server源码分析
- VS2012 无法启动 IIS Express Web
- unity3D使用C#遍历场景内所有元素进行操作
- Spring课程 Spring入门篇 4-4 Spring bean装配(下)之Autowired注解说明3 多选一 qualifier
- 位运算(5)——Power of Two
- echarts环形图点击旋转并高亮
- 同源策略和Jsonp、CORS
- 从零开始的全栈工程师——JS面向对象( 六大继承 )