PatA1107 Social Clusters 社交团体 2020/9/9

问题描述

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:K​i: h​i[1] h​​i[2] ... h​i[K​i]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.

解决方法

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 1001;
//并查集
int ufs[maxn] = {0};
//确定集合内的关系
int course[maxn] = {0};
//确定集合的个数
int isRoot[maxn] = {0};
//由大到小的比较函数
bool cmp(int a, int b)
{
  return a > b;
}
//初始化并查集
void initUfs(int n)
{
  for (int i = 1; i <= n; i++)
  {
    ufs[i] = i;
  }
}
//查询--路径压缩提升之后的查询效率
int findFather(int x)
{
  int temp = x;
  while (ufs[x] != x)
  {
    x = ufs[x];
  }
  while (temp != ufs[temp])
  {
    int y = temp;
    temp = ufs[temp];
    ufs[y] = x;
  }
  return x;
}
// Union 并
int Union(int x, int y)
{
  int root1 = findFather(x);
  int root2 = findFather(y);
  if (root1 == root2)
  {
    return 0;
  }
  else
  {
    ufs[root1] = root2;
    return 1;
  }
}
int main(void)
{
  int num = 0, res = 0;
  scanf("%d", &num);
  initUfs(num);
  for (int i = 1; i <= num; i++)
  {
    int activity = 0;
    int h = 0;
    scanf("%d:", &activity);
    for (int j = 1; j <= activity; j++)
    {
      scanf("%d", &h);
      /*
        利用关系合并集合
      */
      if (course[h] == 0)
      {
        course[h] = i;
      }
      Union(i, findFather(course[h]));
    }
  }
  for (int k = 1; k <= num; k++)
  {
    //记录集合中的个数
    isRoot[findFather(k)]++;
    if (ufs[k] == k)
    {
      res++;
    }
  }
  sort(isRoot + 1, isRoot + num + 1, cmp);
  printf("%d\n", res);
  for (int k = 1; k <= res; k++)
  {
    printf("%d", isRoot[k]);
    if (k != res)
      printf(" ");
  }
  return 0;
}

基本策略

  • 并查集的简单应用

结果展示

  • PatA1107.png

你可能感兴趣的:(PatA1107 Social Clusters 社交团体 2020/9/9)