// #include<bits/stdc++.h> // using namespace std ; // #define endl "\n" // int n , k , a[100] , sum = 0 , x[100]; // bool used[105]; // int check = 0 ; // // cnt la de kiem tra xem da tao duoc bao nhieu mang // void Try(int i , int start , int currentSum , int cnt){ // // neu bat dau quay lui sang cnt == k + 1 thi da du k mang theo yeu cau // if(cnt == k + 1){ // check = 1 ; // return ; // } // for(int j = start ; j <= n ; j++){ // if(!used[j] && currentSum + a[j] <= sum){ // x[i] = a[j]; // used[j] = true ; // //da chia duoc thanh 1 mang co tong = sum => gan lai start = 1 , currentSum = 0 // if(currentSum + a[j] == sum){ // Try(i + 1 , 1 , 0, cnt + 1); // } // else{ // Try(i + 1 , j + 1 , currentSum + a[j] , cnt); // } // // backtrack // used[j] = false ; // } // } // } // int main(){ // ios::sync_with_stdio(false); // cin.tie(nullptr); // cout.tie(nullptr); // cin >> n >> k ; // for(int i = 1 ; i <= n ; i++){ // cin >> a[i]; // sum += a[i]; // } // if(sum % k == 0){ // sum /= k ; // tinh luon // Try(1 , 1 , 0 , 1); // cnt = 1 => thi dieu kien tren la cnt == k + 1 || cnt = 0 => dk tren la cnt == k // cout << check ; // } // else cout << "0"; // } #include <bits/stdc++.h> #define endl "\n" using namespace std; int n, k, sum; bool ans = 0; int a[100]; void Try(int s, int tmp){ if (ans){ return; } if (tmp == k){ ans = 1; return; } for (int i = 0; i < n; i++){ if (s == sum){ Try(0, tmp + 1); cout << "Try(0,tmp + 1) : " << tmp + 1 << endl ; } else if (s < sum){ Try(s + a[i], tmp); cout << "Try( " << s + a[i]<< "," << tmp << " )" << endl ; } else return ; } } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cin >> n >> k; sum = 0; ans = 0; for (int i = 0; i < n; i++){ cin >> a[i]; sum += a[i]; } if (sum % k != 0) cout << "0"; else{ sum /= k; Try(0, 0); // cout << ans; } }
5 3 2 1 4 5 6
Try(0,tmp + 1) : 3 Try(0,tmp + 1) : 3 Try(0,tmp + 1) : 3 Try(0,tmp + 1) : 3 Try(0,tmp + 1) : 3 Try( 6,2 ) Try( 5,2 ) Try( 8,2 ) Try( 9,2 ) Try( 10,2 ) Try( 4,2 ) Try( 3,2 ) Try( 6,2 ) Try( 7,2 ) Try( 8,2 ) Try( 2,2 ) Try( 1,2 ) Try( 4,2 ) Try( 5,2 ) Try( 6,2 ) Try(0,tmp + 1) : 2 Try(0,tmp + 1) : 2 Try(0,tmp + 1) : 2 Try(0,tmp + 1) : 2 Try(0,tmp + 1) : 2 Try( 6,1 ) Try( 5,1 ) Try( 8,1 ) Try( 9,1 ) Try( 10,1 ) Try( 4,1 ) Try( 3,1 ) Try( 6,1 ) Try( 7,1 ) Try( 8,1 ) Try( 2,1 ) Try( 1,1 ) Try( 4,1 ) Try( 5,1 ) Try( 6,1 ) Try(0,tmp + 1) : 1 Try(0,tmp + 1) : 1 Try(0,tmp + 1) : 1 Try(0,tmp + 1) : 1 Try(0,tmp + 1) : 1 Try( 6,0 ) Try( 5,0 ) Try( 8,0 ) Try( 9,0 ) Try( 10,0 ) Try( 4,0 ) Try( 3,0 ) Try( 6,0 ) Try( 7,0 ) Try( 8,0 ) Try( 2,0 ) Try( 1,0 ) Try( 4,0 ) Try( 5,0 ) Try( 6,0 )