欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

1107 Social Clusters (30分)图论求连通分量

程序员文章站 2023-12-23 16:48:40
...

When register on a social network, you are always asked to specify your hobbies in order to find some potential friends with the same hobbies. A social cluster is a set of people who have some of their hobbies in common. You are supposed to find all the clusters.

Input Specification:

Each input file contains one test case. For each test case, the first line contains a positive integer N (≤1000), the total number of people in a social network. Hence the people are numbered from 1 to N. Then N lines follow, each gives the hobby list of a person in the format:

Ki : h​i​​ [1] h​i[2] … h​i[Ki]

where K​i(>0) is the number of hobbies, and h​i​​ [j] is the index of the j-th hobby, which is an integer in [1, 1000].

Output Specification:

For each case, print in one line the total number of clusters in the network. Then in the second line, print the numbers of people in the clusters in non-increasing order. The numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4
Sample Output:
3
4 3 1

题目大意:每个人都有爱好,如果两个人爱好相同就属于相同社交圈,求n个人一共形成多少个社交圈,并输出每个社交圈的人数

分析:将前面人的编号按照自己爱好下标存在vectorhobby【1000】中,之后的人都判断是否这个爱好下标对应的人数>0,如果大于0,说明这个爱好是公共爱好,接着就遍历这个向量vectorhobby[i],为这个爱好中的每个人建立一条边存放在vectorpersons【1000】中,之后就是求连通分量了。

代码:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int>hobby[1001];
vector<int>person[1001];
vector<int>res;
bool flag[1001]={false};
void dfs(int root,int &sum){
	sum++;
	flag[root]=true;
	for(int i=0;i<person[root].size();++i){
		if(flag[person[root][i]]==false)
		dfs(person[root][i],sum);
	}
}
int cmp(int a,int b){
	return a>b;
}
int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;++i){
		int k;
		scanf("%d: ",&k);
		for(int j=0,t;j<k;++j){
			scanf("%d",&t);
			if(hobby[t].size()>0)
			{
				for(int z=0;z<hobby[t].size();++z){
					int d=hobby[t][z];
					person[i].push_back(d);
					person[d].push_back(i);
				}
			}
			hobby[t].push_back(i);
		}
	}
	for(int i=1;i<=n;++i){
		int sum=0;
		if(flag[i]==false){
			dfs(i,sum);
			res.push_back(sum);
		}
		
	}
	sort(res.begin(),res.end(),cmp);
	cout<<res.size()<<endl;
	for(int i=0;i<res.size();++i){
		if(i)
		cout<<" ";
		cout<<res[i];
	}
	return 0;
}

运行截图:
1107 Social Clusters (30分)图论求连通分量

相关标签: PAT 算法

上一篇:

下一篇: