【PAT甲級】並查集專題複習

博主開始複習PAT甲級了,會做多個複習的專題,會解釋需要注意的基本概念和題庫相關的滿分代碼展示。

目的:通過多刷題,多總結回顧,讓自己在方法層面還是代碼細節達到熟練寫出的程度。

形式:思維導圖+代碼點評

提示:每個人的基礎不同,這裏不做普適性的建議。我出的專題重點是串聯知識,僅供參考。


Dijkstra專題近三年考察情況:19年3月第三題

1158之前寫過了:https://blog.csdn.net/allisonshing/article/details/104361040

放出來的都是我優化的liuchuo的源代碼,沒放出來的就按照她的寫法就行。

1107. Social Clusters (30)

https://pintia.cn/problem-sets/994805342720868352/problems/994805361586847744

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> father, isRoot;
int cmp1(int a, int b){return a > b;}
//我改了下面兩個函數,liuchuo版的是非遞歸的
int findFather(int x) {
    return x == father[x]? x : (father[x]=findFather(father[x]));
}
void Union(int a, int b) {
    father[findFather(a)]=findFather(b);
}
int main() {
    int n, k, t, cnt = 0;
    int course[1001] = {0};
    scanf("%d", &n);
    father.resize(n + 1);
    isRoot.resize(n + 1);
    for(int i = 1; i <= n; i++)
        father[i] = i;
    for(int i = 1; i <= n; i++) {
        scanf("%d:", &k);
        for(int j = 0; j < k; j++) {
            scanf("%d", &t);
            if(course[t] == 0)
                course[t] = i;
            Union(i, findFather(course[t]));
        }
    }
    for(int i = 1; i <= n; i++)
        isRoot[findFather(i)]++;
    for(int i = 1; i <= n; i++) {
        if(isRoot[i] != 0) cnt++;
    }
    printf("%d\n", cnt);
    sort(isRoot.begin(), isRoot.end(), cmp1);
    for(int i = 0; i < cnt; i++) {
        printf("%d", isRoot[i]);
        if(i != cnt - 1) printf(" ");
    }
    return 0;
}

1114 Family Property (25分)

https://pintia.cn/problem-sets/994805342720868352/problems/994805356599820288

1118 Birds in Forest (25分)

https://pintia.cn/problem-sets/994805342720868352/problems/994805354108403712

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章