题目传送门

  首先分析题目,数据范围特别大,500000组询问直接模拟肯定会超时,这里其实很容易可以想到用并查集。我们定义三个数组:fa[]表示每一个飞船的队首,front[]表示每一搜飞船到队首的距离,num[]表示以该飞船为队首的队伍中飞船的数量。每次M操作时就将x的队首的num值清空,并将fa值改变为y的队首,再将front值更新即可。询问时只要判断fa是否相等就可以了,不相等的话直接输出-1,否则输出abs(front[x]-front[y])-1。

  Code:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iomanip>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=3e4+;
int n,fa[N],dis[N],cnt[N];
inline int read()
{
char ch=getchar();int num=;bool flag=false;
while(ch<''||ch>''){if(ch=='-')flag=true;ch=getchar();}
while(ch>=''&&ch<=''){num=num*+ch-'';ch=getchar();}
return flag?-num:num;
}
inline int Abs(int x)
{return x>?x:-x;}
inline int find(int x)
{
if(fa[x]==x)return x;
int fx=find(fa[x]);
dis[x]+=dis[fa[x]];
return fa[x]=fx;
}
int main()
{
n=read();
char s;int x,y;
for(int i=;i<=;i++)
fa[i]=i,dis[i]=,cnt[i]=;
for(int i=;i<=n;i++){
cin>>s;
x=read();y=read();
int fx=find(x),fy=find(y);
if(s=='M'){
if(fx==fy)continue;
dis[fx]+=cnt[fy];
fa[fx]=fy;
cnt[fy]+=cnt[fx];
cnt[fx]=;}
else{
if(fx!=fy)printf("-1\n");
else printf("%d\n",Abs(dis[x]-dis[y])-);
}
}
return ;
}

  

最新文章

  1. linux 压缩包覆盖问题
  2. Spring MVC学习笔记——引入静态文件
  3. 设计模式--装饰模式Decorate(结构型)
  4. php的mysql\mysqli\PDO(三)PDO
  5. smartjs 0.2 OOP讲解 - Klass 类继承
  6. 安装最新版本的ReSharper导致原生全局搜索工具的消失问题
  7. RTSP协议详解
  8. 移动端页面的head头部内容
  9. 关于Eclipse中开发插件(二)
  10. Python格式化字符串--format
  11. hdu 5636 搜索 BestCoder Round #74 (div.2)
  12. css 小坑
  13. hive Spark SQL分析窗口函数
  14. 作业20171123 beta-review 成绩
  15. 简述 cookies 和 session 的区别
  16. 6月4 Smarty练习增删改
  17. IconFont使用指南
  18. 再读c++primer plus 003
  19. ssh 认证
  20. Spring boot 注解简单备忘

热门文章

  1. 洛谷 P1976 鸡蛋饼
  2. vijos 1057 盖房子 简单DP
  3. vijos 1180 选课 树形DP
  4. Flask中路由原理
  5. 大聊Python----协程
  6. Python 源码学习之内存管理 -- (转)
  7. Bagging和Boosting 概念及区别(转)
  8. php中的__call()函数重载
  9. Xmind 8 update5 破解
  10. 仿照linux dpm机制,实现自己的dpm【转】