UVa 1329 - Corporative Network Union Find題解

來源:互聯網
上載者:User

標籤:blog   http   使用   資料   2014   for   

UVa的題目好多,本題是資料結構的運用,就是Union Find並查集的運用。主要使用路徑壓縮。甚至不需要合并樹了,因為沒有重複的連線和修改單親節點的操作。

鬱悶的就是不太熟悉這個Oj系統,居然使用庫中的abs就會WA,自己寫了個abs小函數就過了。

題目:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4075

#include <stdio.h>const int MAX_N = 20005;const int MOD = 1000;//在UVa使用庫的abs居然WA,浪費好多時間inline int abs(int a) { return a < 0? -a : a; }struct Subset{int p, w;};Subset subs[MAX_N];int findParent(int x){if (subs[x].p != x){int p = subs[x].p;subs[x].p = findParent(subs[x].p);subs[x].w = (subs[x].w + subs[p].w);}return subs[x].p;}void initSubs(int N){for (int i = 1; i <= N; i++){subs[i].p = i;subs[i].w = 0;}}int main(){int T, N, i, j;char cmd;scanf("%d", &T);while (T--){scanf("%d", &N);getchar();initSubs(N);while ((cmd = getchar()) && cmd != 'O'){if (cmd == 'E'){scanf("%d", &i);subs[i].p = findParent(i);printf("%d\n", subs[i].w);}else{scanf("%d %d", &i, &j);subs[i].w = (abs(j - i))%MOD;subs[i].p = j;//不存在重複連線和更改parent,故此直接連就ok}getchar();}}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.