joj2058

 2058: Find the Section

Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 713 153 Standard
In this task you are asked to deal with a lot of floating point numbers. Find the section in a number table that the sum of the numbers in it is the maximum.

Input

The first line of each test case is an integer N (<=100000). And the following lines have N floating point numbers. The last case have the N equal to zero, which you should not process.

Output

For each test case print "Case #T:" in the first line, where the T starts from 1. And the second line the sentence "The section from N1(th) to N2(th) have the max sum S", which means the numbers in the table from N1(th) to N2(th) have the sum S and S is the maximum you can find. N1, N2 are integers, and S is rounded to the nearest 0.001.

Note: If two sections have the same max sum, find the longer one and the one appears first. The length of the section can be zero which have a sum of zero, and it is from 0(th) to 0(th).

Sample Input

5
1 3.1 -2 7.35 -4
10
-5 -4 -3 -2 -1 0 1 2 3 4
0

Sample Output

Case #1:
The section from 1(th) to 4(th) have the max sum 9.450
Case #2:
The section from 6(th) to 10(th) have the max sum 10.000

Problem Source: coldcpp

This problem is used for contest: 11 

Submit / Problem List / Status / Discuss







#include<iostream>
#include<stdio.h>
using namespace std;
double  a[100000+10];
double  s[100000+10];
int c[100000+10];
int main()
{
   //freopen("in.txt","r",stdin);
    int n;
    int count=0;
    while(1)
    {
        cin>>n;
        if(n==0)break;
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
        }
        s[0]=0;
        c[0]=0;
        for(int i=1;i<=n;i++)
        {
           if(s[i-1]<0)
           {
               s[i]=a[i];
               c[i]=1;
           }
           else
           {
               if(s[i-1]+a[i]>=0)
               {
                   s[i]=a[i]+s[i-1];
                   c[i]=c[i-1]+1;
               }
               else
               {
                   s[i]=a[i];
                   c[i]=1;
               }
           }
        }
        double max=s[1];
        int head=0;
        int tail=1;
        for(int i=1;i<=n;i++)
        {
            if(max<=s[i])
            {
                if(max==s[i]&&c[i]>c[tail])
                {
                    tail=i;
                }
                if(max<s[i])tail=i,max=s[i];
            }
        }
        count++;
        printf("Case #%d:\n",count);
        if(max<0)
        {
            printf("The section from 0(th) to 0(th) have the max sum 0.000\n");
        }
        else
        printf("The section from %d(th) to %d(th) have the max sum %.3f\n",tail-c[tail]+1,tail,max);


    }
    return 0;
}
这个是一个动态规划的题目通过s表示前从i往前最大的子串和。。
不过我的代码跟一个在网上看到的代码有些不太相同,边缘结果不太一样。。。

你可能感兴趣的:(joj2058)