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.
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 1.
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.
8
123 899 51 998 27 33 36 12
4
3 6 9 26
#include<bits/stdc++.h> using namespace std; const int maxn=100010; int book[maxn]={0}; int getID(int temp){ int sum=0; while(temp>0){ sum+=temp%10; temp/=10; } return sum; } bool cmp(int a,int b){ return a>b; } int main(){ int n; cin>>n; int temp; for(int i=0;i<n;i++){ cin>>temp; temp=getID(temp); book[temp]++; } int count=0; for(int i=0;i<maxn;i++){ if(book[i]!=0){ count++; } } printf("%d\n",count); int i,t; for(i=0;i<maxn;i++){ if(book[i]!=0&&t<count-1){ printf("%d ",i); t++; } else if(book[i]!=0){ printf("%d\n",i); } } return 0; }
优化:
#include<bits/stdc++.h> using namespace std; const int maxn=100010; int book[maxn]={0}; int getID(int temp){ int sum=0; while(temp>0){ sum+=temp%10; temp/=10; } return sum; } set<int> s; int main(){ int n; cin>>n; int temp; for(int i=0;i<n;i++){ cin>>temp; temp=getID(temp); s.insert(temp); } printf("%d\n",s.size()); for(set<int>::iterator it=s.begin();it!=s.end();it++){ if(it!=s.begin()){//去除末尾空格的方法 printf(" "); } printf("%d",*it); } return 0; }
原文:https://www.cnblogs.com/dreamzj/p/14454581.html