银河英雄传说

题目链接

并查集时记录下以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 ;
}

最新文章

  1. Struts2日期类型转换
  2. orcl 中decode的妙用
  3. SQL Server 2005 发布 订阅 (配置实例[图])(转载)
  4. MySql5.7-多源复制(多主单从)
  5. 组合——Program B
  6. Jfinal中定时器的初步探索(一)
  7. 打地鼠游戏ios源码
  8. 【数论】Baby Step Giant Step
  9. javaScript常用方法整合(项目中用到过的)
  10. 转:45 Useful JavaScript Tips, Tricks and Best Practices
  11. 【转】Android 4.0.3 CTS 测试
  12. Leetcode_119_Pascal&#39;s Triangle II
  13. Image 图片
  14. oracle事务的四个特性(ACID)
  15. 【java工具】java常用工具
  16. MACD:黄白线、红绿柱与0轴关系
  17. OpenCV——基本图形绘制(椭圆、圆、多边形、直线、矩形)
  18. 01: awk常用
  19. [Functional Programming] mapReduce over Async operations with first success prediction (fromNode, alt, mapReduce, maybeToAsync)
  20. 开源代码SlidingMenu的使用

热门文章

  1. 32位x86处理器编程导入——《x86汇编语言:从实模式到保护模式》读书笔记08
  2. pat00-自测5. Shuffling Machine (20)
  3. Thrift笔记(五)--Thrift server源码分析
  4. VS2012 无法启动 IIS Express Web
  5. unity3D使用C#遍历场景内所有元素进行操作
  6. Spring课程 Spring入门篇 4-4 Spring bean装配(下)之Autowired注解说明3 多选一 qualifier
  7. 位运算(5)——Power of Two
  8. echarts环形图点击旋转并高亮
  9. 同源策略和Jsonp、CORS
  10. 从零开始的全栈工程师——JS面向对象( 六大继承 )