码迷,mamicode.com
首页 > 其他好文 > 详细

银河英雄传说

时间:2018-09-03 00:04:31      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:mes   bsp   include   nbsp   mat   ios   递归   span   clu   

think twice,code once

这道题一开始没想清楚,g[i]表示的是i前面的点,不包括i,

对回溯理解不清,回溯就是递归回来到这里了,再处理一些事......

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 using namespace std;
 5 const int maxn=30007;
 6 int fa[maxn],sz[maxn],g[maxn];
 7 int find(int x){
 8     if(fa[x]==x) return x;
 9     else{
10         int tt=find(fa[x]);
11         g[x]+=g[fa[x]];
12         return fa[x]=tt;
13     }
14 }
15 void merge(int x,int y){
16     int fx=find(x);int fy=find(y);
17     if(fx==fy) return;
18     g[fx]+=sz[fy];fa[fx]=fy;sz[fy]+=sz[fx];sz[fx]=0;
19 }
20 int main(){
21     for(int i=1;i<=maxn;i++){g[i]=0;sz[i]=1;fa[i]=i;}
22     int t;cin>>t;
23     while(t--){
24         char a;cin>>a;
25         int x,y;cin>>x>>y;
26         if(a==M){
27             merge(x,y);
28         }
29         if(a==C){
30             int fx=find(x);int fy=find(y);
31             if(fx!=fy) cout<<-1<<endl;
32             else cout<<abs(g[x]-g[y])-1<<endl;
33         }
34     }
35     return 0;
36 }

 

银河英雄传说

标签:mes   bsp   include   nbsp   mat   ios   递归   span   clu   

原文地址:https://www.cnblogs.com/lcan/p/9575445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!