【LeetCode Weekly Contest 26 Q3】Friend Circles

【题目链接】:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/friend-circles/

【题意】

告诉你任意两个人是不是朋友.
问你最后有多少个连通块;

【题解】

裸并查集。

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define ps push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%lld",&x)
#define ref(x) scanf("%lf",&x)

typedef pair<int, int> pii;
typedef pair<LL, LL> pll;

const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 250;

int f[N];
bool bo[N];

int ff(int x)
{
    if (f[x] == x) return x;
    else
        return f[x] = ff(f[x]);
}

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        memset(bo, false, sizeof bo);
        int n = M.size();
        rep1(i, 0, n - 1)
            f[i] = i;
        rep1(i,0,n-1)
            rep1(j, 0, n - 1)
            if (M[i][j])
            {
                int r1 = ff(i), r2 = ff(j);
                if (r1 != r2)
                {
                    f[r1] = r2;
                }
            }
        int cnt = 0;
        rep1(i, 0, n - 1)
        {
            int x = ff(i);
            if (!bo[x])
            {
                bo[x] = true;
                cnt++;
            }
        }
        return cnt;
    }
};
posted @ 2017-10-04 18:45  AWCXV  阅读(98)  评论(0编辑  收藏  举报