1107. Social Clusters (30)

来源:互联网 发布:java逐个读取单词 编辑:程序博客网 时间:2024/05/17 22:30

最近偏爱bfs,抛弃了dfs
这道题目用了两个二维数组存放信息。
一起bfs。
为了显示出区别,所以用负数表示人的编码
用正数表示爱好
AC代码:

#include <bits/stdc++.h>using namespace std;bool cmp(const int a, const int b){    return a > b; }int main(void){    int n;    cin >> n;    vector<vector<int> > peo(n);    vector<vector<int> > larr(1001);    vector<bool> test(n);    vector<bool> test1(1001);     int i, j, t;    int temp;    for (i = 0; i < n; i++)    {        scanf("%d: ", &t);        for (j = 0; j < t; j++)        {            scanf("%d", &temp);            larr[temp].push_back(-i);            peo[i].push_back(temp);        }    }    vector<int> res;    queue<int> sup;    for (i = 0; i < n; i++)    {        int jt = 0, fron;        if (test[i]) continue;        else        {            jt++;            test[i] = true;            for (j = 0; j < peo[i].size(); j++)            {                if (test1[peo[i][j]]) continue;                sup.push(peo[i][j]);                test1[peo[i][j]] = true;            }            while (!sup.empty())            {                fron= sup.front();                sup.pop();                if (fron <= 0)                {                    fron = -fron;                    if (!test[fron])                    {                        jt++;                        test[fron] = true;                        for (j = 0; j < peo[fron].size(); j++)                        {                            if (test1[peo[fron][j]]) continue;                            sup.push(peo[fron][j]);                            test1[peo[fron][j]] = true;                        }                    }                }                else                {                    for (j = 0; j < larr[fron].size(); j++)                    {                        if (test[-larr[fron][j]]) continue;                        sup.push(larr[fron][j]);                    }                }            }        }        res.push_back(jt);    }    sort(res.begin(), res.end(), cmp);    cout << res.size() << endl;    for (i = 0; i < res.size() - 1; i++)    {        cout << res[i] << " ";    }    cout << res[i];}