【PAT甲级】Friend Numbers

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:

```8
123 899 51 998 27 33 36 12```

```4
3 6 9 26```

AC代码：

```#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 条评论

• 【PAT乙级】判断题

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

• HBU-DS2018SY-1-1 数组循环左移 （20 分）

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

• 【PAT甲级】Counting Ones

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

• HOJ 2317 Pimp My Ride(状态压缩DP)

Pimp My Ride My Tags (Edit) Source : TUD 2005 Time limit : 3 sec Me...

• 【HDU 4305】Lightning（生成树计数）

There are N robots standing on the ground (Don't know why. Don't know how).

• HDU 1866 A + B forever!

A + B forever! Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/3...

• 【PAT甲级】1002 A+B for Polynomials (25分)

This time, you are supposed to find A+B where A and B are two polynomials.

• LeetCode Weekly Contest 32解题思路

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...

• LeetCode 75. Sort Colors题目分析

给定一个包含红，白，蓝且长度为 n 的数组，将数组元素进行分类使相同颜色的元素相邻，并按照红、白、蓝的顺序进行排序。 我们可以使用整数 0，1 和 2 分别代...

• F2. Animal Observation (hard version)

time limit per test：3 seconds memory limit per test：512 megabytes inputstandard ...