数据结构----二叉树集合的操作

#include<iostream>
#include<cstdio>
using namespace std;
#define MAXNUM 10001
int SetType[MAXNUM];
void InitialSet(int S[], int N);
void LinkComputer(int S[], int N);
void Islink(int S[], int N);
void TheNumLink(int S[], int N);
int Find(int S[], int num);
int main()
{
    int N;
    char str;
    cin >> N;
    InitialSet(SetType, N); //初始化数组;
    do
    {
        cin >> str;
        switch (str)
        {
        case 'I':
            LinkComputer(SetType, N);
            break;
        case 'C':
            Islink(SetType, N);
            break;
        case 'S':
            TheNumLink(SetType, N);
            break;
        }
    } while (str != 'S');
    return 0;
}
void InitialSet(int S[], int N)
{
    for (int i = 0; i < N; i++)
    {
        S[i] = -1;
    }
    return;
}
void LinkComputer(int S[], int N)
{
    int num1, num2;
    cin >> num1 >> num2;
    int root1 = Find(S, num1 - 1);
    int root2 = Find(S, num2 - 1);
    if (root1 != root2)
    {
        if (S[root1] < S[root2])
        {
            S[root1] += S[root2];
            S[root2] = root1;
        }
        else
        {
            S[root2] += S[root1];
            S[root1] = root2;
        }
    }
    return;
}
void Islink(int S[], int N)
{
    int num1, num2;
    cin >> num1 >> num2;
    int root1 = Find(S, num1 - 1);
    int root2 = Find(S, num2 - 1);
    if (root1 == root2)
        cout << "yes" << endl;
    else
        cout << "no" << endl;
    return;
}
void TheNumLink(int S[], int N)
{
    int counter = 0;
    for (int i = 0; i < N; i++)
    {
        if (S[i] < 0)
            counter++;
    }
    if (counter == 1)
        cout << "The network is connected." << endl;
    else
        cout << "There are " << counter << " components." << endl;
}
int Find(int S[], int num)
{
    if (S[num] < 0)
    {
        return num;
    }
    else
    {
        return S[num] = Find(S, S[num]);
    }
}

 

上一篇:C语言动态内存管理


下一篇:ref参数的使用