cf1276 B. Two Fairs

链接

点击跳转

题解

MikeMirzayanov给的题解比较神奇,我的做法和他不一样

根据割点的知识, a , b a,b 必须都是割点,否则就可以直接输出 0 0

那么把 a , b a,b 从图上删掉之后,图变成了很多连通块,连通块有三种情况:

  • 只和 a a 直接相连,假设这样的连通块的大小之和为 A A
  • 只和 b b 直接相连,假设这样的连通块的大小之和为 B B
  • a , b a,b 都直接相连

那么 A B A*B 就是答案了

代码

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 1000010
#define maxe 1000010
#define cl(x) memset(x,0,sizeof(x))
#define rep(_,__) for(_=1;_<=(__);_++)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
    ll c, f(1);
    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
    for(;isdigit(c);c=getchar())x=x*10+c-0x30;
    return f*x;
}
ll n, a, b;
struct UnionFind
{
	ll f[maxn], size[maxn];
	void init(ll n)
	{
		for(auto i=1;i<=n;i++)f[i]=i, size[i]=1;
	}
	ll find(ll x){return f[x]==x?x:f[x]=find(f[x]);}
	void merge(ll x, ll y)
    {
        auto fx=find(x), fy=find(y);
        f[fx]=fy;
        if(fx!=fy)size[fy]+=size[fx];
    }
}_a, _b, _ab;
int main()
{
    ll T=read(), m, u, v, i, s=0, A, B;
    while(T--)
    {
        n=read(), m=read(), a=read(), b=read();
        _a.init(n), _b.init(n), _ab.init(n);
        while(m--)
        {
            u=read(), v=read();
            if(u!=a and v!=a)_a.merge(u,v);
            if(u!=b and v!=b)_b.merge(u,v);
            if(u!=a and v!=a and u!=b and v!=b)_ab.merge(u,v);
        }
        A=B=0;
        rep(i,n)
        {
            if(i==a or i==b)continue;
            if(_b.find(i)==_b.find(a))A++;
            if(_a.find(i)==_a.find(b))B++;
            if(_b.find(i)==_b.find(a) and _a.find(i)==_a.find(b))A--, B--;
        }
        printf("%lld\n",A*B);
    }
    return 0;
}
发布了863 篇原创文章 · 获赞 72 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/FSAHFGSADHSAKNDAS/article/details/103650589