洛谷P1892 团伙

SDSC Day 3的题.(的弱化版
这题算是一个并查集的板子题。
答题思路:
对每个点i建立i+n这个点
是朋友进入一个并查集
不是的话把x,y+n x+n,y这两个并查集连接起来
很简单的思路。
C++代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
#include <string>
#define INF 0x3f3f3f3f
#define inf 0x3f
#define maxn 200001
#define maxm 10001
#define ll long long
using namespace std;
int n, m, fa[maxn], x, y;
char p;
void clear()
{
    for (int i = 1; i <= n; i++)
    {
        fa[i] = i;
    }
}
int find(int x)
{
    if (fa[x] == x)
        return x;
    return fa[x] = find(fa[x]);
}
void merge(int x, int y)
{
    int xx = find(x);
    int yy = find(y);
    if (xx == yy)
        return;
    fa[xx] = yy;
}
int ener[201010];

int main()
{
    memset(ener, 0, sizeof(ener));
    cin >> n >> m;
    clear();
    for (int i = 1; i <= m; i++)
    {
        std::string str;
        cin >> str >> x >> y;
        p = str[0];
        if (p == 'F')
            merge(x, y);
        else
        {
            if (ener[x] == 0)
            {
                ener[x] = find(y);
            }
            else
                merge(y, ener[x]);
            if (ener[y] == 0)
                ener[y] = find(x);
            else
                merge(x, ener[y]);
        }
    }
    int ans = 0;
    int sum[maxn];
    memset(sum, 0, sizeof(sum));
    for (int i = 1; i <= n; i++)
    {
        if (find(i) != 0)
            sum[find(i)]++;
    }
    for (int i = 1; i <= n; i++)
    {
        if (sum[i])
            ans++;
    }
    cout << ans;
    return 0;
}

 

posted @ 2018-08-06 21:20  kenlig  阅读(174)  评论(0编辑  收藏  举报