【PAT甲级】Friend Numbers

2019-11-08 14:22:56 浏览数 (1)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

代码语言:txt复制
                 本文链接:[https://blog.csdn.net/weixin_42449444/article/details/89451403](https://blog.csdn.net/weixin_42449444/article/details/89451403) 

Problem Description:

Two integers are called "friend numbers" if they share the same sum of their digits, and the sum is their "friend ID". For example, 123 and 51 are friend numbers since 1 2 3 = 5 1 = 6, and 6 is their friend ID. Given some numbers, you are supposed to count the number of different frind ID's among them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N. Then N positive integers are given in the next line, separated by spaces. All the numbers are less than 10​4​​.

Output Specification:

For each case, print in the first line the number of different frind ID's among the given integers. Then in the second line, output the friend ID's in increasing order. The numbers must be separated by exactly one space and there must be no extra space at the end of the line.

Sample Input:

代码语言:javascript复制
8
123 899 51 998 27 33 36 12

Sample Output:

代码语言:javascript复制
4
3 6 9 26

解题思路:

这题在乙级里写过:【PAT乙级】朋友数。先自定义一个fun()函数用来求各位数之和,建立一个set用来记录朋友证号,然后无脑双重for循环,当俩个数的各位数之和相等的时候就说明它们俩个是朋友数 存入set中。然而我第一次提交之后有个测试点TLE了,于是我在双重for循环中加入了一条if语句,如果set中已经记录过了这个朋友证号就可以不用再进行第二层for循环了,提交之后AC啦。

AC代码:

代码语言:javascript复制
#include <bits/stdc  .h>
using namespace std;
 
int fun(int n)  //用来求各位数之和
{
    string temp = to_string(n);
    int sum = 0;
    for(auto it : temp)
    {
        sum  = it-'0';
    }
    return sum;
}
 
int main()
{
    int N;
    cin >> N;
    int a[N];
    for(int i = 0; i < N; i  )
    {
        cin >> a[i];
    }
    set<int> s;  //用来记录朋友证号
    for(int i = 0; i < N; i  )
    {
        int temp = fun(a[i]);
        if(s.count(temp) == 0)  //第一次递交后出现了TLE,然后我加了这条if语句,不再考虑出现过的朋友证号
        {
            for(int j = i; j < N; j  )
            {
                if(temp == fun(a[j]))  //两个数的各位数之和相等,它们就是朋友数
                {
                    s.insert(temp);
                }
            }
        }
    }
    cout << s.size() << endl;    //set.size()就是朋友证号的个数
    bool isVirgin = true;  //判断是不是第一次
    for(auto it : s)   //无脑遍历set进行输出
    {
        if(isVirgin)
        {
            cout << it;
            isVirgin = false;
        }
        else
        {
            cout << " " << it;
        }
    }
    return 0;
}

0 人点赞