Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Queue;
- import java.util.Scanner;
- import java.util.Set;
- /**
- * All index start from 0, ... - 1 when getting input
- * use crates
- *
- *
- * @author reobj_
- *
- */
- public class Main {
- public static void main(String[] args) {
- Scanner consoleIn = new Scanner(System.in);
- int amountCows = consoleIn.nextInt();
- int amountGroups = consoleIn.nextInt();
- // int ans = 0;
- Set<Integer> invites = new HashSet<Integer>();
- invites.add(1);
- Set[] groups = new HashSet[amountGroups];
- for(int i = 0; i < amountGroups; i++) {
- groups[i] = new HashSet<Integer>();
- }
- // Input
- for(int i = 0; i < amountGroups; i++) {
- int amount = consoleIn.nextInt(); // Per group
- for(int j = 0; j < amount; j++) {
- int in = consoleIn.nextInt();
- groups[i].add(in);
- }
- }
- // Buffer for invitation, if this one is cleared means
- // you got the minimum amount that needs to be invited
- Queue<Integer> toCheck = new LinkedList<Integer>();
- toCheck.add(1); // Default invited cow
- while(!toCheck.isEmpty()) {
- int current = toCheck.remove(); // Process next element in side queue
- invites.add(current); // Invite, which's checked
- // ans++;
- for(int j = 0; j < amountGroups; j++) {
- if(groups[j].size() == 0) continue;
- groups[j].remove(current); // Take out i, like 1 (first time)
- // Only one cow's left, must be invited
- if(groups[j].size() == 1) {
- // Pop out the (last) element in the set
- toCheck.add( (Integer) groups[j].iterator().next() );
- }
- }
- }
- System.out.println( invites.size() );
- // System.out.println(ans);
- consoleIn.close();
- }
- }
Add Comment
Please, Sign In to add comment