您的位置:首页 > 其它

最大连续子序列和(经典DP) 之 hdu 1231 最大连续子序列

2014-08-01 15:16 465 查看
//  [8/1/2014 Sjm]
/*
经典问题。。。

状态:以当前位置i结尾的最大连续子序列和

*/



#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstring>
#include <set>
#include <utility>
#include <locale>
#include <ctime>
using namespace std;
//using int64 = long long;
const int INF = 0x3f3f3f3f;
const int MaxN = 10010;

int N, arr[MaxN];

void Solve()
{
int ans = -1, maxTmp = -1;
int beginTmp = 0, endTmp = 0, ibegin = 0, iend = 0;
for (int i = 0; i < N; ++i)
{
if (maxTmp < 0)
{
maxTmp = arr[i];
beginTmp = i;
endTmp = i;
}else
{
maxTmp += arr[i];
endTmp = i;
}
if (maxTmp > ans)
{
ans = maxTmp;
//cout << "---" << ans << endl;
ibegin = beginTmp;
iend = endTmp;
}
}
cout << ans << " " << arr[ibegin] << " " << arr[iend] << endl;
}

int main()
{
#ifdef HOME
freopen("in", "r", stdin);
//freopen("out", "w", stdout);
#endif

while (cin >> N && N)
{
bool judge = true;
for (int i = 0; i < N; ++i) {
cin >> arr[i];
if (arr[i] >= 0) judge = false;
}
if (judge)
{
cout << 0 << " " << arr[0] << " " << arr[N - 1] << endl;
}
else
{
Solve();
}
}

#ifdef HOME
cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
#endif
return 0;
}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: