NBUT - 1451Elise

xiaoxiao2021-02-28  85

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.

Input 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. Output For each case, you should output the least cost. Sample Input 5 1 kill 1 kill 2 sleep sing 2 sing fart 1 fart Sample Output 1 Hint In this case, the spider 1 or 2 just need to learn to sleep or sing or fart. So it's 1. 题意:有n个蜘蛛,蜘蛛之间如果没有相同的兴趣,就会打架,相同的兴趣可以直接或间接联系得到 看题用并查集,但是由元素中成分合并某些元素,先用map把字符串赋值,若两元素有成分的值相等则合并两元素。 代码: #include<map> #include<cmath> #include<vector> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int n; int father[110]; void intl() { for(int i=1;i<=n;i++) father[i]=i; } int find(int x) { if(x!=father[x]) father[x]=find(father[x]); return father[x]; } void unin(int x,int y) { int nx=find(x); int ny=find(y); if(nx!=ny) father[nx]=ny; } int main() { while(~scanf("%d",&n)) { intl(); map<string,int>mat;//给每门兴趣编号 vector<int >G[110];//储存第i个蜘蛛的兴趣 mat.clear(); int cnt=0;int num=1; for(int i=1;i<=n;i++) { int m; 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]);//放入G[i]中 } } if(cnt==n) printf("%d\n",cnt); else {//遍历每个蜘蛛 有相同的成分则合并 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]) unin(i,k); int ans=0; for(int i=1;i<=n;i++) if(father[i]==i) ans++; printf("%d\n",ans-1); } } }
转载请注明原文地址: https://www.6miu.com/read-19322.html

最新回复(0)