Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

第一次一次性AC, 纪念一下。 什么叫路径压缩,牛人解释下

Posted by hongbinneu at 2009-04-04 20:09:19 on Problem 2524
#include <iostream>

using namespace std;

int pre[50001];
int num;

void makeset(int i)
{
    pre[i] = -1;
}

int find(int a)
{
    if (pre[a] < 0)
        return a;
    else 
        return find(pre[a]);
}

void uni(int a, int b)
{
    int t1 = find(a);
    int t2 = find(b);
    if (t1 == t2)
        return;
    num--;
    if (pre[t1] < pre[t2])
    {
        pre[t1] += pre[t2];
        pre[t2] = t1;    
    }
    else
    {
        pre[t2] += pre[t1];
        pre[t1] = t2;
    }
}

int main()
{
    //freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);
    int n, m;
    int cases = 0;

    while (1)
    {
        cases++;
        scanf("%d%d", &n, &m);
        if (n == 0 && m == 0) break;
        for (int i = 1; i <= n; i++)
        {
            makeset(i);
        }
        num = n;
        for (int i = 0; i < m; i++)
        {
            int a, b;
            scanf("%d%d", &a, &b);
            uni(a, b);            
        }
        printf("Case %d: %d\n",cases, num);
    }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator