【问题标题】:Merging Communities and finding a community by its member合并社区并通过其成员查找社区
【发布时间】:2015-10-05 19:21:07
【问题描述】:

问题陈述

人们在社交网络中相互联系。 Person I 和 Person J 之间的连接表示为 M I J。当属于不同社区的两个人连接时,净效应是 I 和 J 所属的两个社区的合并。

一开始有N个人代表N个社区。假设人 1 和 2 连接,然后连接 2 和 3,那么 1,2 和 3 将属于同一个社区。​​p>

有两种类型的查询:

M I J => 包含人 I 和 J 的社区合并(如果他们属于不同的社区)。

Q I => 打印我所属社区的规模。

我的方法:

我创建了一组空集合。当两个人合并时,我正在检查所有内部集合,如果找到其中任何一个,我会将它们添加到该集合并突破。 如果不是,我正在与这些人一起创造一个新的内在组合。 现在在这个父集合中,我需要比较所有内部集合,如果找到交集,我应该合并两个内部集合,这是我做不到的。

我的方法正确吗?但是这是一个非常迭代的过程,有没有更好的方法来解决呢?

我的代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int nPeople = sc.nextInt();
        int queries = sc.nextInt();
        Set<Set<Integer>> community = new HashSet<Set<Integer>>();
        for(int i = 0 ; i<queries ; i++){
           char query = sc.next().charAt(0);
           if(query == 'Q'){
                int p = sc.nextInt();
                Set<Integer> tmpset = new HashSet<Integer>();

                for( Set<Integer> innerSet : community){
                   for(Integer person : innerSet) {
                       if( person == p ){
                           for(Integer each : innerSet){
                               tmpset.add(each);
                           }
                       }
                   }
                }

                if(tmpset.size()!= 0) {
                    System.out.println(tmpset.size());
                }
                else {
                    System.out.println("1");
                }
            }
            else if(query=='M'){
                int person1 = sc.nextInt();
                int person2 = sc.nextInt();

                int c = 0;

                loop:
                for( Set<Integer> innerSet : community){
                   for(Integer person : innerSet) {
                       if( person == person1 || person == person2){
                           innerSet.add(person1);
                           innerSet.add(person2);
                           c++;
                           break loop;

                       }
                   }
                }

                if(c==0){
                     Set<Integer> tmpset = new HashSet<Integer>();
                     tmpset.add(person1);
                     tmpset.add(person2);
                     community.add(tmpset);
                }
            }
        }


    }
}

我的代码输出:包含集合的集合。

问题链接:https://www.hackerrank.com/challenges/merging-communities

在@Adamski 的帮助下解决了这个问题,使用不相交集数据结构,但仍然不是那么有效的解决方案。

代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int nPeople = sc.nextInt();
        DisJoint comm = new DisJoint(nPeople);
        int queries = sc.nextInt();
        for(int k = 0 ; k<queries ; k++){
            char query = sc.next().charAt(0);
            if(query == 'Q'){
               int person = sc.nextInt(); 
               int personParent = comm.Find(person);
               int community = 0;
               for(int j =1 ; j<nPeople+1 ; j++){
                   int tmpParent = comm.Find(j);
                   if(personParent == tmpParent){
                       community++;
                   }
               }
               System.out.println(community);
            }
            if(query == 'M'){
                int person1 = sc.nextInt();
                int person2 = sc.nextInt();
                comm.Union(person1,person2);
            }
        }

    }
}

 class DisJoint{
    public int Count;
    public int[] Parent;
    public int[] Rank;
    public DisJoint(int count){
        this.Count = count;
        this.Parent = new int[this.Count+1];
        this.Rank = new int[this.Count+1];
        for (int i = 1; i < this.Count+1; i++) {
            this.Parent[i] = i;
            this.Rank[i] = 0;
        }
    }
    public int Find(int i){
        if(i == Parent[i]){
            return Parent[i];
        }
        else{
           int result = Find(Parent[i]);
           Parent[i] = result;
           return result;
        }
    }

    public void  Union(int a, int b){
        if(a>b){
            int tmp = a;
            a = b;
            b = tmp;
        }
        int aroot = this.Find(a);
        int broot = this.Find(b);
        int arank = Rank[aroot];
        int brank = Rank[broot];

        if (aroot == broot){
           return;
        }
        if (arank < brank) {
           this.Parent[aroot] = broot;
         } 
        else if (arank > brank) {
          this.Parent[broot] = aroot;
         }
        else{
          this.Parent[aroot] = broot;
          Rank[broot]++;
        }
    }

}

请测试上述链接中的代码。

