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 friend 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 104
.
Output Specification:
For each case, print in the first line the number of different friend 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
Sample Output:
4
3 6 9 26
自己写的
#include<iostream>
#include <vector>
#include<set>
using namespace std;
bool ha[60]={false};
int suma(int a){
int res = 0;
while(a!=0){
res+=a%10;
a/=10;
}
return res;
}
int main()
{
int n;
int a[10004];
int k = 0;
vector<int>v;
scanf("%d",&n);
for(int i =0;i<n;i++){
scanf("%d",&a[i]);
int tmp = suma(a[i]);
if(ha[tmp]);
else{
ha[tmp] = true;
k++;
}
}
cout << k << endl;
for(int i =0;i<60;i++){
if(ha[i]==true){
v.push_back(i);
}
}
for(int i=0;i<v.size();i++){
if(i) cout << " ";
cout << v[i];
}
}
别人家的,感觉区别还是有的,区别在于他地思路更加灵清。如果出现过什么都不做,如果没有出现过,这是一个关键点。还是考察对题目的理解力。
#include<iostream>
using namespace std;
const int maxn = 1e4+10;
int N;
bool appeared[60]={0};
int ans = 0;
string s[maxn];
int main(){
int i,j,k;
cin >> N;
for(i=0;i<N;i++) cin >> s[i];
for(i=0;i<N;i++){
j = 0;
for(char c:s[i]) j+= c-'0';
if(appeared[j]);
else{
appeared[j]= true;
ans++;
}
}
cout << ans << endl;
int cnt = 0;
for(i=0;i<60;i++){
if(appeared[i]){
if(cnt) cout << " ";
else cnt = 1;
cout << i;
}
}
}