A group of N people has some distinct integer ratings 'R' and a consistency factor 'C'. People who frequently participate have consistency factor 1
and those who rarely participate have a consistency factor 0
People create groups by following all these conditions:
1. Ri, Rj are ratings of two-person. If Ri is divisible by Rj, jth person joins ith person's group.
2.Consistency factor of teammates in a group must be the same.
3.No Group must be a proper subset of other groups.
4.A person may be a member of more than one group.
Your task is to find the numbers of groups created.
Example:
Input: 1
5
8 6 2 3 4
1 1 1 0 1
Output: 3
Approach
Java
import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;public class RatedGroups {public static void main(String args[]) throws Exception {int n = 5;int arr[] = { 8, 6, 2, 3, 4 };int arr2[] = { 1, 1, 1, 0, 1 };int freqo[] = new int[10001];int freqz[] = new int[10001];boolean visitedo[] = new boolean[10001];boolean visitedz[] = new boolean[10001];HashSet<Integer> setone = new HashSet<Integer>();HashSet<Integer> setzero = new HashSet<Integer>();ArrayList<Integer> one = new ArrayList<Integer>();ArrayList<Integer> zero = new ArrayList<Integer>();int temp = 0;for (int i = 0; i < n; i++) {temp = arr2[i];if (temp == 1) {one.add(arr[i]);// storing in list onefreqo[arr[i]]++; // increasing the frequecnysetone.add(arr[i]);// adding to set so that we can find it faster}else {zero.add(arr[i]);// storing in list zerofreqz[arr[i]]++; // increasing the frequencysetzero.add(arr[i]);// so we can find it faster}}Collections.sort(one, Collections.reverseOrder());Collections.sort(zero, Collections.reverseOrder());int count = 0;// solving the question for consistency = 1for (Integer i : one) {if (visitedo[i])continue;visitedo[i] = true;count += freqo[i];for (int j = 1; j * j <= i; j++) {if (i % j == 0) {if (setone.contains(j))visitedo[j] = true;if (i / j != j && setone.contains(i / j))visitedo[i / j] = true;}}}// solving the question for consistency = 1for (Integer i : zero) {if (visitedz[i])continue;visitedz[i] = true;count += freqz[i];for (int j = 1; j * j <= i; j++) {if (i % j == 0) {if (setzero.contains(j))visitedz[j] = true;if (i / j != j && setzero.contains(i / j))visitedz[i / j] = true;}}}System.out.println(count);}}
No comments:
Post a Comment