Contest100000597 - 《算法筆記》6.2小節——C++標準模板庫(STL)介紹->set的常見用法詳解

問題 A: Set Similarity (25)

題目描述

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.

輸入

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.

輸出

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

樣例輸入

3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3

樣例輸出

50.0%
33.3%

Note

題目要求指定兩個集合之間的相似度,而相似度是相同元素的種類數除以共有的所有元素的種類數。所有對於輸入的每個集合,我們只關心種類數而不關心個數,所以用set來存儲是最好的。輸入完後,對於給定的集合1和集合2,我們首先枚舉集合1的元素,查看其是否在集合2中,是的話,cnt計數+1,由於set中元素唯一,不用擔心cnt重複計算的情況;然後共有的元素種類數,只需要將兩個集合的長度相加,再減去重複計算的部分即cnt即可得到。

#include <iostream>
#include <set>
#include <algorithm>
#include <iomanip>
using namespace std;

int main()
{
    int n, m, a, set1, set2;
    set<int> st[51];
    while (cin >> n)
    {
        for (int i = 1; i <= n; ++i) // 輸入n個集合的數據
        {
            cin >> m;
            while (m--) // 輸入每個集合中m個數
            {
                cin >> a; // 輸入集合中的數
                st[i].insert(a); // 加入集合中
            }
        }

        cin >> a; // 輸入查詢數
        while (a--)
        {
            int cnt = 0;
            cin >> set1 >> set2;
            set<int> &p = st[set1], &q = st[set2], set3;
            for (set<int>::iterator it = p.begin(); it != p.end(); ++it) // 遍歷集合set1中的元素
            {
                if (q.find(*it) != q.end()) // 如果在集合set2中存在該元素
                    ++cnt; // 計數加1
            }
            cout << fixed << setprecision(1) << ((cnt * 1.0) / (p.size() + q.size() - cnt)) * 100 << "%\n";
        }
    }
}

一定要自己寫一遍哦~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章