1. 程式人生 > 其它 >1063 Set Similarity (25point(s))(STL中set的風花雪月...

1063 Set Similarity (25point(s))(STL中set的風花雪月...

技術標籤:PAT甲級# set資料結構stlset演算法

題目連結

what

容易超時,給的時間只能遍歷一次

不信?熱乎的炮灰…

using namespace std;
#include<bits/stdc++.h>
set<int>store[51];
int N, M, n, a, p, q;
int  main() {
	cin >> N;
	for (int i = 1; i <= N; i++) {
		cin >> n;
		for (int j = 0; j < n; j++) {
			cin >> a;
store[i].insert(a); } } cin >> M; for (int i = 0; i < M; i++) { cin >> p >> q; set<int>intersection,convergence; set_intersection(store[p].begin(), store[p].end(), store[q].begin(), store[q].end(), inserter(intersection, intersection.begin())); set_union(store[
p].begin(), store[p].end(), store[q].begin(), store[q].end(), inserter(convergence, convergence.begin())); cout << fixed << setprecision(1) << intersection.size()*1.0 / convergence.size() * 100 << "%" << endl; } return 0; }

方法一

erase(),返回true \false

using namespace
std; #include <iostream> #include <iomanip> #include<set> set<int>store[51], query; int N, M, n, a, p, q; int main() { cin >> N; for (int i = 1; i <= N; i++) { cin >> n; for (int j = 0; j < n; j++) { cin >> a; store[i].insert(a); } } cin >> M; for (int i = 0; i < M; i++) { int cnt = 0; cin >> p >> q; query = store[q]; int total= store[q].size(); auto pointer = store[p].begin(); for (pointer; pointer != store[p].end(); pointer++) { if (query.erase(*pointer) == false)total++; else cnt++; } cout << fixed << setprecision(1) << cnt*1.0/total* 100.0 << "%" << endl; } return 0; }

方法二

find() ,返回給定值的迭代器,如果沒找到則返回end()。

using namespace std;
#include <iostream>
#include <iomanip>
#include<set>
set<int>store[51];
int N, M,n,a,p,q;
int  main() {
	cin >> N;
	for (int i = 1; i <= N; i++) {
		cin >> n;
		for (int j = 0; j < n; j++) {
			cin >> a;
			store[i].insert(a);
		}
	}
	cin >> M;
	for (int i = 0; i < M; i++) {
		double total= store[q].size();
		int cnt = 0;
		cin >> p >> q;
		auto pointer = store[p].begin();
		for (pointer; pointer != store[p].end(); pointer++) {
			if (store[q].find(*pointer) != store[q].end())cnt++;
			else total++;
		}
		cout << fixed << setprecision(1) << cnt / total * 100 <<"%"<< endl;
	}
	return 0;
}

方法三

insert(),返回值是pair<set::iterator,bool>

#include <iostream>
#include <iomanip>
#include<set>
set<int>store[51],query;
int N, M, n, a, p, q;
int  main() {
	cin >> N;
	for (int i = 1; i <= N; i++) {
		cin >> n;
		for (int j = 0; j < n; j++) {
			cin >> a;
			store[i].insert(a);
		}
	}
	cin >> M;
	for (int i = 0; i < M; i++) {
		int cnt = 0;
		cin >> p >> q;
		query = store[q];
		auto pointer = store[p].begin();
		for (pointer; pointer != store[p].end(); pointer++) {
			if (query.insert(*pointer).second == false)cnt++;
		}
		cout << fixed << setprecision(1) << cnt*1.0 / query.size() * 100.0 << "%" << endl;
	}
	return 0;
}