保护果实
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
A有一棵果树,但是树上的果子总是还没有成熟就被B偷偷摘走了。于是,A想买一些栅栏想把果树围起来,让B再也偷不了果子。卖栅栏的人有N块栅栏,每块栅栏长度为ai。但是,卖栅栏的人与B关系很好,他不想随便卖给A。于是,他规定,如果要买第i块栅栏,那么必须要先买第i-1块栅栏(第一块栅栏除外)。同时,A是一个不想浪费的人,他想把他买的所有栅栏都用上,并且,让栅栏围成的图形是个多边形。那么,A最少需要买多少块栅栏呢。
Input
一共有两行。
第一行一个数,表示总共的栅栏数 N(N≤1,000,000) 。
第二行有N个数,第i个数表示第i块栅栏的长度 ai (ai之和不会超过int的上界) 。
Output
输出一个数,表示最少需要的栅栏数,如果无解输出-1.
Sample input and output
Sample Input | Sample Output |
---|---|
3 3 4 5 | 3 |
代码
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<queue>
#include<stack>
#define M 1000000+1000
#define MOD 1000007
#define LL long long
using namespace std;
int a[M];
int main()
{
int n;
while(~scanf("%d",&n))
{
int i,j;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int sum=0;
int maxx=0;
int num=0;
if(n<3) printf("-1\n");
else
{
for(i=0;i<n;i++)
{
if(a[i]>maxx)
maxx=a[i];
sum+=a[i];
if(sum>2*maxx) // 对三角形来说,就是 两边之和大于第三边,
{ // 对多边形来说,最大边 一定要小于 其他各个边的合;
num=i+1;// 一定为 sum>2*maxx; 第一次写 sum/2>max..果断尴尬
break;
}
}
if(num==0||num<3) printf("-1\n");
else
printf("%d\n",num);
}
}
return 0;
}