(UVA) Forests - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1168

Each person is associated with a structure that contains all the trees that this person heard. In the end, these structures are grouped in order to check how many different structures we have.


import java.io.*;
import java.util.*;

class Main {
    public static void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        int numTests = Integer.parseInt(br.readLine());
        br.readLine(); // blank space
        for (int i = 0; i < numTests; i++) {
            if (i > 0) {
                System.out.println();
            }
           
            String line = br.readLine();
            String[] s = line.split("\\s");
            int numPeople = Integer.parseInt(s[0]);
            int numTrees = Integer.parseInt(s[1]);
           
            HashMap<Integer, HashSet<Integer>> peopleTree = new HashMap<>();
            for (int j = 1; j <= numPeople; j++) {
                peopleTree.put(j, new HashSet<Integer>());
            }
           
            line = br.readLine();
            while (line != null && !line.equals("")) {
                s = line.split("\\s");
                int p = Integer.parseInt(s[0]);
                int t = Integer.parseInt(s[1]);
                peopleTree.get(p).add(t);
                line = br.readLine();
            }
           
            int count = 0;
            HashSet<HashSet<Integer>> hs = new HashSet<>();
            for (int j = 1; j <= numPeople; j++) {
                hs.add(peopleTree.get(j));
            }
           
            System.out.println(hs.size());
        }
                                       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução