这道题和组队赛的那道题基本是一样的。
题目大意:
初始时,有n个龙珠,编号从1到n,分别对应的放在编号从1到n的城市中。
现在又2种操作:
T A B,表示把A球所在城市全部的龙珠全部转移到B城市。(第一次时,因为A球所在的城市只有一个球,所以只移动1个,如果有多个,则全部移动)。
Q A,表示查询A。要求得到的信息分别是:A现在所在的城市,A所在城市的龙珠数目,A转移到该城市移动的次数(如果没有移动就输出0
主要是记录移动次数,其实每个根结点都是最多移动一次的,所以记录移动次数把自己的加上父亲结点的就是移动总数了
感悟:
自己花了2个小时,,
一开始一直纠结在如果每次都访问同一个节点,这个节点会加上他父亲的节点个数,这样的话就会改变值,但实际上,
由于这道题的城市也是编号为1~n,所以当他每个根结点都是最多移动一次的,新加到的父亲是cnt为0的。。(语文不好,解释不清)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<string>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<stack>
#include<cmath>
#include<map>
#include<vector>
#define ll long long
#define inf 0x3f3f3f3f
#define INF 1000000000
#define bug1 cout<<"bug1"<<endl;
#define bug2 cout<<"bug2"<<endl;
#define bug3 cout<<"bug3"<<endl;
using namespace std;
const int maxn=10005;
int fa[maxn];
int n,m;
int num[maxn],cnt[maxn];
int _find(int x){
if(fa[x]==x)return x;
else{
int tmp=fa[x];
fa[x]=_find(fa[x]);
cnt[x]+=cnt[tmp];//传说中的维护,本节点加上父亲节点的移动次数,然后本节点的父亲改变为没有cnt为0的点。
return fa[x];
}
}
void bing(int u,int v){
int fx=_find(u);
int fy=_find(v);
if(fx!=fy){
num[fy]+=num[fx];
fa[fx]=fy;
cnt[fx]++;
}
}
void init(){
for(int i=1;i<=n;++i){
fa[i]=i;
cnt[i]=0;
num[i]=1;
}
}
int main(){
int T;
scanf("%d",&T);
int cas=1;
while(T--){
scanf("%d%d",&n,&m);
init();
printf("Case %d:\n",cas++);
for(int i=1;i<=m;++i){
char str[5];
scanf("%s",&str);
if(str[0]=='T'){
int u,v;
scanf("%d%d",&u,&v);
bing(u,v);
}
else{
int t;
int a;
scanf("%d",&a);
t=_find(a);
cout<<t<<' '<<num[t]<<' '<<cnt[a]<<'\n';
}
}
}
}
本文介绍了一种关于龙珠在不同城市间转移的问题,并提供了一种解决方案。通过使用并查集来跟踪龙珠的位置和移动次数,实现了高效查询和更新。文章详细说明了算法的设计思路及实现细节。
11万+

被折叠的 条评论
为什么被折叠?



