题解Atcoder Grand Contest C - Squared Graph

Problem Statement
Takahashi has received an undirected graph with N vertices, numbered 1, 2, ..., N. The edges in this graph are represented by (ui,vi). There are no self-loops and multiple edges in this graph.

Based on this graph, Takahashi is now constructing a new graph with N2 vertices, where each vertex is labeled with a pair of integers (a,b) (1≤a≤N, 1≤b≤N). The edges in this new graph are generated by the following rule:

Span an edge between vertices (a,b) and (a',b') if and only if both of the following two edges exist in the original graph: an edge between vertices a and a', and an edge between vertices b and b'.
How many connected components are there in this new graph?

Constraints
2≤N≤100,000
0≤M≤200,000
1≤ui<vi≤N
There exists no pair of distinct integers i and j such that ui=uj and vi=vj.

题意:给出一个有n个点的图G,构造一个新的有n^2^个点的图,每个点是一个二元组坐标,(a,b)和(a’,b’)有连边当且仅当a和a’有边,b和b’有边,询问这个新生成的图的连通分量个数。

大力分类讨论。

基本性质:原图是一棵树,新图就是打叉的形式

为了方便思考,我们把图复制一份,称为图A和图B,那么新图的定义改为(a,b)和(a’,b’)有连边当且仅当a和a’在图A中有边,b和b’在图B中有边。

首先考虑孤点,在两张图中孤点不与其他点连边,那么在新图中只要坐标有孤点,就一定不和任何点连边,就是A中的孤点和B中所有点组成N个点都是连通分量,B中孤点同理。但是还要减去重复的部分。

减去红色的,加上阴影部分,方案数为

IAN+IBNIAIB

然后考虑连通分量,分成两类,一类是二分图,一类是非二分图。

显然非二分图在新图中一定是一个连通分量,相当于在一棵树上再加一条边形成奇环,也就是在打叉的图中继续连边,一定能连成一个联通块。

也就是说一个非二分图一定是一个连通分量。

而二分图一定是两个连通分量。因为形成树之后,再连一条边还是会把已经连在一起的点连起来,这样一共会有两个联通块。

设非二分图个数P,二分图个数Q。

那么联通块个数为

PAPB+2QAQB

这样还不全,因为原图两个联通块对于新图来说,还有一部分点分别在两个联通块内。

可以发现如果一个来自于P,一个来自于Q,那么这一定是一个联通块。

这样会有贡献:

PAQB+PBQA

这样,把所有的情况加起来就是答案,由于A图和B图完全一样,所以可以简化式子,答案为

2InI2+P2+2PQ+2Q2

二分图黑板染色判断即可。

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std; 
#define N 2010000
struct node {ll to,next;}e[N*3];
ll size,o,p,vis[N],tag[N],g[N],f,n,m,i,du[N],I,P,Q;

void add(ll o,ll p)
{e[++size].to=p;e[size].next=g[o];g[o]=size;}

void dfs(ll x)
{
    vis[x]=1;
    for (ll k=g[x];k;k=e[k].next)
    {
        ll y=e[k].to;
        if (vis[y]==0)
        {
            tag[y]=tag[x]^1;
            dfs(y);
        }
        else  if (tag[x]==tag[y]) f=0;
    }
}

int main()
{
    scanf("%lld %lld",&n,&m);
    for (i=1;i<=m;i++)
    {
        scanf("%lld %lld",&o,&p);
        add(o,p);
        add(p,o);
        du[o]++;du[p]++;
    }

    for (i=1;i<=n;i++)
    {
        if (vis[i]==1) continue;
        if (du[i]==0)
        {
            I++;
            continue;
        }
        f=1;dfs(i);
        if (f==1) Q++;else P++;
    }

    ll ans=2*I*n-I*I+P*P+2*P*Q+2*Q*Q;

    printf("%lld\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值