zoukankan      html  css  js  c++  java
  • UVALive 3027(并查集)

    题意:某公司的各企业群要建立联系,I i j 表示企业i与企业j建立联系,并且以企业j为中心(并查集中的父亲)(企业j为暂时的中心企业),E i 表示查询企业 i 距离此时的中心企业的距离。各企业间的距离规定:企业i 与 企业j 间距离为|i - j| % 1000。

    分析:改造并查集中的find函数,每次查询i企业到中心企业的距离时,不断向上依次寻找他的父亲,直到找到中心企业为止,不断累加现企业与其父亲企业间的距离即可。

     1 #include<cstdio>
     2 #include<cstring>
     3 #include<cctype>
     4 #include<cstdlib>
     5 #include<cmath>
     6 #include<iostream>
     7 #include<sstream>
     8 #include<iterator>
     9 #include<algorithm>
    10 #include<string>
    11 #include<vector>
    12 #include<set>
    13 #include<map>
    14 #include<deque>
    15 #include<queue>
    16 #include<stack>
    17 #include<list>
    18 #define fin freopen("in.txt", "r", stdin)
    19 #define fout freopen("out.txt", "w", stdout)
    20 #define pr(x) cout << #x << " : " << x << "   "
    21 #define prln(x) cout << #x << " : " << x << endl
    22 typedef long long ll;
    23 typedef unsigned long long llu;
    24 const int INT_INF = 0x3f3f3f3f;
    25 const int INT_M_INF = 0x7f7f7f7f;
    26 const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
    27 const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
    28 const double pi = acos(-1.0);
    29 const double EPS = 1e-6;
    30 const int dx[] = {0, 0, -1, 1};
    31 const int dy[] = {-1, 1, 0, 0};
    32 const ll MOD = 1e9 + 7;
    33 const int MAXN = 20000 + 10;
    34 const int MAXT = 10000 + 10;
    35 using namespace std;
    36 int fa[MAXN];
    37 int ans;
    38 void find(int v)
    39 {
    40     ans += abs(fa[v] - v) % 1000;
    41     if(fa[v] == v) return;
    42     else find(fa[v]);
    43 }
    44 int main()
    45 {
    46     int T;
    47     scanf("%d", &T);
    48     while(T--)
    49     {
    50         int N;
    51         scanf("%d", &N);
    52         char c;
    53         for(int i = 1; i <= N; ++i)
    54             fa[i] = i;
    55         while(scanf("%c", &c) == 1)
    56         {
    57             if(c == 'O') break;
    58             if(c == 'E')
    59             {
    60                 int x;
    61                 scanf("%d", &x);
    62                 ans = 0;
    63                 find(x);
    64                 printf("%d\n", ans);
    65             }
    66             else if(c == 'I')
    67             {
    68                 int a, b;
    69                 scanf("%d%d", &a, &b);
    70                 fa[a] = b;
    71             }
    72         }
    73     }
    74     return 0;
    75 }
  • 相关阅读:
    适合程序员的两样工具-续集
    JavaScript之面向对象1
    人类简史笔记摘录
    做正确的事
    个人高效率任务列表
    视频技术基础
    了解更多梭罗与瓦尔登湖
    禅与摩托车维修的艺术
    人工智能发展及算法
    互联网没能降低房价,人工智能就可以不?
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/5906426.html
Copyright © 2011-2022 走看看