For each case: The first line contains an integer N represents the number of
For each test case, output a integer in a single line which represents the super-neatness of the row of trees.
3 1 3 1 4 1 2 3 4
6 10
As for the first case, the super-neatness of the row of trees [1, 3, 1] is 6, because there are 6 different subsequence of this row of trees: [1] (from index 0 to index 0), neatness is 0; [1, 3] (from index 0 to index 1), neatness is 2; [1, 3, 1] (from index 0 to index 2), neatness is 2; [3] (from index 1 to index 1), neatness is 0; [3, 1] (from index 1 to index 2), neatness is 2; [1] (from index 2 to index 2), neatness is 0.
等有机会再去重新学一遍线段树吧,要深入的学习,不能浅尝即止,这是别人ac的代码,个人觉得这篇代码写的很规范,值得我去学习。
#include
#include
#define N 1100000
using namespace std;
struct node
{
int num, numid;
}t[4 * N];
typedef long long LL;
LL ans;
int n, h[N], p, q;
void buildmax(int x, int l, int r)
{
int mid = (l + r) / 2;
if (l == r)
{
t[x].num = h[l];
t[x].numid = l;
return;
}
buildmax(x * 2, l, mid);
buildmax(x * 2 + 1, mid + 1, r);
int ls = x * 2, rs = x * 2 + 1;
t[x].num = max(t[ls].num, t[rs].num);
if (t[x].num == t[ls].num)
t[x].numid = t[ls].numid;
else
t[x].numid = t[rs].numid;
}
void buildmin(int x, int l, int r)
{
int mid = (l + r) / 2;
if (l == r)
{
t[x].num = h[l];
t[x].numid = l;
return;
}
buildmin(x * 2, l, mid);
buildmin(x * 2 + 1, mid + 1, r);
int ls = x * 2, rs = x * 2 + 1;
t[x].num = min(t[ls].num, t[rs].num);
if (t[x].num == t[ls].num)
t[x].numid = t[ls].numid;
else
t[x].numid = t[rs].numid;
}
void querymax(int x, int l, int r, int ls, int rs)
{
if (r < ls || l > rs) return;
if (l <= ls && rs <= r)
{
if (t[x].num > p)
{
p = t[x].num;
q = t[x].numid;
}
return;
}
int mid = (ls + rs) / 2;
querymax(x * 2, l, r, ls, mid);
querymax(x * 2 + 1, l, r, mid + 1, rs);
}
void querymin(int x, int l, int r, int ls, int rs)
{
if (r < ls || l > rs) return;
if (l <= ls && rs <= r)
{
if (t[x].num < p)
{
p = t[x].num;
q = t[x].numid;
}
return;
}
int mid = (ls + rs) / 2;
querymin(x * 2, l, r, ls, mid);
querymin(x * 2 + 1, l, r, mid + 1, rs);
}
void askmax(int l, int r)
{
if (l > r) return;
p = 0;
querymax(1, l, r, 1, n);
int t = q;
// cout << l << ' ' << r << ' ' << t << endl;
ans += LL(t - l + 1) * (r - t + 1) * h[t];
askmax(l, t - 1);
askmax(t + 1, r);
}
void askmin(int l, int r)
{
if (l > r) return;
p = 100000000;
querymin(1, l, r, 1, n);
int t = q;
ans -= LL(t - l + 1) * (r - t + 1) * h[t];
askmin(l, t - 1);
askmin(t + 1, r);
}
int main()
{
//freopen("1.in", "r", stdin);
//freopen("1.out", "w", stdout);
while(scanf("%d", &n) != EOF)
{
for(int i = 1; i <= n; i ++) scanf("%d", &h[i]);
buildmax(1, 1, n);
ans = 0;
askmax(1, n);
//cout << ans << endl;
buildmin(1, 1, n);
askmin(1, n);
cout << ans << endl;
}
return 0;
}