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中孤点同理。但是还要减去重复的部分。
减去红色的,加上阴影部分,方案数为
IA∗N+IB∗N−IA∗IB
然后考虑连通分量,分成两类,一类是二分图,一类是非二分图。
显然非二分图在新图中一定是一个连通分量,相当于在一棵树上再加一条边形成奇环,也就是在打叉的图中继续连边,一定能连成一个联通块。
也就是说一个非二分图一定是一个连通分量。
而二分图一定是两个连通分量。因为形成树之后,再连一条边还是会把已经连在一起的点连起来,这样一共会有两个联通块。
设非二分图个数P,二分图个数Q。
那么联通块个数为
PA∗PB+2∗QA∗QB
这样还不全,因为原图两个联通块对于新图来说,还有一部分点分别在两个联通块内。
可以发现如果一个来自于P,一个来自于Q,那么这一定是一个联通块。
这样会有贡献:
PA∗QB+PB∗QA
这样,把所有的情况加起来就是答案,由于A图和B图完全一样,所以可以简化式子,答案为
2∗I∗n−I2+P2+2∗P∗Q+2∗Q2
二分图黑板染色判断即可。
代码
#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;
}