帶權並查集 La 3027

來源:互聯網
上載者:User


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


每參考題解的時候其實我已經自己類比把並查集改為帶權並查集了

但是因為模數弄錯  WA了幾個小時。。。。。。。。。。。。


其實在回溯的時候,修改權值就行,然後查詢之前,還需要再維護一次

先貼我的垃圾代碼,好TMD冗雜:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <functional>using namespace std;#define MAXN 20010#define MOD 1000int father[MAXN],dis[MAXN];void makeset(int n){    for(int i=0;i<=n;i++)    {        father[i]=i;        dis[i]=0;    }}inline int ABS(int a,int b){    if(a-b>0)return a-b;    else return b-a;}int Find1(int x){    if(x != father[x])    {        int t = Find1(father[x]);        dis[x]+=dis[father[x]];        father[x] =t;        return father[x];    }    else    return x;}void Union(int x, int y){    /*調用Union之前必須先確定x,y不在同一個集合,然後把x的父節點改為y*/    dis[x]=ABS(x,y)%MOD;    int t=Find1(y);    dis[y]+=dis[t];    dis[x]+=dis[y];    y=t;    father[x]=y;}int main(){    //freopen("La 3027.txt","r",stdin);    int n,ncase,u,v;    char c;    scanf("%d",&ncase);    while(ncase--)    {        scanf("%d",&n);        makeset(n);        while(1)        {            while((c=getchar()) != 'O' && c != 'E' && c != 'I');            if(c == 'O')break;            if(c == 'E')            {                scanf("%d",&u);                Find1(u);                printf("%d\n",dis[u]);            }            else            {                if(c == 'I')                {                    scanf("%d%d",&u,&v);                    Union(u,v);                    //dis[u]=(ABS(u,v))%MOD;                    //father[u]=v;                }            }        }    }    return 0;}



然後看了劉汝佳的代碼  果然大牛,比My Code短了一半......

// LA3027 Corporative Network// Rujia Liu#include<iostream>#include<string>#include<algorithm>using namespace std;const int maxn = 20000 + 10;int pa[maxn], d[maxn];int findset( int x ) {  if (pa[x] != x) {    int root = findset( pa[x] );    d[x] += d[pa[x]];    return pa[x] = root;   } else return x;}int main() {  int T;  cin >> T;  while(T--) {    int n, u, v;    string cmd;    cin >> n;    for(int i = 1; i <= n; i++) { pa[i] = i; d[i] = 0; }    while(cin >> cmd && cmd[0] != 'O') {      if(cmd[0] == 'E') { cin >> u; findset(u); cout << d[u] << endl; }      if(cmd[0] == 'I') { cin >> u >> v; pa[u] = v; d[u] = abs(u-v) % 1000; }    }  }  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.