PAT乙级真题 1064 朋友数 C++实现(符STL set用法)

题目

如果两个整数各位数字的和是一样的,则被称为是“朋友数”,而那个公共的和就是它们的“朋友证号”。例如 123 和 51 就是朋友数,因为 1+2+3 = 5+1 = 6,而 6 就是它们的朋友证号。给定一些整数,要求你统计一下它们中有多少个不同的朋友证号。
输入格式:
输入第一行给出正整数 N。随后一行给出 N 个正整数,数字间以空格分隔。题目保证所有数字小于 10^4。
输出格式:
首先第一行输出给定数字中不同的朋友证号的个数;随后一行按递增顺序输出这些朋友证号,数字间隔一个空格,且行末不得有多余空格。
输入样例:
8
123 899 51 998 27 33 36 12
输出样例:
4
3 6 9 26

思路

用STL库中的set,存储每个不同的朋友数。

set常见用法有:

#include <set>
using namespace std;
//定义
set<int> myset;
//插入元素
myset.insert(20);
//查找元素
set<int>::iterator it=myset.find(20);
//检查不存在某值
if (myset.find(value)==myset.end()){...}
//删除元素
myset.erase (it);
//删除所有元素
myset.clear();
//判断set是否为空
if (myset.empty()){...}

set是红黑树结构,近似平衡,插入、删除、查找操作的时间复杂度都是 O(logn),并且能自动排序。

简直完美。

代码

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

int main(){ 
    int n;
    cin >> n;
    set<int> ss;
    for (int i=0; i<n; i++){
        string s;
        cin >> s;
        int sum = 0; 
        for (int j=0; j<s.length(); j++){
            sum += s[j] - 48;
        }
        if (ss.find(sum)==ss.end()){
            ss.insert(sum);
        }
    }

    //set会自动排序(从小到大)
    cout << ss.size() << endl;
    set<int>::iterator it=ss.begin();
    cout << *it++;
    while (it!=ss.end()){
        cout << " " << *it++;
    }
    cout << endl;
    return 0;
}


发布了105 篇原创文章 · 获赞 7 · 访问量 1732

猜你喜欢

转载自blog.csdn.net/zhang35/article/details/103918714