51nod 2456 最小约数 V2

题目

给出n个数,将这n个数进行分组,分组规则为:除了1以外最小的约数相同的数字分为一组。最后,输出这个最小约数,同时按照从小到大的顺序逐一输出这些数字。

例如:7个数,35 8 39 12 8 26 25
输出为:

2 8 8 12 26([8, 8, 12, 26]为给定的7个数中,以2为最小约数(除1以外)的数)
3 39([39]为给定的7个数中,以3为最小约数(除1以外)的数)
5 25 35([25, 35]为给定的7个数中,以5为最小约数(除1以外)的数)

输入
第一行:1个数n(n <= 1000)
后面n行,每行1个数a[i](2 <= a[i] <= 10000)
输出
按照约数d从小到大的顺序,逐行输出所有最小约数(除了1之外的)为d的数字,并且每行中输出数字的顺序也是从小到大。
输入样例
7
35
8
39
12
8
26
25
输出样例
2 8 8 12 26
3 39
5 25 35

解题思路

利用struct储存最小约数和数字 然后用sort排序 在排序之前在struct最后放一个数用来输出

代码

#include <bits/stdc++.h>
#include<iostream>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include<cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
const int MOD = 1E9+7;
const int N = 100000+5;
using namespace std;

struct x
{
    int num;
    int yue;
}a[N];

int cmp( x a,x b)
{
    if(a.yue== b.yue){
        return a.num < b.num;
    }
    return a.yue < b.yue;
}
int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    //freopen("input.txt","r",stdin);
    // IO
    int n;
    cin >> n;
    for(int i = 0;i < n;i++){
        cin >> a[i].num;
        for(int j = 2; ; j++){
            if(a[i].num%j==0){
                a[i].yue = j;
                break;
            }
        }
    }
    a[n].num = 100000;
    a[n].yue = 100000;

    sort(a,a+n,cmp);
    int l = 0,r;
    int x = a[0].yue;
    for(int i = l; i <= n; i++){
        if(x != a[i].yue){
            cout << x << ' ';
            for(int j = l; j < i; j++){
                cout << a[j].num << ' ';
            }
            cout << endl;
            l = i;
            x = a[i].yue;
        }
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值