1. 程式人生 > >LOJ #2587. 「APIO2018」鐵人兩項

LOJ #2587. 「APIO2018」鐵人兩項

是不是$ vector$存圖非常慢啊......

題意:求數對$(x,y,z)$的數量使得存在一條$x$到$z$的路徑上經過$y$,要求$x,y,z$兩兩不同  LOJ #2587


$ Solution:$

首先考慮一棵樹的情況怎麼做

我們列舉每一個點計算貢獻,貢獻即為經過這個點的鏈的數量

只要求出這個點的所有子樹大小就可以算出這個貢獻

 

然後發現如果某條鏈經過某個點雙聯通分量

這個連通分量裡的所有點都會被這條鏈的端點對計算貢獻

我們直接構建圓方樹,令方點的權值為這個點雙連通分量的大小

由於每個圓點每次都會被多算一次貢獻(被兩個方點共用或者是端點),我們令圓點的點權為$ -1$

然後直接在樹上做就好了

注意原圖不一定連通


$ my \ code:$

#include<ctime>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#define M 400010
#define rt register int
#define ll long long
using
namespace std; namespace fast_IO{ const int IN_LEN=10000000,OUT_LEN=10000000; char ibuf[IN_LEN],obuf[OUT_LEN],*ih=ibuf+IN_LEN,*oh=obuf,*lastin=ibuf+IN_LEN,*lastout=obuf+OUT_LEN-1; inline char getchar_(){return (ih==lastin)&&(lastin=(ih=ibuf)+fread(ibuf,1,IN_LEN,stdin),ih==lastin)?EOF:*ih++;} inline
void putchar_(const char x){if(oh==lastout)fwrite(obuf,1,oh-obuf,stdout),oh=obuf;*oh++=x;} inline void flush(){fwrite(obuf,1,oh-obuf,stdout);} } using namespace fast_IO; #define getchar() getchar_() inline ll read(){ ll x = 0; char zf = 1; char ch = getchar(); while (ch != '-' && !isdigit(ch)) ch = getchar(); if (ch == '-') zf = -1, ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * zf; } void write(ll y){if(y<0)putchar('-'),y=-y;if(y>9)write(y/10);putchar(y%10+48);} void writeln(const ll y){write(y);putchar('\n');} int i,j,k,m,n,x,y,z,cnt,size; int F[M],L[M],N[M],a[M],val[M],dfn[M],low[M],sta[M],top; void add(int x,int y){ a[++k]=y; if(!F[x])F[x]=k; else N[L[x]]=k; L[x]=k; } vector<int>e[400010]; void Add(int x,int y){ e[x].push_back(y); e[y].push_back(x); } void bemin(int &x,int y){ if(y<x)x=y; } int fa[400010],sz[400010],ds; void tarjan(int x){ dfn[x]=low[x]=++cnt;sta[++top]=x;sz[x]=1; for(rt i=F[x];i;i=N[i]){ if(!dfn[a[i]]){ tarjan(a[i]),bemin(low[x],low[a[i]]); if(low[a[i]]>=dfn[x]){ n++; while(sta[top+1]!=a[i])sz[n]+=sz[sta[top]],Add(sta[top],n),top--,val[n]++; sz[x]+=sz[n];Add(x,n);val[n]++; } } else bemin(low[x],dfn[a[i]]); } } ll ret; void calc(int x,int pre){ ll ans=0;int allsz=0; for(auto i:e[x])if(i!=pre){ calc(i,x); ans-=1ll*sz[i]*sz[i]; allsz+=sz[i]; } ans+=2ll*(size-(x<=ds))*allsz-1ll*allsz*allsz; ret+=ans/2*val[x]; } int main(){ n=ds=read();m=read(); for(rt i=1;i<=m;i++){ x=read();y=read(); add(x,y); add(y,x); } for(rt i=1;i<=n;i++)val[i]=-1; for(rt i=1;i<=ds;i++)if(!dfn[i])tarjan(i),size=sz[i],calc(i,i),ret-=1ll*size*(size-1); cout<<ret*2; return 0; }