题解 CF277A 【Learning Languages】

Topic Portal
to dfs out of the problem solution.

And put it in the other solution to a problem, as each language, everyone is treated as a node, a person to master a language can be represented as a node node on behalf of these individuals with the language even on behalf of an edge, just China Unicom will everyone can.

Then points about class:

  1. If the language is not full of people, then obviously you need to connect the total number of edges (everyone to learn the same language).
  2. If there will be the language of people, and even then only in communication indicates the total number of people block node minus one side (into the human language and would not be the language, supra, it will not be the language of the language simply attaching them as a tree can, it is a combined total block of communication nodes minus a number of al).

Then only need to obtain dfs represents the total number of people communication block node, then according to the above-described classification operation

Code:

#include<bits/stdc++.h>
using namespace std;
int n,m,i,j,x,y,s;
vector<int>k[201];//邻接表存图,1-100号节点表示人,101-200号节点表示语言
bool b[201],bb;//b数组代表该节点是否被遍历过,bb代表是否有会语言的人
void dfs(int x)
{
    b[x]=1;//将当前节点标为已遍历
    int i;
    for(i=0;i<k[x].size();i++)if(!b[k[x][i]])dfs(k[x][i]);//遍历与当前节点相连的其他未遍历的节点
}
int main()
{
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&x);
        while(x--)
        {
            scanf("%d",&y);
            k[i].push_back(100+y);//连边
            k[100+y].push_back(i);//连边
        }
    }
    for(i=1;i<=n;i++)
    {
        if(!b[i]){if(k[i].size()>=1)bb=1;s++;dfs(i);}//如果当前节点还没被遍历过,就将连通块数加一,在遍历该节点
    }
    if(bb)s--;//如果有会语言的人,就将答案减一
    printf("%d",s);
}

Guess you like

Origin www.cnblogs.com/pzc2004/p/11600851.html