Ultraviolet A 1335 Beijing guards

Source: Internet
Author: User

The clever thing is that when the number of people is an odd number, the solution is to select the first person from the left as far as possible. If the number is an even number, select the person from the left as far as possible. If the number is an odd number, select from the right as far as possible.

Then, list the possible number of gifts in two parts to see if the problem is met. The first person and the last person do not select a duplicate.

Conclusion: redefinition of global variables may lead to errors. Therefore, you should be cautious when you fail to check the global variables.

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 100010;int a[maxn],left[maxn],right[maxn];int n;bool test(int p){    int x=a[1],y=p-a[1];    left[1]=x;right[1]=0;    for(int i=2;i<=n;i++)    {        if(i%2==1)        {            right[i]=min(y-right[i-1],a[i]);            left[i]=a[i]-right[i];        }        else        {            left[i]=min(x-left[i-1],a[i]);            right[i]=a[i]-left[i];        }    }    return left[n]==0;}int main(){    while(scanf("%d",&n)!=EOF)    {        if(n==0) break;        for(int i=1;i<=n;i++)            scanf("%d",&a[i]);        if(n==1)        {            printf("%d\n",a[1]);            continue;        }        a[n+1]=a[1];        int ans1=0,ans2=0;        for(int i=1;i<=n;i++)        {            ans1=max(ans1,a[i]+a[i+1]);        }        if(n%2==1)        {            for(int i=1;i<=n;i++)            {                ans2=max(ans2,a[i]*3);            }            while(ans1<ans2)            {                int m=ans1+(ans2-ans1)/2;                if(test(m))                    ans2=m;                else                    ans1=m+1;            }        }        printf("%d\n",ans1);    }    return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.