Codechef Sam and Sequences(单调队列)
2015-03-03 19:28
344 查看
题目链接:http://www.codechef.com/problems/PRYS03/
这题只要考虑每个数字,最左和最右分别能延伸到的位置,然后就能计算出每个数字需要计算的次数,由于数字可能重复,所以对于左边维护到不大于的第一个数字位置,右边维护到小于的第一个数字位置,然后维护好后,在扫一遍计算总和即可
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 100005;
int t, n;
ll a
;
struct Node {
ll v;
int id;
Node() {}
Node (ll v, int id) {
this->v = v;
this->id = id;
}
} S
;
int left
, right
;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%lld", &a[i]);
S[0].id = 0;
int top = 0;
for (int i = 1; i <= n; i++) {
while (top && S[top].v > a[i]) top--;
left[i] = S[top].id;
S[++top] = Node(a[i], i);
}
S[0].id = n + 1;
top = 0;
for (int i = n; i >= 1; i--) {
while (top && S[top].v >= a[i]) top--;
right[i] = S[top].id;
S[++top] = Node(a[i], i);
}
ll ans = 0;
for (int i = 1; i <= n; i++)
ans += (ll)(i - left[i]) * (right[i] - i) * a[i];
printf("%lld\n", ans);
}
return 0;
}
这题只要考虑每个数字,最左和最右分别能延伸到的位置,然后就能计算出每个数字需要计算的次数,由于数字可能重复,所以对于左边维护到不大于的第一个数字位置,右边维护到小于的第一个数字位置,然后维护好后,在扫一遍计算总和即可
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 100005;
int t, n;
ll a
;
struct Node {
ll v;
int id;
Node() {}
Node (ll v, int id) {
this->v = v;
this->id = id;
}
} S
;
int left
, right
;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%lld", &a[i]);
S[0].id = 0;
int top = 0;
for (int i = 1; i <= n; i++) {
while (top && S[top].v > a[i]) top--;
left[i] = S[top].id;
S[++top] = Node(a[i], i);
}
S[0].id = n + 1;
top = 0;
for (int i = n; i >= 1; i--) {
while (top && S[top].v >= a[i]) top--;
right[i] = S[top].id;
S[++top] = Node(a[i], i);
}
ll ans = 0;
for (int i = 1; i <= n; i++)
ans += (ll)(i - left[i]) * (right[i] - i) * a[i];
printf("%lld\n", ans);
}
return 0;
}
相关文章推荐
- Codeforces Round #291 (Div. 2) D. R2D2 and Droid Army RMQ/单调队列/尺取法
- Codeforces Gym - 101234J Zero Game [单调队列]
- CodeChef Little Elephant and Balance
- CodeChef Sereja and LCM(矩阵快速幂)
- CodeChef:Company and Club Hierarchies(树形dp & 技巧)
- CodeForce Round 219 Div2 E Watching Fireworks is Fun 单调队列DP
- SPOJ130_Rent your airplane and make money_单调队列DP实现
- CodeChef SEAVOTE Sereja and Votes
- [CodeChef-DGTCNT]Chef and Digits
- Range Minimum Queries (CodeChef ANDMIN )
- CF&&CC百套计划2 CodeChef December Challenge 2017 Chef and Hamming Distance of arrays
- Codechef Wonder Woman and the Dark man
- Codechef December Challenge 2014 Chef and Apple Trees 水题
- HDU5945 Fxx and game(单调队列)
- hdu 5945 Fxx and game【dp+单调队列】
- Codechef2015 May - Chef and Strings (后缀自动机)
- bzoj2806 [Ctsc2012]Cheat(单调队列优化dp+二分+广义SAM)
- CodeChef - AND Pairwise AND sum
- Codechef Little Elephant and Painting (期望+动态规划)
- CF&&CC百套计划2 CodeChef December Challenge 2017 Chef And Easy Xor Queries