Flower
时间限制:1000ms 内存限制:65535KB
题目描述
Rabbit loves flowers very much and she plants n pots of flowers in her house . But she never prunes them because she is lazy . So the flowers have different heights and look ugly . One day , Kayaking decides to prune the flowers to make them look beautiful . To make them have equal heights , smart Kayaking has a wonderful idea. Initially , the i-th pot of flower's height is a[i]. Each time , Kayaking will select n-1 pots of flowers and prune them to make their height subtract 1 with his 49m knife . Exactly , the height of the flowers is at least 1 Now , Kayaking wants to know if it is possible to prune the flowers to make them have equal height . If possible , what is the minimum times he prunes the flowers .Could you tell him ?
输入格式
The input starts with a line contains exactly one positive number T which is the number of test case.
Each test case starts with a line contains a number n indicates the number of flowers Then there is a line contains n numbers indicates a [i].
输出格式
For each test case , print a single line containing one integer-the minimum times Kayaking prunes the flowers , or-1 if it is impossible.
样例输入
2 5 1 2 2 2 2 5 1 2 2 2 3
样例输出
1 -1
提示
T≤20, n≤100000 , ai≤1000000000
题目大概翻译后意思为:
共t组询问。有n朵花,高度不等。你每次只能对n-1朵花进行剪切,使他们减少1m,但是花至少1m。提问,能否使n朵花高度相等,如果能,输出剪切次数,如果不能输出-1。
题解:
每次对n-1朵花进行剪切,那也就是每次使一朵花生长1m。也就是说,只要足够长,是可以做到是每朵花一样高。但是这样做有一个限制,虽然我们把问题转换成每次让一朵花生长1m,但实际上还是每次对n-1朵花进行剪切,如果花没有足够长,那么我们还没剪到每朵花一样长,就会出现高度为1m的花,使其无法再次剪切,也就是输出-1。那么我们可以把这个作为答案的判定条件,如果足够长就输出次数,如果不够长就输出-1。
代码如下
#include<iostream>
#include<stack>
#include<algorithm>
#include<cstring>
#include<iomanip>
#include<cmath>
using namespace std;
long a[100005];
int main()
{
ios::sync_with_stdio(0);//io优化防超时
cin.tie(0);
cout.tie(0);
long long t,n;
cin>>t;
while(t--)
{
memset(a,0,sizeof(a));//每组都是新的开始,所以要清空数组
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];//输入数据
sort(a+1,a+1+n);//对数据进行排序,找到最小的和最大的
long long sum=0; //十年oi一场空,不开longlong见祖宗
for(int i=1;i<=n;i++)
sum+=a[n]-a[i];//最长的不需要生长,所以相等其实就是每朵花生长到最长
bool ans=1;//一开始定义有答案
if(sum>=a[n]+1)//原判断为for(int i=1;i<=n;i++)if(sum>=a[i]+a[n]-a[i]+1)ans=0;判断修剪后,每朵花是否比1小,化简得到现式
ans=0;
if(ans==1)//如果答案存在,输出次数
cout<<sum<<endl;
else//如果答案不存在,输出-1
cout<<"-1"<<endl;
}
return 0;
}
本题的难点除了翻译弄清题意以外(孩子英语不好已经自闭了),只存在于判定式,在想清原理后,其实本题不难。