標籤:style blog http 2014 os 代碼
題目:
連結:點擊開啟連結
題意:
有N個積木,1到N編號。進行一些操作P次,M:X Y把X積木放到Y的上面,如果X和Y相等請忽略。C:X 計算X積木下的積木數目。
思路:
帶權並查集的題目,定義數組sum[i]表示i積木下面積木的數目。遇到操作M,就把X和Y合并到同一個集合中。我們視每個結點為1個 Pile,其中rank[i]就表示每個Pile處的積木的個數,Initially, there are N piles, and each pile contains one block.所以,rank[]的初始值應該是1。
代碼:
#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int N = 30030;int root[N];int sum[N],rank[N];int q;int findset(int x){ if(x == root[x]) return x; int temp = findset(root[x]); sum[x] += sum[root[x]]; return root[x] = temp;}void mergeset(int x,int y){ int fx = findset(x); int fy = findset(y); if(fx == fy) return ; root[fx] = fy; sum[fx] += rank[fy];//sum rank[fy] += rank[fx];//每進行一次M操作,rank的值都要更新。}void init(){ for(int i=0; i<=30000; i++) { root[i] = i; rank[i] = 1; sum[i] = 0; }}int main(){ //freopen("input.txt","r",stdin); char ch; int x,y,z; while(scanf("%d",&q) != EOF) { init(); getchar(); while(q--) { scanf("%c",&ch); getchar(); if(ch == 'M') { scanf("%d%d",&x,&y); mergeset(x,y); } else { scanf("%d",&z); findset(z); printf("%d\n",sum[z]); } getchar(); } } return 0;}
---------------------------------------------------------------
戰鬥,從不退縮;奮鬥,永不停歇~~~~~~~~