fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. int n, a[10], arr[10], k, used[10], d = 1, s = 0;
  6. bool timThayyy = false;
  7.  
  8. // a[] là hoán vị của các số tự nhiên từ 1 đến n
  9. // arr[] là hoán vị của n phần tử
  10.  
  11.  
  12. void check() {
  13. if (timThayyy)
  14. return;
  15. int sum = 0;
  16. vector<int> res;
  17. res.clear();
  18. for (int i = 0; i < n; i++) {
  19. if (sum + arr[a[i] - 1] > s/k)
  20. return;
  21. sum += arr[a[i] - 1];
  22. if (sum == s/k) {
  23. res.push_back(a[i] - 1); // lưu vị trí phần tử cuối của nhóm
  24. sum = 0;
  25. }
  26. }
  27. timThayyy = true;
  28. cout<< "Có thể chia "<< n<< " phần tử thành "<< k<< " nhóm có tổng là "<< s/k<< endl;
  29. int j = 0;
  30. cout<< j + 1<< ": ";
  31. for (int i = 0; i < n; i++) {
  32. cout<< arr[a[i] - 1]<< " ";
  33. if (res[j] == a[i] - 1) {
  34. cout<< endl;
  35. j++;
  36. if (i < n - 1)
  37. cout<< j + 1<< ": ";
  38. }
  39. }
  40. }
  41.  
  42. void permutation(int i) {
  43. if (timThayyy)
  44. return;
  45. for (int j = 1; j <= n; j++) {
  46. if (!used[j]) {
  47. a[i] = j;
  48. used[j] = 1;
  49. if (i == n - 1)
  50. check();
  51. else
  52. permutation(i + 1);
  53. used[j] = 0;
  54. }
  55. }
  56. }
  57.  
  58. int main() {
  59. cin >> n>> k;
  60. for (int i = 0; i < n; i++) {
  61. cin>> arr[i];
  62. s += arr[i];
  63. }
  64. if (s % k != 0) {
  65. cout<< "oh noooo!!!!";
  66. return 0;
  67. }
  68. permutation(0);
  69. }
  70.  
Success #stdin #stdout 0.01s 5284KB
stdin
6 3
1 2 3 4 5 6
stdout
Có thể chia 6 phần tử thành 3 nhóm có tổng là 7
1: 1 6 
2: 2 5 
3: 3 4