PAT A1063

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805409175420928

我的思路是找总数,把两个集合载入另一个集合中,然后载入前的两个集合的长度减去载入后合并的集合的长度,就是相同的集合个数。但是这样做超时了。

#include <cstdio>
#include <set>
using namespace std;
set<int> a[2010], b;
int main(){
	int n, m, num;
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%d", &m);
		for(int j = 0; j < m; j++){
			scanf("%d", &num);
			a[i].insert(num);
		}
	}
	int k;
	scanf("%d", &k);
	int id1, id2;
	for(int i = 0; i < k; i++){
		scanf("%d%d", &id1, &id2);
		for(set<int>::iterator it = a[--id1].begin(); it != a[id1].end(); it++)
			b.insert(*it);
		for(set<int>::iterator it = a[--id2].begin(); it != a[id2].end(); it++)
			b.insert(*it);
		printf("%.1f%%\n", 100.0 * (a[id1].size() + a[id2].size() - b.size()) / b.size());
		b.clear();
	}
	return 0;
}

参照算法笔记上的思路,遍历其中一个,在另一个集合中查找,有就common++;没有就total++;

#include <cstdio>
#include <set>
using namespace std;
set<int> a[2010];
int main(){
	int n, m, num;
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		scanf("%d", &m);
		for(int j = 0; j < m; j++){
			scanf("%d", &num);
			a[i].insert(num);
		}
	}
	int k;
	scanf("%d", &k);
	int id1, id2;
	for(int i = 0; i < k; i++){
		scanf("%d%d", &id1, &id2);
		int total, common = 0;
		total = a[--id2].size();
		for(set<int>::iterator it = a[--id1].begin(); it != a[id1].end(); it++){
			if(a[id2].find(*it) != a[id2].end())
				common++;
			else
				total++;
		}
		printf("%.1f%%\n", 100.0 * common / total);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值