QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#593540 | #3226. Distance Sum | dongyc666 | WA | 3ms | 15932kb | C++14 | 2.4kb | 2024-09-27 14:33:50 | 2024-09-27 14:33:51 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int NR=2e5+10;
int n,dis[NR],fa[NR][20],dep[NR];
int L[NR],R[NR],dfn[NR],siz[NR],idx[NR],S;
#define pii pair<int,int>
#define fi first
#define se second
#define mkp make_pair
#define pb emplace_back
vector<pii>son[NR];
set<int>s;
void dfs(int id,int fath){
dep[id]=dep[fath]+1;
fa[id][0]=fath;siz[id]=1;
dfn[id]=++S;idx[S]=id;
L[id]=dfn[id];
for(int i=1;i<=18;i++)fa[id][i]=fa[fa[id][i-1]][i-1];
for(auto lcy:son[id]){
dis[lcy.fi]=dis[id]+lcy.se;
dfs(lcy.fi,id);
siz[id]+=siz[lcy.fi];
}
R[id]=dfn[id]+siz[id]-1;
}
int LCA(int x,int y){
if(dep[x]<dep[y])swap(x,y);
for(int i=18;i>=0;i--)
if(dep[fa[x][i]]>=dep[y])x=fa[x][i];
if(x==y)return x;
for(int i=18;i>=0;i--)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
int getd(int x,int y){
return dis[x]+dis[y]-2*dis[LCA(x,y)];
}
int jump(int x,int y){
for(int i=18;i>=0;i--)
if((y>>i)&1)x=fa[x][i];
return x;
}
struct BIT{
int c[NR];
int lowbit(int x){
return x&(-x);
}
void add(int x,int y){
while(x<=n){
c[x]+=y;
x+=lowbit(x);
}
}
int ask(int x){
int res=0;
while(x){
res+=c[x];
x-=lowbit(x);
}
return res;
}
int calc(int l,int r){return ask(r)-ask(l-1);}
}T;
void Insert(int x){
if(s.count(dfn[x]))return;
auto it=s.lower_bound(dfn[x]);
int tmp=LCA(idx[*it],x);
s.insert(dfn[tmp]);
s.insert(dfn[x]);
}
int getfa(int x){
auto it=s.lower_bound(dfn[x]);
if(it==s.begin())return 0;
it--;
return LCA(idx[*it],x);
}
signed main(){
cin>>n;
for(int i=2,x,y;i<=n;i++)
cin>>x>>y,son[x].pb(mkp(i,y));
dfs(1,0);
int res=0,rt=0;
for(int i=1;i<=n;i++){
if(!rt)rt=i;
res+=getd(rt,i);
Insert(i);T.add(dfn[i],1);
// printf("%lld %lld %lld %lld\n",L[i],R[i],L[rt],R[rt]);
if(L[rt]<=L[i]&&R[i]<=R[rt]&&i!=rt){
int tmp=jump(i,dep[i]-dep[rt]-1);
auto it1=s.lower_bound(L[tmp]),it2=s.lower_bound(R[tmp]);
it2--;
int tar=LCA(idx[*it1],idx[*it2]),val=T.calc(L[tar],R[tar]);
// printf("i:%lld tar:%lld val:%lld\n",i,tar,val);
if(val*2>i){
res-=(val*2-i)*(dis[tar]-dis[rt]);
rt=tar;
}
}
else{
int val=T.calc(L[rt],R[rt]);
if(val*2<i){
int nxt=getfa(rt);
res-=(i-val*2)*(dis[rt]-dis[nxt]);
rt=nxt;
}
}
// printf("i:%lld rt:%lld\n",i,rt);
cout<<res<<'\n';
}
return 0;
}
详细
Test #1:
score: 0
Wrong Answer
time: 3ms
memory: 15932kb
input:
10 5 1 2 1 1 1 4 1 2 1 5 1 2 1 2 1 5 1
output:
0 3 6 6 6 8 9 11 12 14
result:
wrong answer 3rd lines differ - expected: '4', found: '6'