首页 > 代码库 > 13C-非递减序列
13C-非递减序列
将序列中的数字每次+1或-1,最少的次数形成非递减序列
#include <cstdio>#include <vector>#include <algorithm>using namespace std;struct node{ int Left, Right, Height; vector<int> Lower;};typedef long long int64;int N, M;int Seq[5000];node Nodes[5000];int64 Result;int main(){ int I, J; scanf("%d", &N); for (I = 0; I < N; I++) scanf("%d", Seq + I); M = 0; for (I = 0; I < N; I++) if (M == 0 || Seq[I] > Nodes[M - 1].Height) { Nodes[M].Left = Nodes[M].Right = I; Nodes[M++].Height = Seq[I]; } else { Nodes[M - 1].Right++; if (Seq[I] < Nodes[M - 1].Height) { Nodes[M - 1].Lower.push_back(Seq[I]); push_heap(Nodes[M - 1].Lower.begin(), Nodes[M - 1].Lower.end()); } while (Nodes[M - 1].Lower.size() * 2 >= Nodes[M - 1].Right - Nodes[M - 1].Left + 1) { J = Nodes[M - 1].Lower[0]; if (M > 1 && Nodes[M - 2].Height > J) J = Nodes[M - 2].Height; while (!Nodes[M - 1].Lower.empty() && Nodes[M - 1].Lower[0] >= J) { pop_heap(Nodes[M - 1].Lower.begin(), Nodes[M - 1].Lower.end()); Nodes[M - 1].Lower.pop_back(); } Nodes[M - 1].Height = J; if (M > 1 && Nodes[M - 2].Height == J) { M--; if (Nodes[M - 1].Lower.size() < Nodes[M].Lower.size()) Nodes[M - 1].Lower.swap(Nodes[M].Lower); Nodes[M - 1].Lower.reserve(Nodes[M - 1].Lower.size() + Nodes[M].Lower.size()); while (!Nodes[M].Lower.empty()) { Nodes[M - 1].Lower.push_back(Nodes[M].Lower.back()); push_heap(Nodes[M - 1].Lower.begin(), Nodes[M - 1].Lower.end()); Nodes[M].Lower.pop_back(); } Nodes[M].Lower.clear(); Nodes[M - 1].Right = Nodes[M].Right; } } } Result = 0; for (I = 0; I < M; I++) for (J = Nodes[I].Left; J <= Nodes[I].Right; J++) if (Seq[J] < Nodes[I].Height) Result += Nodes[I].Height - Seq[J]; else Result += Seq[J] - Nodes[I].Height; printf("%I64d\n", Result); return 0;}
13C-非递减序列
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。