【HDOJ】1003

问题描述

Given a sequence a[1],a[2],a[3]……a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.

SB Code

#include <iostream>

using namespace std;

struct Node {
    int start, end, value;
};

int main()
{
    int T;
    Node sum;
    Node tmp;
    int N;
    int a[100001];
    while (cin >> T && T!=EOF) {
          for (int j = 0; j < T; j++) {
              cin >> N;
              sum.value = 0;
              memset(a, 0, 100001);
              for (int i = 0; i < N; i++) {
                cin >> a[i];
              }

              for (int s = 0; s < N; s++) {
                  for (int l = 1; l <= N - s; l++) {
                      tmp.value = 0;
                      for (int i = s; i < s + l; i++) {
                          tmp.value += a[i];
                          tmp.start = s + 1;
                          tmp.end = s + l;
                      }
                      if (tmp.value > sum.value) sum = tmp;
                  }
              }

              cout << "Case " << j + 1 << endl;
              cout << sum.value << " " << sum.start << " "<< sum.end << endl;
              if (j + 1 != T) cout << endl;
          }
    }
    return 0;
}

AC Code

#include <iostream>

using namespace std;

struct Node {
    int start, end, value;
};

int main()
{
    int T;
    Node sum;
    Node tmp;
    int N;
    int a[100002];
    while (cin >> T && T!=EOF) {
          for (int j = 0; j < T; j++) {
              cin >> N;
              sum.value = -10000;
              sum.start = 1;
              sum.end = 0;
              tmp.value = 0;
              tmp.start = 1;
              tmp.end = 0;
              memset(a, 0, 100001);
              for (int i = 0; i < N; i++) {
                cin >> a[i];
              }

              for (int i = 0; i < N; i++) {
                  tmp.value += a[i];
                  if (tmp.value > sum.value) {
                     sum.value = tmp.value;
                     sum.start = tmp.start;
                     sum.end = i + 1;
                  }
                  if (tmp.value < 0) {
                     tmp.start = i + 2;
                     tmp.value = 0;  
                  }
              }

              cout << "Case " << j + 1 << ":"<< endl;
              cout << sum.value << " " << sum.start << " "<< sum.end << endl;
              if (j + 1 != T) cout << endl;
          }
    }
    return 0;
}

我知道这个struct用得很蠢……

猜你喜欢

转载自blog.csdn.net/qq_29977681/article/details/80488168
今日推荐