• 最大乘积 Maximun Product


    最大乘积

      题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=84562#problem/B

    题意:

    输入n个元素组成的序列s,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出0.

    注意格式。

      

    Sample Input
    3
    2 4 -3


    5
    2 5 -1 2 -1


    Sample Output
    Case #1: The maximum product is 8.


    Case #2: The maximum product is 20.

      分析:

       设置x为最大值y为最小值 ,在枚举更新时,如果a[i]为正,则对应跟新,

    a[i]为0时,当前最大值,最小值置零,a[i]小于0时,最大的值乘以a[i]后变成最小,

    相反最小变成最大。

     1 #include<iostream>
     2 using namespace std;
     3 int main()
     4 {
     5 int i,n,a[20],count=1;
     6  while(cin>>n)
     7 { 
     8 long long max=0,x=0,y=0,z;  //乘积最大可以为10^18所以防止溢出用long long
     9     for(i=0;i<n;i++)
    10 cin>>a[i];
    11 for(i=0;i<n;i++)
    12 {
    13 if(a[i]==0) x=y=0;
    14 else if(a[i]>0) 
    15 {  x=x*a[i];
    16    y=y*a[i];
    17    if(x==0) x=a[i];
    18 }else if(a[i]<0)    //小于0进行交叉相乘
    19 {
    20 z=x*a[i];
    21 x=y*a[i];
    22 y=z;
    23 if(y==0)  y=a[i];
    24 } 
    25 if(max<x&&a[i])
    26 max=x;
    27 }
    28 printf("Case #%d: The maximum product is %lld.
    
    ",count++,max);
    29 }
    30 return 0;
    31 }
  • 相关阅读:
    Fleury算法
    2012 MultiUniversity Training Contest 2
    高斯若尔当消元法(线性代数)
    hdu4307(最小割)
    hdu4305(生成树计数)
    hdu4318(最短路)
    hdu4309(网络流)
    hdu4313(生成树)
    生成树计数
    MYSQL 远程登录及常用命令
  • 原文地址:https://www.cnblogs.com/fenhong/p/4680623.html
Copyright © 2020-2023  润新知