分成互质组_DFS
分成互质组
给定 n 个正整数,将它们分组,使得每组中任意两个数互质。
至少要分成多少个组?
输入格式
第一行是一个正整数 n。
第二行是 n 个不大于10000的正整数。
输出格式
一个正整数,即最少需要的组数。
数据范围
1 ≤ n ≤ 1
输入样例:
输出样例:
折磨死我了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | #include <bits/stdc++.h> using namespace std; const int N = 15; int n, ans = 999; int a[N]; int group[N][N]; bool book[N]; int q1, q2; int gcd( int a, int b){ return b ? gcd(b, a % b) : a; } bool check( int i, int x, int cnt){ for ( int j = 0; j < cnt; j++){ if (gcd(a[i],group[x][j]) > 1) return false ; } return true ; } void dfs( int cnt, int x, int group_index, int group_cnt){ q1 = group_index; q2 = group_cnt; //printf("cnt = %d %d %d\n",cnt,q1,q2); // printf("x = %d index = %d ----------\n",x,group_index); // for(int i = 0; i < group_cnt; i++){ // printf("%d ",group[group_index][i]); // } // printf("\n"); // for(int i = 0; i < group_index; i++){ // for(int j = 0; j < group_cnt; j++){ // printf("%d ",group[i][j]); // } // printf("\n"); // } // printf("-------\n"); if (group_index > ans) return ; if (cnt == n){ ans = group_index; //printf("----------------------ans = %d\n",ans); return ; } int flag = 1; for ( int i = x; i < n; i++){ //printf("cnt = %d i = %d\n",cnt,i); //printf("%d %d\n",!book[x],check(i, group_index, group_cnt)); if (!book[i] && check(i, group_index, group_cnt)){ book[i] = 1; group[group_index][group_cnt] = a[i]; //printf("i = %d j = %d group[i][j] = %d\n",group_index,group_cnt,group[group_index][group_cnt]); dfs(cnt + 1, i + 1, group_index, group_cnt + 1); book[i] = 0; flag = 0; } } if (flag){ // for(int i = 0; i < group_cnt; i++){ // printf("%d ",group[group_index][i]); // } // printf("cnt = %d\n",cnt); dfs(cnt, 0, group_index + 1, 0); } } int main(){ cin >> n; for ( int i = 0; i < n; i++){ cin >> a[i]; } dfs(0,0,0,0); cout << ans + 1 << endl; return 0; } |
__EOF__

本文作者:从荣
本文链接:https://www.cnblogs.com/rongrongrong/p/15922590.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/rongrongrong/p/15922590.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】