UVa 11509 Maximum Product(最大乘积)
2015-12-30 21:56
489 查看
题目链接:UVa 11509
题意:
输入n个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出0(表示无解)。1<=n<=18,-10<=S[i]<=10。
分析:
两层循环对每个s[i]求最大连续子序列乘积,逐个取最大即可。
注意:
C++中 long long 不能用%I64d输出。
CODE:
附一个O(n)的解法。原博地址:UVa 11059
题意:
输入n个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出0(表示无解)。1<=n<=18,-10<=S[i]<=10。
分析:
两层循环对每个s[i]求最大连续子序列乘积,逐个取最大即可。
注意:
C++中 long long 不能用%I64d输出。
CODE:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <string> #include <algorithm> #include <queue> using namespace std; int n, a[20],cases=0; long long ans, tmp; int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif while (cin >> n) { for (int i = 0; i < n; i++) cin >> a[i]; ans = 0; for (int i = 0; i < n; i++) { tmp = 1; for (int j = i; j < n; j++) { tmp *= a[j]; ans = max(ans, tmp); } } printf("Case #%d: The maximum product is %lld.\n\n", ++cases, ans); } return 0; }
附一个O(n)的解法。原博地址:UVa 11059
#include <iostream> #include <cstdlib> #include <cstring> using namespace std; int data[20]; int main() { int n,t = 1; while (cin >> n) { for (int i = 1 ; i <= n ; ++ i) cin >> data[i]; long long max = 0,neg = 0,pos = 0,tem; for (int i = 1 ; i <= n ; ++ i) { if (data[i] == 0) neg = pos = 0; else if (data[i] > 0) { pos = pos*data[i]; neg = neg*data[i]; if (!pos) pos = data[i]; }else if (data[i] < 0) { tem = pos*data[i]; pos = neg*data[i]; neg = tem; if (!neg) neg = data[i]; } if (max < pos && data[i]) max = pos; } cout << "Case #" << t ++ << ": The maximum product is " << max << ".\n\n"; } return 0; }
相关文章推荐
- cocos2d-x 3.0游戏实例学习笔记《卡牌塔防》第八部---怪物出场
- 玩转递归
- 超强、超详细Redis数据库入门教程
- 第八章(2)-使用泛型委托
- SonarQube升级
- 面试干货
- 反转链表
- Linux下使用雅黑与Consolas字体
- jsp知识点
- WPS热点怎么关闭
- 将MATLAB中的mat数据转换为OpenCV能够读取的xml数据
- 32c3 ctf writeup
- Java类集学习(六)应用范例(一对多的关系)
- Android 上实现非root的 Traceroute -- 非Root权限下移植可执行二进制文件 脚本文件
- dependency-injection(依赖注入)
- eclipse jad 反编译 插件安装
- DocFX
- Duplicate复制数据库并创建物理StandBy(spfile+不同实例名+不同路径)
- bzoj3141: [Hnoi2013]旅行
- 图灵奖获得者传记