博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hdu1962Corporative Network带权回路
阅读量:7258 次
发布时间:2019-06-29

本文共 980 字,大约阅读时间需要 3 分钟。

/*
    有N个企业,每个企业想要实现通信,要用线路来连接,线路的长度为abs(a-b)%1000;
    如果企业a 链接到了企业b 那么b就是the center of the serving!
    然后有两种操作:
    E a : 输出企业a到serving center 的线路的距离
    I a, b  将企业a连接到企业 b,那么b就成为了serving center(之前连接a的企业,他们的serving center也变成了b) 
    
   思路:并查集! (压缩路径时回溯求解) ! 
*/ 
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#define M 20005
using namespace std;
int n;
int f[M];
int ans[M];//节点 i到 serving center的距离! 
int getFather(int x){
    if(x==f[x]) return x;
    int ff=getFather(f[x]);
    ans[x]+=ans[f[x]];//节点x到serving center 的距离要加上其父节点到serving center的距离! 
    return f[x]=ff;
}
void Union(int a, int b){ 
    if(a==b) return;
    f[a]=b;
    ans[a]=abs(a-b) % 1000;
}
int main(){
   int t;
   char ch[3];
   cin>>t;
   while(t--){
      cin>>n;
      int a, b;
      memset(ans, 0, sizeof(ans));
      for(int i=1; i<=n; ++i)
         f[i]=i;
      while(cin>>ch && ch[0]!='O'){
          if(ch[0]=='E'){
             cin>>a;
             getFather(a);
             cout<<ans[a]<<endl;
          }
          else{
             cin>>a>>b;
             Union(a, b);
          }
      }
   }
   return 0;
}
本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/3902548.html,如需转载请自行联系原作者
你可能感兴趣的文章
round 函数
查看>>
在 UIWebView中搜索并高亮度显示文本
查看>>
js的正则表达式RegExp
查看>>
RAC1——Clusterware概念简介1
查看>>
一位10年Java工作经验的架构师聊Java和工作经验
查看>>
试除法求最小N个素数之二
查看>>
HDU2017 字符串统计
查看>>
terminator终端工具
查看>>
【转】那些相见恨晚的 JavaScript 技巧
查看>>
Lind.DDD.Authorization用户授权介绍
查看>>
谈谈设计模式~原型模式(Prototype)
查看>>
商城商品倒计时原生插件
查看>>
激光打印机的Color/paper, Xerography介绍
查看>>
敏捷开发
查看>>
react-native项目构建配置及window调试devtools
查看>>
Gym 100341C AVL Trees NTT
查看>>
第 1 章 虚拟化 - 004 - 启动第一个 KVM 虚机
查看>>
2.1.2_BeanFactory.getBean内部处理逻辑
查看>>
储存过程-原理、语法、函数详细说明
查看>>
第十六周项目6-黑豆传说
查看>>