栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1063 Set Similarity (25 分) java 题解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1063 Set Similarity (25 分) java 题解

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 set = new HashSet<>();
			Set 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());
	}
}
PTA提交截图:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/274669.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号