日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【51nod - 1050】循环数组最大子段和(dp)

發(fā)布時(shí)間:2023/12/10 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【51nod - 1050】循环数组最大子段和(dp) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題干:

N個(gè)整數(shù)組成的循環(huán)序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的連續(xù)的子段和的最大值(循環(huán)序列是指n個(gè)數(shù)圍成一個(gè)圈,因此需要考慮a[n-1],a[n],a[1],a[2]這樣的序列)。當(dāng)所給的整數(shù)均為負(fù)數(shù)時(shí)和為0。

例如:-2,11,-4,13,-5,-2,和最大的子段為:11,-4,13。和為20。

?收起

輸入

第1行:整數(shù)序列的長(zhǎng)度N(2 <= N <= 50000) 第2 - N+1行:N個(gè)整數(shù) (-10^9 <= S[i] <= 10^9)

輸出

輸出循環(huán)數(shù)組的最大子段和。

輸入樣例

6 -2 11 -4 13 -5 -2

輸出樣例

20

解題報(bào)告:

? ? 模板了。

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; }

另一個(gè)做法:

https://blog.csdn.net/weixin_41544329/article/details/85076111

總結(jié)

以上是生活随笔為你收集整理的【51nod - 1050】循环数组最大子段和(dp)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。