BZOJ 1345 序列问题 单调栈

题目链接:

https://www.lydsy.com/JudgeOnline/problem.php?id=1345

题目大意:

对于一个给定的序列a1,…,an,我们对它进行一个操作reduce(i),该操作将数列中的元素ai和ai+1用一个元素max(ai,ai+1)替代,这样得到一个比原来序列短的新序列。这一操作的代价是max(ai,ai+1)。进行n-1次该操作后,可以得到一个长度为1的序列。我们的任务是计算代价最小的reduce操作步骤,将给定的序列变成长度为1的序列。

思路:

由贪心可知,每个数合并的对象为离这个数最近的并且大于等于这个数的值。可以用单调栈找出来离它最近的并且比它大的数字。我这里用了两次单调栈,第一次找出右边第一个大于等于a[i]的数,第二次找出左边大于等于a[i]的数。

 1 #include<bits/stdc++.h>
 2 #define IOS ios::sync_with_stdio(false);//不可再使用scanf printf
 3 #define Max(a, b) ((a) > (b) ? (a) : (b))//禁用于函数,会超时
 4 #define Min(a, b) ((a) < (b) ? (a) : (b))
 5 #define Mem(a) memset(a, 0, sizeof(a))
 6 #define Dis(x, y, x1, y1) ((x - x1) * (x - x1) + (y - y1) * (y - y1))
 7 #define MID(l, r) ((l) + ((r) - (l)) / 2)
 8 #define lson ((o)<<1)
 9 #define rson ((o)<<1|1)
10 #define Accepted 0
11 #pragma comment(linker, "/STACK:102400000,102400000")//栈外挂
12 using namespace std;
13 inline int read()
14 {
15     int x=0,f=1;char ch=getchar();
16     while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
17     while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
18     return x*f;
19 }
20 typedef long long ll;
21 const int maxn = 1000000 + 10;
22 const int MOD = 1000000007;//const引用更快,宏定义也更快
23 const int INF = 1e9 + 7;
24 const double eps = 1e-6;
25 ll a[maxn];
26 stack<ll>q;
27 ll ans[maxn];
28 bool vis[maxn];
29 
30 int main()
31 {
32     ll n;
33     ll mmax = 0;
34     ll tot = 0;
35     scanf("%lld", &n);
36     for(int i = 1; i <= n; i++)
37     {
38         scanf("%lld", &a[i]);
39         mmax = max(mmax, a[i]);
40         while(!q.empty() && a[q.top()] <= a[i])//顺序扫一遍 维护递减的单调栈 求解i右边第一个大于a[i]的值
41         {
42             vis[q.top()] = 1;
43             ans[q.top()] = a[i];
44             q.pop();
45         }
46         q.push(i);
47     }
48     while(!q.empty())q.pop();
49     for(int i = n; i >= 1; i--)
50     {
51         while(!q.empty() && a[q.top()] <= a[i])//逆序扫一遍 维护递减的单调栈 求解i左边第一个大于a[i]的值
52         {
53             if(vis[q.top()])ans[q.top()] = min(ans[q.top()], a[i]);
54             else ans[q.top()] = a[i], vis[q.top()] = 1;
55             q.pop();
56         }
57         q.push(i);
58     }
59     int cnt = 0;
60     for(int i = 1; i <= n; i++)if(vis[i])cnt++, tot += ans[i];
61     if(cnt == n)tot -= mmax;
62     cout<<tot<<endl;
63     return Accepted;
64 }

 

posted @ 2018-09-29 21:24  _努力努力再努力x  阅读(221)  评论(0编辑  收藏  举报