【问题讨论】:

    标签: java algorithm data-structures merge set


    【解决方案1】:

    这是通过所有测试用例的解决方案的完整代码。

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Solution {
    static int parent[],rank[],m[];
    static int find(int i)
    {
        if(i==parent[i])
        return i;
       int res=find(parent[i]);
       parent[i]=res;
            return res;
    
    }
    
    static void union(int i,int j)
    {
        int irep=find(i),jrep=find(j);
        if(irep==jrep)
        return;
        if(rank[irep]>rank[jrep])
        {
            parent[jrep]=irep;
            m[irep]+=m[jrep];
        }
        else if(rank[irep]<rank[jrep])
        {
            parent[irep]=jrep;
            m[jrep]+=m[irep];
        }
        else
        {
            parent[jrep]=irep;
            rank[irep]++;
            m[irep]+=m[jrep];
        }
    
    
    
    }
    public static void main(String []args)throws IOException
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt(),q=sc.nextInt();
    parent=new int[n+1];
    rank=new int[n+1];
    m=new int[n+1];
    for(int i=0;i<=n;i++)
        {
        parent[i]=i;
        rank[i]=1;
        m[i]=1;
    
    }
    for(int i=0;i<q;i++)
        {
    
        switch(sc.next().charAt(0))
            {
            case 'Q':
            int c=0;
    
            System.out.println(m[find(sc.nextInt())]);
            break;
            case 'M':
            union(sc.nextInt(),sc.nextInt());
            break;
    
        }
    
    }
    
    }
    
    
    
    }
    

    【讨论】:

      【解决方案2】:

      首先,关于您的代码。这是糟糕的OO设计:

      1. 一切都在一个方法中(您是否考虑过为“Q”和“M”创建单独的方法?)
      2. 所有变量都是该方法的本地变量

      现在,关于解决方案,我采取了另一种方法:

      1. 一个人永远只属于一个社区。所以我有一个“世界”数据结构,可以直接告诉我任何特定人的社区。它可以是一个地图,其中关键是人,社区是价值。我选择了一个列表,其中索引是人,价值是社区。
      2. 一旦你有了它,就很容易找到任何指定人的社区(我有一个特定的方法可以做到这一点)
      3. 一旦你有这种能力找到一个社区,Q'操作就变成了一个给定的(列表的大小,duh)并且与“世界”'M'操作一起也很容易(猜猜看,我有一个特定的方法可以做到就是这样...)

      所以我创建了以下代码(经过测试和工作) 注意:由于问题中的索引是从 1 开始的,所以我用 size == nPeople 定义了“world”,并且没有使用它的 0 索引。

      public class Solution
      {
          // data structure: index is person and value is community
          static List<Integer> world;
      
          // input 
          static int nPeople, queries;
          static Scanner sc = new Scanner(System.in);
      
          public static void main(String[] args)
          {
              /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
              System.out.println("people operations:");
              init();
      
              for (int i = 0; i < queries; i++) {
                  System.out.println("next operation:");
                  char operation = sc.next().charAt(0);
                  switch (operation) {
                  case 'Q':
                      System.out.println(query(sc.nextInt()));
                      break;
                  case 'M':
                      merge(sc.nextInt(), sc.nextInt());
                      System.out.println("done");
                      break;
                  }
              }
          }
      
          // init world
          private static void init()
          {
              nPeople = sc.nextInt();
              queries = sc.nextInt();
              world = new ArrayList<>();
              for (int i = 0 ; i <= nPeople ; i++)  world.add(i);
          }
      
          // get the community of specified person 
          // return size
          private static int query(Integer person)
          {
              return getCommunity(person).size();
          }
      
          // check that the two specified persons do not belong to same community 
          // get the two communities of specified persons 
          // iterate over list of persons of comunity2, 
          // set them to community (value) of person1 
          private static void merge(Integer person1, Integer person2)
          {
              if (world.get(person1).equals(world.get(person2))) return;
      
              List<Integer> community1 = getCommunity(person1);
              List<Integer> community2 = getCommunity(person2);
              if (community1.isEmpty() || community2.isEmpty()) return;
      
              Integer community1Id = world.get(community1.get(0)); 
              for (Integer person : community2) {
                  world.set(person, community1Id);
              }
          }
      
          // returns list of persons (indexes in world) 
          // that belong to community (value) of specified person
          private static List<Integer> getCommunity(Integer person)
          {
              List<Integer> community = new ArrayList<>();
              for (int i = 0 ; i < world.size() ; i++) {
                  if (world.get(i).equals(world.get(person))) {
                      community.add(i);
                  }
              }
              return community;
          }
      }
      

      【讨论】:

        【解决方案3】:

        您是否考虑过使用数据结构来表示不相交的集合?例如这里:http://www.mathblog.dk/disjoint-set-data-structure/

        基本前提是您定义一个类(例如Person)并将您的社区集表示为单个数组。每个Person 都包含一个返回数组的索引,要么指向它自己,要么指向另一个Person

        | Adam | Dave | Fred | Tom | James |
        | 0    | 0    | 1    | 3   | 3     |
        

        在上面的例子中,为了测试 Fred 和 Dave 是否在同一个社区中,你从每个 Person 开始,然后按照图表到根 person;即索引引用自身的人:

        Fred -> Dave -> Adam
        Dave -> Adam
        

        (显然这里有一个优化,在第一次遍历期间,您实际上在到达根之前遇到了 Dave。)

        相比之下,测试 James 和 Fred 是否在同一个社区:

        James -> Tom
        Fred -> Dave -> Adam
        

        人们有不同的根源,因此属于不同的社区。​​p>

        然后,合并社区就是将一个社区的根人员重新指向另一个社区的根。

        推断社区的规模更复杂;我将把它作为练习留给你来解决!

        【讨论】:

        • FWIW,使用路径压缩和秩并集,这种方法每次操作的 O(α(n)),其中 α 是逆阿克曼函数。所以效率极高
        • @NiklasB.:谢谢;我不知道 - 很有趣。
        • @Adamski 用于推断社区的大小,我正在检查 queryPerson 的父级,然后使用计数器检查集合中每个元素的父级,并将计数器的值作为社区大小返回。请检查问题部分,我已添加此代码。
        猜你喜欢
        • 1970-01-01
        • 2012-04-10
        • 2020-01-21
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-25
        • 1970-01-01
        相关资源
        最近更新 更多