AcWing241. 楼兰图腾
题目大意
解题思路
^
字符,我们需要的其实是:
i
的前面比它小的字符数,记作l[i]
i
后面比它大的字符数,记作r[i]
l[num]
种(只要比r[num]
种(只要比resA
统计
V
,我们也这样统计。
解题代码
这里代码放两份,一份是规矩扫描,另一份是边扫描第二次边统计。
代码1
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
using LL = long long;
const int N = 2e5 + 10;
int n, a[N], Al[N], Bl[N], tr[N], Ar[N], Br[N];
void add(int x, int v)
{
for (; x <= n; x += x & -x) tr[x] += v;
}
int ask(int x)
{
int res = 0;
for (; x; x -= x & -x) res += tr[x];
return res;
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i ++ )
scanf("%d", &a[i]);
for (int i = 1; i <= n; i ++ )
{
int j = a[i];
Al[j] += ask(j - 1), Ar[j] += ask(n) - ask(j); //Al是一个数前面比它小的,Ar是一个数前面比它大的
add(j, 1);
}
memset(tr, 0, sizeof tr);
LL resA = 0, resV = 0;
for (int i = n; i; i -- )
{
int j = a[i];
Br[j] += ask(j - 1), Bl[j] += ask(n) - ask(j); //Br是后面比它小的,Bl是后面比它大的
add(j, 1);
}
for (int i = 1; i <= n; i ++ )
{
int j = a[i];
resA += (LL) Al[j] * Br[j];
resV += (LL) Ar[j] * Bl[j];
}
printf("%lld %lld\n", resV, resA);
return 0;
}
代码2
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
using LL = long long;
const int N = 2e5 + 10;
int n, a[N], low[N], big[N], tr[N];
void add(int x, int v)
{
for (; x <= n; x += x & -x) tr[x] += v;
}
int ask(int x)
{
int res = 0;
for (; x; x -= x & -x) res += tr[x];
return res;
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i ++ )
scanf("%d", &a[i]);
for (int i = 1; i <= n; i ++ )
{
int j = a[i];
low[j] += ask(j - 1), big[j] += ask(n) - ask(j);
add(j, 1);
}
memset(tr, 0, sizeof tr);
LL resA = 0, resV = 0;
for (int i = n; i; i -- )
{
int j = a[i];
resA += (LL) low[j] * ask(j - 1);
resV += (LL) big[j] * (ask(n) - ask(j));
add(j, 1);
}
printf("%lld %lld\n", resV, resA);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)