日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【最后测试点超时】1063 Set Similarity (25 分)_22行代码AC

發布時間:2024/2/28 58 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【最后测试点超时】1063 Set Similarity (25 分)_22行代码AC 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

立志用最少的代碼做最高效的表達


PAT甲級最優題解——>傳送門


Given two sets of integers, the similarity of the sets is defined to be N?c??/N?t??×100%, where N?c?? is the number of distinct common numbers shared by the two sets, and N?t?? is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

Input Specification:
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 (≤10?4??) and followed by M integers in the range [0,10?9??]. 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.

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

Sample Input:
3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3

Sample Output:
50.0%
33.3%


題意:給定N個集合。 K個查詢, 查詢某兩個集合間共同出現元素個數(不重復)/全部元素個數(不重復)

算法設計:用unordered_map建立映射,將A集合的元素帶入B中, 查看是否出現過即可。

提高效率的方法:
1、使用了map而非unordered_map。 二者區別在于map的插入效率為O(nlogn),因為每次插入都要自動維護有序序列。 而后者的插入效率為O(1)
2、在求Nc和Nt時,只求出Nc,用總值減Nc即為Nt的值。不需要額外計算Nt


儲備知識擴展:集合和映射問題(很重要,提高效率,降低碼量):

  • set——有序去重集合。

  • map——有序去重映射

  • multiset——有序不去重集合

  • multimap——有序不去重映射

  • unordered_set——無序不去重集合(普通集合)

  • unordered_map——無序不去重映射(普通映射)


#include<bits/stdc++.h> using namespace std; int main() { // ios::sync_with_stdio(false);unordered_map<int, int>s[55];int n; scanf("%d", &n);for(int j = 1; j <= n; j++) {int m; scanf("%d", &m); for(int i = 0; i < m; i++) {int x; scanf("%d", &x);s[j][x]++;}} int k; cin >> k; while(k--) {int x, y; scanf("%d%d", &x, &y);int Nc = 0, Nt = 0;for(auto i : s[x]) if(s[y].count(i.first) > 0 ) Nc++;Nt = s[x].size()+s[y].size()-Nc;printf("%.1lf%%\n", Nc*100.0/Nt);}return 0; }

耗時:


求贊哦~ (?ω?)

總結

以上是生活随笔為你收集整理的【最后测试点超时】1063 Set Similarity (25 分)_22行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。