题目解析
给定n个集合
再给定k组 要进行计算相似度的两个集合
求出
解题思路
set将每个集合弄成不重复的
然后 一个一个去填充到res中
两个集合相同的个数 = 两个集合的个数 - 两个集合合并之后不同的个数
答案就是
注: java 会T 数据量有亿点大
代码
暴力
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int n = sc.nextInt();
TreeSet<Integer> shu[] = new TreeSet[n + 10];
for (int i = 1; i <= n; i++)
{
int cnt = sc.nextInt();
shu[i] = new TreeSet<Integer>();
while (cnt-- > 0)
{
int x = sc.nextInt();
shu[i].add(x);
}
}
int k = sc.nextInt();
TreeSet<Integer> res = new TreeSet<Integer>();
while (k-- > 0)
{
int a = sc.nextInt();
int b = sc.nextInt();
res.clear();
for (int i : shu[a])
res.add(i);
for (int i : shu[b])
res.add(i);
out.printf("%.2f%%\n", (shu[a].size() + shu[b].size() - res.size()) * 100.0 / res.size());
}
out.flush();
out.close();
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
}
Set 的 addAll函数
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int n = sc.nextInt();
TreeSet<Integer> shu[] = new TreeSet[n + 10];
for (int i = 1; i <= n; i++)
{
int cnt = sc.nextInt();
shu[i] = new TreeSet<Integer>();
while (cnt-- > 0)
{
int x = sc.nextInt();
shu[i].add(x);
}
}
int k = sc.nextInt();
TreeSet<Integer> res = new TreeSet<Integer>();
while (k-- > 0)
{
int a = sc.nextInt();
int b = sc.nextInt();
res.clear();
res.addAll(shu[a]);
res.addAll(shu[b]);
out.printf("%.2f%%\n", (shu[a].size() + shu[b].size() - res.size()) * 100.0 / res.size());
}
out.flush();
out.close();
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
}
c++
#include <cstdio>
#include <unordered_set>
using namespace std;
const int N = 50;
unordered_set<int> shu[N + 10];
unordered_set<int> res;
int main()
{
int n; scanf("%d", &n);
for(int i = 1; i <= n; i ++)
{
int cnt; scanf("%d", &cnt);
while(cnt -- > 0)
{
int x; scanf("%d", &x);
shu[i].insert(x);
}
}
int k; scanf("%d", &k);
while(k -- > 0)
{
int a, b; scanf("%d%d", &a, &b);
res.clear();
for(int i : shu[a]) res.insert(i);
for(int i : shu[b]) res.insert(i);
printf("%.2f%%\n", (shu[a].size() + shu[b].size() - res.size()) * 100.0 / res.size());
}
return 0;
}