Problem Description
给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个, 例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和 为20。 在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该 子序列的第一个和最后一个元素。
 
Input
测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。
 
Output
对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元 素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。
 
Sample Input
6
-2 11 -4 13 -5 -2
 
10
-10 1 2 3 4 -5 -23 3 7 -21
 
6
5 -8 3 2 5 0
 
1
10
 
3
-1 -5 -2
 
3 -
1 0 -2
 
Sample Output
20 11 13
10 1 4
10 3 5
10 10 10
0 -1 -2
0 0 0
 
我用树状数组写的
code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <algorithm> using namespace std; int lowbit(int x)
{
return x&(-x);
} int a[100000+10];
int c[100000+10];
int s[100000+10]; int Sum(int x)
{
int s=0;
while(x>0)
{
s+=c[x];
x=x-lowbit(x);
}
return s;
} bool fu(int *a, int n)
{
for(int i=1; i<=n; i++)
{
if(a[i]>=0) return false;
}
return true;
}
int main()
{
int n;
int i, j;
while(scanf("%d", &n)!=EOF)
{
for(i=1; i<=n; i++)
{
scanf("%d", &a[i]);
}
if(fu(a, n)==true)
{
printf("0 %d %d\n", a[1], a[n]);
continue;
}
for(i=1; i<=n; i++)
{
c[i]=0;
for(j=i-lowbit(i)+1; j<=i; j++)
c[i]+=a[j];
//printf("c[%d]=%d\n", i, c[i]);
}
int ans=-1;
for(i=1; i<=n; i++)
s[i]=Sum(i); int left, right;
for(i=1; i<=n; i++)
{
int dd=s[i], ff=0;
if(dd>ans)
{
ans=dd;
left=a[1];
right=a[i];
}
for(j=1; j<i; j++)
{
ff=s[j];
if(dd-ff > ans)
{
ans = dd-ff;
left=a[j+1];
right=a[i];
}
}
}
printf("%d %d %d\n", ans, left, right);
}
return 0;
}

最新文章

  1. Android 上实现像微信一样的用Fragment来实现的Tab切页效果 提供源码下载
  2. BaseAdapter日常的封装
  3. Java 字符串用逗号并接
  4. FileObverse文件观察者的Debug报告
  5. PropertyGrid--基本功能
  6. 【Struts2学习笔记(1)】Struts2中Action名称的搜索顺序和多个Action共享一个视图--全局result配置
  7. 如何将mongodb bson文件转成json文件
  8. objective-C学习笔记(四)函数成员:方法(函数)
  9. Android 解屏幕锁与点亮屏幕
  10. 12.04 ubuntu 更改IP
  11. Notice: ob_end_clean() [ref.outcontrol]: failed to delete buffer. No buffer to delete
  12. gzip: File too large错误
  13. 我的hibernate学习记录(二)
  14. python基础15下_迭代器_生成器
  15. VS2010与Matlab2010b混合编程
  16. LeetCode——295. Find Median from Data Stream
  17. Oracle 11g 静默安装-db_install.rsp详解
  18. http://www.gasi.ch/blog/inside-deep-zoom-2/
  19. MySQL中MyISAM与InnoDB区别及选择,mysql添加外键
  20. 摘要JSR168 PORLET标准手册汉化整理

热门文章

  1. android中延迟执行某个任务
  2. javascript iframe 操作(一)
  3. iOS 集成阿里百川最新版(3.1.1.96) 实现淘宝授权登录以及调用淘宝客户端商品详情页
  4. 【转】Visual studio 快捷键大全
  5. JavaScript 初步认识
  6. 辛星教你高速掌握PHP的正則表達式
  7. ASSERT(m_hWnd == hWndOrig) - 解决之
  8. jetty;linux 目录结构
  9. Sharepoint server 2016自定义作业不能部署
  10. #1560 : H国的身份证号码II(dp+矩阵快速幂)