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