There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that:
- each ball belongs to exactly one of the sets,
- there are no empty sets,
- there is no set containing two (or more) balls of different colors (each set contains only balls of one color),
- there are no two sets such that the difference between their sizes is greater than 1.
Print the minimum possible number of sets.
The first line contains one integer number n (1 ≤ n ≤ 500).
The second line contains n integer numbers a1, a2, ... , an (1 ≤ ai ≤ 109).
Print one integer number — the minimum possible number of sets.
3 4 7 8
5
2 2 7
4
In the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color.
题目大意:给定若干堆的球,每堆球为一种颜色,试问可以划分最少多少集合的球。每一个集合的球满足如下要求,每个集合内的球颜色相同,任意相邻两个集合内元素的个数差不超过1个。
解题思路:首先对于假定集合的大小为x,x+1,那么如何去判断这个x是否满足要求呢?对于一个a[i]来说,若a[i]%x==0,那么肯定满足要求。若a[i]%x!=0,a[i]/x+a[i]%x>=1满足要求,原因在此不赘述,此时划分a[i]/x+1堆即可。
对于一个给定的x可以判断其是否满足要求,那么如何去枚举x呢?下面有两种方法:
1.从a[0]到1开始枚举,若满足条件直接跳出
2.从1到sqrt(a[0])枚举,a[0]/i和i(原因很简单,记a[0]可以划分k个集合,大小为x,x+1,那么x*k<=a[0])
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
const int INF=0x3f3f3f3f*2;
int a[505];
int n;
ll work(int x)
{
ll sum=0;
for(int i=0;i<n;i++)
{
if(a[i]%x==0||(a[i]/x+a[i]%x>=x-1))
sum+=a[i]/x+(a[i]%x!=0);
else
return 0;
}
return sum;
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sort(a,a+n);
ll s;
for(int k=1;k<=a[0] + 1;k++)
{
s=work(a[0]/k+1);
if(s)
break;
s=work(a[0]/k);
if(s)
break;
}
printf("%I64d\n",s);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=500+10;
int n;
LL a[maxn],ans=-1;
void calc(int k)
{
LL temp=0;
for (int i=1; i<=n; i++) {
int x=a[i]/k,y=a[i]%k;
if (x<y) {
return ;
}
x-=y;
temp+=(x+y-x/(k+1));
}
if (ans==-1||ans>temp) {
ans=temp;
}
}
int main()
{
cin>>n;
for (int i=1; i<=n; i++) {
scanf("%I64d",&a[i]);
}
for (int k=1; (LL)k*k<=a[1]; k++) {
calc(k);
calc(a[1]/k);
if (a[1]%k==0&&a[1]>k) {
calc(a[1]/k-1);
}
}
cout<<ans;
return 0;
}