[algorithm]pta 7-1 集合相似度
阿新 • • 發佈:2022-04-03
給定兩個整數集合,它們的相似度定義為:Nc/Nt×100%。其中Nc是兩個集合都有的不相等整數的個數,Nt是兩個集合一共有的不相等整數的個數。你的任務就是計算任意一對給定集合的相似度。
輸入格式:
輸入第一行給出一個正整數N(≤50),是集合的個數。隨後N行,每行對應一個集合。每個集合首先給出一個正整數M(≤104),是集合中元素的個數;然後跟M個[0,109]區間內的整數。
之後一行給出一個正整數K(≤2000),隨後K行,每行對應一對需要計算相似度的集合的編號(集合從1到N編號)。數字間以空格分隔。
輸出格式:
對每一對需要計算的集合,在一行中輸出它們的相似度,為保留小數點後2位的百分比數字。
輸入樣例:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3
輸出樣例:
50.00% 33.33%
#include <iostream> #include <stdio.h> #include <set> #include <vector> using namespace std; class solution1 { public: solution1(); }; vector<set<int>> SetArr; solution1::solution1() { SetArr.resize(256); int nLoop, nSize, nNum; float nSLength, nCatLenght; vector<float> showarr; cin >> nLoop; for (int i = 0; i < nLoop; i++) { cin >> nSize; for (int j = 0; j < nSize; j++) { cin >> nNum; SetArr[i].insert(nNum);//新增到集合 } } cin >> nLoop; while (nLoop--) { //不涉及到陣列新增什麼的,可以用這迴圈更方便 int nCom1, nCom2; cin >> nCom1 >> nCom2; nSLength = SetArr.at(nCom1 - 1).size() + SetArr.at(nCom2 - 1).size(); set<int> newset(SetArr.at(nCom1-1));//拷貝初始化 newset.insert(SetArr.at(nCom2-1).begin(), SetArr.at(nCom2-1).end());//插入 相當於是合併了 nCatLenght = newset.size(); showarr.push_back(((nSLength - nCatLenght) / nCatLenght) * 100); } for (int i = 0; i < showarr.size(); i++) { printf("%.2f%%\n", showarr[i]); } } int main() { solution1 s1; return 0; }