UVALive - 3027Corporative Network(帶權並查集)

來源:互聯網
上載者:User

標籤:http   io   ar   for   cti   sp   代碼   on   c   

題目: UVALive - 3027Corporative Network(帶權並查集)


題目大意:有n和節點,初始時每個節點的父節點都不存在,然後有下面兩種操作:I 操作 I a,b 將a的父節點變成b。E操作 E a,查詢a到它的父節點的距離。


解題思路:帶權並查集。注意這裡距離的變化是a -> b,那麼a到根節點的距離就是a到b的距離的絕對值 % 1000 + b到它的根節點的距離。


代碼:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 2e5 + 5;int p[maxn], c[maxn];int n;void init () {for (int i = 1; i <= n; i++) {p[i] = i;c[i] = 0;}}int getParent (int a) {if (a == p[a])return a;int t = p[a];p[a] = getParent (p[a]);c[a] += c[t];return p[a];}int main () {int T;int a, b;char str[10];scanf ("%d", &T);while (T--) {scanf ("%d", &n);init();while (scanf ("%s", str) != EOF) {if (str[0] == 'O')break;if (str[0] == 'E') {scanf ("%d", &a);int q1 = getParent (a);printf ("%d\n", c[a]);} else {scanf ("%d%d", &a, &b);p[a] = b;c[a] = abs (a - b) % 1000;}}}return 0;}

 

UVALive - 3027Corporative Network(帶權並查集)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.