騰訊9.6筆試

young_Tao發表於2020-09-09

直接給出程式碼:

/*
50 5
2 1 2
5 10 11 12 13 14
2 0 1
2 49 2
4 6 7 8 2
 */
#include<bits/stdc++.h>

using namespace std;

vector<vector<int>> data;
set<int> s;

int main()
{
    int n , m;
    cin >> n >> m;

    for(int i = 0; i < m; i++)
    {
        int x;
        cin >> x;
        vector<int> te;
        for(int j = 0; j < x; j++)
        {
            int temp;
            cin >> temp;
            te.push_back(temp);
        }
        data.push_back(te);
    }

    s.insert(0);

    for(set<int>::iterator it = s.begin(); it!= s.end(); it++)
    {
        int k = *it;
        for(int i = 0; i < m; i++)
        {
            int flag = 0;
            for(int j = 0; j < data[i].size(); j++)
            {
                if(k == data[i][j])
                {
                    flag = 1;
                    break;
                }
            }
            if(flag == 1) {
                for (int j = 0; j < data[i].size(); j++) {
                    s.insert(data[i][j]);
                }
            }
        }
    }

    cout << s.size();

    return 0;
}

/*
#include<bits/stdc++.h>

using namespace std;

vector<int> father(100010, 0);

int findfather(int a)
{
    int x = a;
    while(x != father[x])
    {
        x = father[x];
    }

    while(a != father[a])
    {
        int t = father[a];
        father[a] = x;
        a = t;
    }

    return x;
}

int f_union(int a, int b)
{
    int fa = findfather(a);
    int fb = findfather(b);
    if(fa != fb)
    {
        father[fa] = fb;
    }
}

int main()
{
    int n , m;
    cin >> n >> m;

    //vector<int> father(n, 0);
    for(int i = 0; i < n; i++)
    {
        father[i] = i;
    }

    for(int i = 0; i < m; i++)
    {
        int x, first;
        cin >> x >> first;
        for(int j = 1; j < x; j++)
        {
            int last;
            cin >> last;
            f_union(first, last);
        }
    }

    int f0father = findfather(0);
    int res = 1;
    for(int i = 1; i < n; i++)
    {
        if(findfather(i) == f0father)
        {
            res++;
        }
    }

    cout << res;

    return 0;
}

 */

過了80%,後來在牛客網上看大家討論,說下面出現的ID會超過人數限制,即會有無效ID,那麼這裡可以遍歷上方的set,去掉無效的ID,再求剩下的ID數。

相關文章