【Codeforces Round #170 Div. 1】 227A Learning Languages

来源:互联网 发布:网络直播策划方案 编辑:程序博客网 时间:2024/06/04 18:33

Description
The “BerCorp” company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).


【题目大意】
n个员工,m种语言,每个员工会k种语言,问总共还要学习多少语言,可以让每两个员工可以直接或者间接交流。


【题目分析】
很简单的一道题目。
首先,我们把能直接或间接交流的员工合并到一个连通块中(显然应该使用并查集)。然后统计一下连通块的个数。我们设想两个连通块a和b,我们只需要让b中的一个人学习a中任何一个人会的语言,就可以让这两个联通块联通起来(就相当于把两个连通块联通起来了)。这样cnt个连通块,我们只需要连cnt-1条边就可以了。那么就是要学cnt-1个语言。
但是作为Div.1 A。出题人就是丧心病狂,假设你遇到了一群婴儿(什么都不会说),那你只能教会他们每个人一种语言,这就是坑。如果所有人都不会说任何语言,就要输出cnt了。
(提刀战出题人)


【代码】

#include<iostream>#include<cstdio>#include<vector>#define fo(i,j,k) for(i=j;i<=k;i++)using namespace std;bool b[101];int father[101],t[101],ans;vector <int> v[101];int find(int x){    if(x==father[x]) return x;    return father[x]=find(father[x]);}int main(){    int i,j,k,n,m,x;    scanf("%d%d",&n,&m);    fo(i,1,100) father[i]=i;    fo(i,1,n)    {        scanf("%d",&t[i]);        fo(j,1,t[i])        {            scanf("%d",&x);            v[x].push_back(i);        }    }    fo(i,1,n) if(t[i]) break;    if(i>n)     {        printf("%d\n",n);        return 0;    }    fo(i,1,m)     {        x=v[i].size()-2;        fo(j,0,x)        {            int r1=find(v[i][j]);            int r2=find(v[i][j+1]);            if(r1!=r2) father[r1]=r2;        }    }    fo(i,1,n)    {        if(!b[find(i)]) ans++;        b[find(i)]=1;    }    printf("%d\n",ans-1);    return 0;}
0 0
原创粉丝点击