PTA浙江大学数据结构习题——第五周

树7 堆中的路径

插入所有节点后,从下往上不断输出当前结点的父节点即可。

#include <iostream>

using namespace std;

#define MinData -10010

typedef struct HeapStruct *MinHeap;
struct HeapStruct
{
    
    
    int *arr;
    int size, capacity;
};

MinHeap create(int maxsize)
{
    
    
    MinHeap H = (MinHeap)malloc(sizeof (struct HeapStruct));
    H->arr = (int*)malloc((maxsize + 1) * sizeof(int));
    H->size = 0;
    H->capacity = maxsize;
    H->arr[0] = MinData;    // 哨兵,小于所有元素
    return H;
}

bool isfull(MinHeap H)
{
    
    
    if (H->size == H->capacity) return true;
    return false;
}

void insert(MinHeap H, int x)
{
    
    
    if (isfull(H))
    {
    
    
        puts("当前小根堆已满");
        return;
    }
    
    H->size ++;
    int cur = H->size;
    for (; H->arr[cur / 2] > x; cur /= 2)
        H->arr[cur] = H->arr[cur / 2];
    H->arr[cur] = x;
}

int main()
{
    
    
    int n, m, x;
    cin >> n >> m;
    
    MinHeap H = create(n);
    for (int i = 0; i < n; i ++)
    {
    
    
        cin >> x;
        insert(H, x);
    }
    
    int i;
    for (int j = 0; j < m; j ++)
    {
    
    
        cin >> i;
        while (i > 1)
        {
    
    
            cout << H->arr[i] << " ";
            i /= 2;
        }
        cout << H->arr[1] << endl;
    }
    
    return 0;
}

树8 File Transfer

s[i] 存的是编号为 i 的电脑的根节点。

#include <iostream>
#include <unordered_set>

using namespace std;

const int N = 10010;

int n;
int s[N];
unordered_set<int> root;

int find(int x)
{
    
    
    if (s[x] != x)  s[x] = find(s[x]);
    return s[x];
}

void add(int x, int y)
{
    
    
    s[find(x)] = find(y);
}

int main()
{
    
    
    cin >> n;
    for (int i = 1; i <= n; i ++)   s[i] = i;   // 刚开始每个节点是自己的根
    
    string str;
    int x, y;
    while (cin >> str, str != "S")
    {
    
    
        cin >> x >> y;
        if (str == "I") add(x, y);
        else
        {
    
    
            if (find(x) == find(y)) puts("yes");
            else    puts("no");
        }
    }
    
    int res = 1;
    root.insert(find(1));
    for (int i = 2; i <= n; i ++)
    {
    
    
        if (!root.count(find(i)))
        {
    
    
            root.insert(find(i));
            res ++;
        }
    }
    if (res == 1)   puts("The network is connected.");
    else    printf("There are %d components.\n", res);
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ManiacLook/article/details/124356230