题解 魔法宝石
好奇怪啊,建个笛卡尔树试试?
需要枚举左右子树的点对,可以之枚举一边的?
只枚举比较小的那边?
\(O(n\log n)\)?懒,所以用 map,再加个 log 也能过
点击查看代码
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define N 500010
#define fir first
#define sec second
#define ll long long
//#define int long long
char buf[1<<21], *p1=buf, *p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
inline int read() {
int ans=0, f=1; char c=getchar();
while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
return ans*f;
}
int n;
int a[N];
namespace force{
int ans;
int qmax(int l, int r) {int ans=0; for (int i=l; i<=r; ++i) ans=max(ans, a[i]); return ans;}
void solve() {
for (int i=1; i<=n; ++i)
for (int j=i+1; j<=n; ++j)
if (a[i]+a[j]==qmax(i, j)) ++ans;
cout<<ans<<endl;
}
}
namespace task1{
ll ans;
map<int, int> mp[N];
int ls[N], rs[N], top;
pair<int, int> sta[N];
void dfs(int u) {
if (ls[u]) dfs(ls[u]);
if (rs[u]) dfs(rs[u]);
if (mp[ls[u]].size()>mp[rs[u]].size()) swap(ls[u], rs[u]);
for (auto it:mp[ls[u]]) if (mp[rs[u]].find(a[u]-it.fir)!=mp[rs[u]].end())
ans+=1ll*it.sec*mp[rs[u]][a[u]-it.fir];
for (auto it:mp[ls[u]]) mp[rs[u]][it.fir]+=it.sec;
swap(mp[rs[u]], mp[u]);
++mp[u][a[u]];
}
void solve() {
for (int i=1; i<=n; ++i) {
int k=top;
pair<int, int> t={a[i], i};
while (k && t.fir>sta[k].fir) --k;
if (k!=top) ls[t.sec]=sta[k+1].sec;
if (k) rs[sta[k].sec]=i;
sta[top=++k]=t;
}
// cout<<"ls: "; for (int i=1; i<=n; ++i) cout<<ls[i]<<' '; cout<<endl;
// cout<<"rs: "; for (int i=1; i<=n; ++i) cout<<rs[i]<<' '; cout<<endl;
dfs(sta[1].sec);
cout<<ans<<endl;
}
}
signed main()
{
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
n=read();
for (int i=1; i<=n; ++i) a[i]=read();
// force::solve();
task1::solve();
return 0;
}