我想知道是否有人可以提供一种算法,将给定数量的项目(例如x)分为n个不同的组。
例如。
分组th>Group1 = 3, Group2 = 2 Group1 = 2, Group2 = 2, Group3 = 1Group1 = 2, group2 -7 = 1Group1 = 5, Group2 = 5
我找了一段时间,没有找到任何东西。发帖后,我又搜索了一遍,立刻找到了我要找的东西(lol)。
#include<bits/stdc++.h>
using namespace std;;
// Function that prints
// the required sequence
void split(int x, int n)
{
// If we cannot split the
// number into exactly 'N' parts
if(x < n)
cout<<"-1"<<" ";
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for(int i=0;i<n;i++)
cout<<(x/n)<<" ";
}
else
{
// upto n-(x % n) the values
// will be x / n
// after that the values
// will be x / n + 1
int zp = n - (x % n);
int pp = x/n;
for(int i=0;i<n;i++)
{
if(i>= zp)
cout<<(pp + 1)<<" ";
else
cout<<pp<<" ";
}
}
}
// Driver code
int main()
{
int x = 5;
int n = 3;
split(x, n);
}
来源:Geeks for Geeks:将数字分成N部分,使最小部分和最大部分之间的差异最小。链接:https://www.geeksforgeeks.org/split-the-number-into-n-parts-such-that-difference-between-the-smallest-and-the-largest-part-is-minimum/