-
[1451] Elise
- 时间限制: 1000 ms 内存限制: 65535 K
- 问题描述
-
Elise is the Spider Queen . She has a skill, Spider Form (蜘蛛形态) .
When she transformed to the spider, there will be some small spiders around her.
But she has a problem - the small spiders will have infighting because of less common interest. So Elise decided to train their interesting.
At least, they must have common interest no matter directly or indirectly.
How to train theirs interest in least cost? We assume that train a interest for a spider cost 1 strength and there are at most 100 interests in total.
- 输入
-
This problem contains several cases.
The first line of each case is an integer N (1 ≤ N ≤ 100), indicates the number of spiders.
Then N lines followed.
The ith line contains an integer Ti (0 ≤ Ti ≤ 100) that indicates the number of this spider's interest and Ti strings indicate the interests. You can assume there are only lowercase letters in the strings and no longer than 20. - 输出
-
For each case, you should output the least cost.
- 样例输入
-
5 1 kill 1 kill 2 sleep sing 2 sing fart 1 fart
- 样例输出
-
1
- 提示
-
In this case, the spider 1 or 2 just need to learn to sleep or sing or fart. So it's 1.
- 来源
-
XadillaX
题意: 有很多个小蜘蛛,如果小蜘蛛没有共同的兴趣就会内讧,让一个小蜘蛛培养一个兴趣需要一个单位的花费,为了让小蜘蛛们不内讧,需要给部分蜘蛛培养兴趣,求最少花费?
分析:属于集合问题,很自然的就想到了并查集,难点在于是字符串的并查集而不是数字,所有需要用到map,数据比较小,可以直接暴力。注意:蜘蛛的兴趣数可能为0。
/* Author: ZXPxx Memory: 244 KB Time: 296 MS Language: G++ Result: Accepted */ #include<cstdio> #include<string> #include<cstring> #include<vector> #include<map> using namespace std; const int mx=100+5; int p[mx],n,m; int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } void Union(int a,int b) { int x=find(a); int y=find(b); if(x!=y) { p[x]=y; } } int main() { while(~scanf("%d",&n)) { for(int i=1; i<=n; i++) p[i]=i; //初始化并查集 map<string,int> mat; vector<int> G[mx]; mat.clear(); int num=1,cnt=0; //cnt记录 兴趣为0的蜘蛛数 for(int i=1; i<=n; i++) { scanf("%d",&m); if(m==0) cnt++; G[i].clear(); //清空vector char s[25]; for(int j=1; j<=m; j++) { scanf("%s",s); if(!mat[s]) mat[s]=num++; //给兴趣编号 G[i].push_back(mat[s]); } } if(cnt==n) { printf("%d\n",cnt); //如果全为0,则每个小蜘蛛都要学习 同一种兴趣 continue; } for(int i=1; i<=n; i++) for(int j=0; j<G[i].size(); j++) for(int k=i+1; k<=n; k++) for(int l=0; l<G[k].size(); l++) if(G[i][j]==G[k][l]) Union(i,k); //兴趣相同,合并 int ans=0; for(int i=1; i<=n; i++) { if(p[i]==i) ans++; } printf("%d\n",ans-1); } return 0; }
NBUT 1451 Elise (map +并查集)
最新推荐文章于 2015-11-25 11:14:48 发布