Given two sets of integers, the similarity of the sets is defined to be Nc/Nt×100%, where Nc is the number of distinct common numbers shared by the two sets, and Nt is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.
Input Specification:
Each input file contains one test case. Each case first gives a positive integer N (≤50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (≤104) and followed by M integers in the range [0,109]. After the input of sets, a positive integer K (≤2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.
Output Specification:
For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.
Sample Input:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3
Sample Output:
50.0%
33.3%
解题思路:
题目大意:输入某些集合,求指定两个集合中的并集:交集。
先将所有集合元素存储至二维数组中,求并集时,不仅要保证和指定集合有重合,还要保证和自身集合无重合。交集只需把两集合元素都放入同一set中即可。
注意局部变量的使用和输出的格式。
java代码:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int [][]arr = new int[n][];
for(int i = 0; i < n;i++) {
String[] split = br.readLine().split(" ");
int m = Integer.parseInt(split[0]);
arr[i] = new int[m];
for(int j = 0; j < m;j++) {
arr[i][j] = Integer.parseInt(split[j + 1]);
}
}
int count = Integer.parseInt(br.readLine());
StringBuilder builder = new StringBuilder();
for(int i = 0; i < count;i++) {
int ans = 0;
String[] split = br.readLine().split(" ");
int a = Integer.parseInt(split[0]) - 1;
int b = Integer.parseInt(split[1]) - 1;
Set<Integer> set = new HashSet<>();
Set<Integer> set1 = new HashSet<>();
for(int j = 0; j < arr[a].length;j++) {
set.add(arr[a][j]);
}
for(int j = 0; j < arr[b].length;j++) {
boolean key = set.contains(arr[b][j]);
boolean key1 = set1.contains(arr[b][j]);
if(key && !key1) {
ans++;
}
set1.add(arr[b][j]);
}
set.addAll(set1);
String str = String.format("%.3f",(ans * 1.0) / set.size());
builder.append(String.format("%.1f%%\n",Float.parseFloat(str) * 100));
// System.out.printf("%.1f%%\n",Float.parseFloat(str) * 100);
}
System.out.print(builder.toString().trim());
}
}