首页 > 其他 > 详细

1120 Friend Numbers (20 分)

时间:2021-02-27 09:44:46      阅读:27      评论:0      收藏:0      [点我收藏+]

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 1.

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
 

Sample Output:

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;
}

 

1120 Friend Numbers (20 分)

原文:https://www.cnblogs.com/dreamzj/p/14454581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!