2020 BIT冬训-模拟与暴力 F - Maximum Product UVA - 11059

UVA的judge好慢……20min还是in judege queue。

这题的首先将字符串分割为以0隔开的子串(千万不要把0放进去啊)。

对于每一个子串,将其分为3个部分。

第一个负数及之前的数的乘积(ltemp),第一个和最后一个负数中间的数的乘积(ctemp),最后一个负数及之后数的乘积(rtemp)。

如果ctemp为0,即只有一个负数。此时选取第一个负数之前的正数乘积(lztemp)和第一个负数后的数的乘积(rtemp)较大值即可。

如果ctemp大于0。由于ltemp小于0,rtemp小于0。故三者乘积为正且最大。

如果ctemp小于0。由于ltemp小于0,rtemp小于0。故选择其中与ctemp相乘较大的即可。

注意可能有坑爹数据1018。所以要开long long

AC代码。

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
long long s[20],n,ans,ltemp,rtemp,ctemp,lztemp,id;
int main(){
    while(~scanf("%lld",&n)){
        ans=0,ltemp=0,lztemp=0,rtemp=0,ctemp=0;
        for(int i=0;i<n;i++){
            scanf("%lld",&s[i]);
        }
        for(int i=0;i<n;i++){
            if(s[i]){
                if(s[i]<0){
                    if(ltemp>=0){
                        if(ltemp==0)
                            ltemp=1;
                        ltemp*=s[i];
                    }else{
                        if(rtemp!=0){
                            if(ctemp==0)
                                ctemp=1;
                            ctemp*=rtemp;
                        }
                        rtemp=s[i];
                    }
                }else{
                    if(ltemp==0){
                        ltemp=1;
                        ltemp*=s[i];
                        lztemp=ltemp;
                    }else if(ltemp>0){
                        ltemp*=s[i];
                        lztemp=ltemp;
                    }else if(rtemp==0)
                        rtemp =1;
                    rtemp*=s[i];
                }
            }else{
                if(ctemp==0){
                    if(rtemp>=0)
                        ans=max(ans,max(lztemp,rtemp));
                    else
                        ans=max(ans,ltemp*rtemp);
                }else if(ctemp>0)
                    ans=max(ans,ltemp*ctemp*rtemp);
                else
                    ans=max(ans,max(ltemp*ctemp,ctemp*rtemp));
                ltemp=0,lztemp=0,rtemp=0,ctemp=0;
            }
        }
        if(ctemp==0){
            if(rtemp>=0)
                ans=max(ans,max(lztemp,rtemp));
            else
                ans=max(ans,ltemp*rtemp);
        }else if(ctemp>0)
            ans=max(ans,ltemp*ctemp*rtemp);
        else
            ans=max(ans,max(ltemp*ctemp,ctemp*rtemp));
        printf("Case #%lld: The maximum product is %lld.\n\n",++id,ans);
    }
}

 

posted @ 2021-02-05 19:18  mikku  阅读(41)  评论(0)    收藏  举报