问题 D: Minimum Sum
时间限制: 2 Sec 内存限制: 256 MB提交: 77 解决: 19
[提交][状态][讨论版][命题人:admin]
题目描述
One day, Snuke was given a permutation of length N, a1,a2,…,aN, from his friend.
Find the following:
Constraints
1≤N≤200,000
(a1,a2,…,aN) is a permutation of (1,2,…,N).
Find the following:
Constraints
1≤N≤200,000
(a1,a2,…,aN) is a permutation of (1,2,…,N).
输入
The input is given from Standard Input in the following format:
N
a1 a2 … aN
N
a1 a2 … aN
输出
Print the answer.
Note that the answer may not fit into a 32-bit integer.
Note that the answer may not fit into a 32-bit integer.
样例输入
3
2 1 3
样例输出
9
思路:首先用一个set维护每次添加最小值的下标,每次添加最小的元素的时候,查询Set中小于该元素的下标最大的,和大于该元素下标的最小的,然后可以找出该元素影响的范围,
然后把该元素的下标加入set中
init:用set 最好先添加一个上下界,以防set不好操作。
代码如下:
#include <bits/stdc++.h> #define IT set<int>::iterator using namespace std; const int N=200000+7; typedef long long ll; struct Node{ ll v; int index; }node[N]; int c[N],n,vis[N]; int cmp(Node a,Node b) { return a.v<b.v; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%lld",&node[i].v); node[i].index=i; } ll ans=0; memset(vis,0,sizeof(vis)); sort(node+1,node+1+n,cmp); set<int>s; s.clear(); s.insert(0); s.insert(n+1); for(int i=1;i<=n;i++) { IT head,tail; tail=s.upper_bound(node[i].index); head=s.upper_bound(node[i].index); head--; ans+=node[i].v*(*tail-node[i].index)*(node[i].index - *head); s.insert(node[i].index); } printf("%lld ",ans); return 0; }