[PA2014]Fiolki
传送门
Solution
正解是并查集重构树
可是我的启发式\(set\)合并\(O(k\log^2 n)\)也过了吖
Code
#include<bits/stdc++.h>
#define ll long long
#define db double
#define dbg1(x) void(0)
#define dbg2(x) void(0)
#define dbg3(x) void(0)
using namespace std;
inline int read()
{
int f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
return x*f;
}
const int MN=2e5+5;
#define P pair<int,int>
#define mp make_pair
#define pb push_back
set<P> S[MN];ll ans;
int N,M,K,c[MN],lie[MN];
vector<int> G[MN];
vector<pair<int,int> >H[MN];
vector<pair<P,int> > z;
set<P>::iterator it,ii,jj;
int Cb(int x,int y)
{
if(S[x].size()>=S[y].size()) std::swap(x,y);
z.clear();
for(it=S[x].begin();it!=S[x].end();++it)
{
int id=(*it).first;
for(int j=0;j<H[id].size();++j)
{
ii=S[y].lower_bound(mp(H[id][j].second,0));
if(ii==S[y].end()) continue;
if((*ii).first==H[id][j].second) z.pb(mp(H[id][j],id));
}
}
std::sort(z.begin(),z.end());
for(int i=0;i<z.size();++i)
{
int _x=(z[i].first).second,_y=z[i].second,lefx,lefy;
ii=S[y].lower_bound(mp(_x,0));
jj=S[x].lower_bound(mp(_y,0));
if(ii==S[y].end()||jj==S[x].end()||(*ii).first!=_x||(*jj).first!=_y)continue;
ans+=2ll*min(lefx=(*ii).second,lefy=(*jj).second);
S[y].erase(ii);S[x].erase(jj);
if(lefx>lefy) S[y].insert(mp(_x,lefx-lefy));
else S[x].insert(mp(_y,lefy-lefx));
}
for(it=S[x].begin();it!=S[x].end();++it)S[y].insert(*it);
return y;
}
void dfs(int x)
{
int n=G[x].size(),i;
for(i=0;i<n;++i) dfs(G[x][i]);
for(i=0;i<n;++i) lie[x]=Cb(lie[x],lie[G[x][i]]);
}
int main()
{
N=read(),M=read(),K=read();
int i,a,b;
for(i=1;i<=N;++i) S[i].insert(mp(i,read())),lie[i]=i;
for(i=1;i<=M;++i) a=read(),b=read(),G[b].pb(a),++c[a];
for(i=1;i<=K;++i) a=read(),b=read(),H[a].pb(mp(i,b)),H[b].pb(mp(i,a));
for(i=1;i<=N;++i) if(!c[i]) dfs(i);
return 0*printf("%lld\n",ans);
}
Blog来自PaperCloud,未经允许,请勿转载,TKS!
致虚极,守静笃,万物并作,吾以观其复