結果

問題 No.1054 Union add query
ユーザー tnakao0123tnakao0123
提出日時 2020-05-16 03:01:53
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,645 bytes
コンパイル時間 789 ms
コンパイル使用メモリ 94,804 KB
実行使用メモリ 12,608 KB
最終ジャッジ日時 2023-10-19 23:04:44
合計ジャッジ時間 4,697 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,816 KB
testcase_01 AC 2 ms
5,816 KB
testcase_02 AC 2 ms
5,816 KB
testcase_03 TLE -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

/* -*- coding: utf-8 -*-
 *
 * 1054.cc:  No.1054 Union add query - yukicoder
 */

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_N = 500000;
const int MAX_Q = 500000;

/* typedef */

template <typename T, const int MAX_N>
struct ExUFT {
  int n, links[MAX_N];
  T vs[MAX_N];
  ExUFT() {}

  void init(int _n) {
    n = _n;
    for (int i = 0; i < n; i++) links[i] = i, vs[i] = 0;
  }

  int root(int i) {
    int i0 = links[i];
    while (links[i0] != i0) {
      vs[i] += vs[i0];
      i0 = links[i0];
    }
    return (links[i] = i0);
  }

  T getv(int i) {
    int ri = root(i);
    return (ri != i) ? vs[i] + vs[ri] : vs[i];
  }

  void addv(int i, T v) {
    int ri = root(i);
    vs[ri] += v;
  }
  
  bool same(int i, int j) { return root(i) == root(j); }

  int merge(int i0, int i1) {
    int r = n++;
    links[r] = r, vs[r] = 0;

    links[root(i0)] = links[root(i1)] = r;
    return r;
  }
};

/* global variables */

ExUFT<int,MAX_N+MAX_Q> uft;

/* subroutines */

/* main */

int main() {
  int n, m;
  scanf("%d%d", &n, &m);

  uft.init(n);

  while (m--) {
    int t, a, b;
    scanf("%d%d%d", &t, &a, &b);

    if (t == 1) {
      a--, b--;
      uft.merge(a, b);
    }
    else if (t == 2) {
      a--;
      uft.addv(a, b);
    }
    else {
      a--;
      printf("%d\n", uft.getv(a));
    }
  }
  return 0;
}
0