【HDU4694】 —Important Sisters(支配树)
支配树模板题
注意最后的地方从开始
#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ob==ib)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ob==ib)?EOF:*ib++;
}
#define gc getchar
inline int read(){
char ch=gc();
int res=0,f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define ll long long
#define re register
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
inline void chemx(int &a,int b){a<b?a=b:0;}
inline void chemn(int &a,int b){a>b?a=b:0;}
cs int N=50005;
int n,m;
namespace TT{
vector<int> e1[N],fr1[N],e2[N],fr2[N],t[N],p;
queue<int> q;
int idx[N],pos[N],tim,ff[N];
int ga[N],mn[N],semi[N];
int in[N],dep[N],val[N],fa[N][17];
inline void init(){
for(int i=1;i<=n;i++)ga[i]=mn[i]=semi[i]=i;
}
inline int find(int x){
if(ga[x]==x)return x;
int t=ga[x];ga[x]=find(ga[x]);
if(pos[semi[mn[t]]]<pos[semi[mn[x]]])mn[x]=mn[t];
return ga[x];
}
inline void add1(int u,int v){
e1[u].pb(v),fr1[v].pb(u);
}
inline void add2(int u,int v){
e2[u].pb(v),fr2[v].pb(u),in[v]++;
}
void dfs_t(int u){
pos[u]=++tim,idx[tim]=u;
for(int &v:e1[u])
if(!pos[v])ff[v]=u,add2(u,v),dfs_t(v);
}
inline void tarjan(){
for(int i=n;i>1;i--){
int u=idx[i],mx=i;
if(!u)continue;
for(int &v:fr1[u]){
if(!pos[v])continue;
if(pos[v]<pos[u])chemn(mx,pos[v]);
else find(v),chemn(mx,pos[semi[mn[v]]]);
}
semi[u]=idx[mx],ga[u]=ff[u],add2(semi[u],u);
}
}
inline void topsort(){
for(int i=1;i<=n;i++)if(!in[i])fr2[i].pb(0),q.push(i),p.pb(i);
while(!q.empty()){
int u=q.front();q.pop();
for(int &v:e2[u]){
in[v]--;
if(!in[v])p.pb(v),q.push(v);
}
}
}
inline int Lca(int u,int v){
if(dep[u]<dep[v])swap(u,v);
for(int i=16;~i;i--)if(dep[fa[u][i]]>=dep[v])u=fa[u][i];
if(u==v)return u;
for(int i=16;~i;i--)if(fa[u][i]!=fa[v][i])u=fa[u][i],v=fa[v][i];
return fa[u][0];
}
inline void buildt(){
for(int &u:p){
int v=fr2[u][0];
for(int &x:fr2[u])v=Lca(v,x);
fa[u][0]=v,dep[u]=dep[v]+1;
t[v].pb(u);
for(int i=1;i<=16;i++)fa[u][i]=fa[fa[u][i-1]][i-1];
}
}
void dfs(int u){
val[u]+=u;
for(int &v:t[u])
val[v]+=val[u],dfs(v);
}
inline void build(){
init();
for(int i=1;i<=m;i++){
int u=read(),v=read();
add1(u,v);
}
dfs_t(n);
tarjan();
topsort();
buildt();
dfs(n);
for(int i=1;i<n;i++)cout<<val[i]<<" ";cout<<val[n]<<'\n';
}
inline void clear(){
for(int i=0;i<=n;i++){
e1[i].clear(),fr1[i].clear();
e2[i].clear(),fr2[i].clear();
t[i].clear(),val[i]=0;
dep[i]=pos[i]=idx[i]=ff[i]=0;
for(int j=0;j<=16;j++)fa[i][j]=0;
}
tim=0,p.clear();
}
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
TT::build(),TT::clear();
}
}