【51nod - 1050】循环数组最大子段和(dp)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【51nod - 1050】循环数组最大子段和(dp)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                題干:
N個整數組成的循環序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的連續的子段和的最大值(循環序列是指n個數圍成一個圈,因此需要考慮a[n-1],a[n],a[1],a[2]這樣的序列)。當所給的整數均為負數時和為0。
例如:-2,11,-4,13,-5,-2,和最大的子段為:11,-4,13。和為20。
?收起
輸入
第1行:整數序列的長度N(2 <= N <= 50000) 第2 - N+1行:N個整數 (-10^9 <= S[i] <= 10^9)輸出
輸出循環數組的最大子段和。輸入樣例
6 -2 11 -4 13 -5 -2輸出樣例
20解題報告:
? ? 模板了。
AC代碼:
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const LL mod = 1e9 + 7; const int N = 200005; int a[N]; LL pre[N]; int main() {int n;scanf("%d", &n);for (int i = 1; i <= n; i++) {scanf("%d", &a[i]);a[n + i] = a[i];}for (int i = 1; i <= 2 * n; i++) {pre[i] = pre[i - 1] + a[i];}deque<int> q;q.push_back(0);LL ans = a[1];for (int i = 1; i <= 2 * n; i++) {if (!q.empty() && q.front() < i - n) {q.pop_front();}if(pre[i] - pre[q.front()] > ans) {ans = pre[i] - pre[q.front()];}else {while (!q.empty() && pre[q.back()] >= pre[i]) {q.pop_back();}}//ans = max(ans, pre[i] - pre[q.front()]);q.push_back(i);}printf("%lld\n", ans);return 0; }或者:
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const LL mod = 1e9 + 7; const int N = 200005; int a[N]; LL pre[N]; int main() {int n;scanf("%d", &n);for (int i = 1; i <= n; i++) {scanf("%d", &a[i]);a[n + i] = a[i];}for (int i = 1; i <= 2 * n; i++) {pre[i] = pre[i - 1] + a[i];}deque<int> q;q.push_back(0);LL ans = a[1];for (int i = 1; i <= 2 * n; i++) {if (!q.empty() && q.front() < i - n) {q.pop_front();}ans = max(ans, pre[i] - pre[q.front()]);while (!q.empty() && pre[q.back()] >= pre[i]) {q.pop_back();}q.push_back(i);}printf("%lld\n", ans);return 0; }另一個做法:
https://blog.csdn.net/weixin_41544329/article/details/85076111
總結
以上是生活随笔為你收集整理的【51nod - 1050】循环数组最大子段和(dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 3百块和3千块的智能手表有啥区别?主要看
- 下一篇: 曝iPhone 14将继续使用Light
