您的位置:首页 > 其它

AtCoder Grand Contest 006 F - Blackout 三染色

2018-02-16 10:40 507 查看

题意

有一个n*n的网格图,一开始有m个格子是黑色的,其余全是白色的。规定若(x,y)和(y,z)都是黑色,则可以把(z,x)也染尘黑色。问最多可以把多少个格子染黑。

n,m<=100000

分析

不妨把黑格子(x,y)看成一条有向边,那么就变成了一个图上的问题。

对于每一个弱连通块进行三染色,然后分三种情况讨论:

若三种颜色中只出现了两种或以下,则不会增加新的边。

若三种颜色都存在且染色成功,则每种颜色的点都可以向它的下一种颜色的点连边。

若三种颜色都不存在且染色失败,则任意点两两之间都有连边,包括自环。

证明懒的写了,可以去看题解。

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

typedef long long LL;

const int N=100005;

int n,m,f
,s
,col
,tot,t[3],cnt,last
,nx[3]={1,2,0},ls[3]={2,0,1},flag;
bool vis
;
struct edge{int to,next,op;}e[N*2];

int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}

int find(int x)
{
if (f[x]==x) return x;
else return f[x]=find(f[x]);
}

void addedge(int u,int v)
{
e[++cnt].to=v;e[cnt].op=0;e[cnt].next=last[u];last[u]=cnt;
e[++cnt].to=u;e[cnt].op=1;e[cnt].next=last[v];last[v]=cnt;
}

void dfs(int x)
{
vis[x]=1;t[col[x]]++;tot++;
for (int i=last[x];i;i=e[i].next)
if (!vis[e[i].to]) col[e[i].to]=!e[i].op?nx[col[x]]:ls[col[x]],dfs(e[i].to);
else if (col[e[i].to]!=(!e[i].op?nx[col[x]]:ls[col[x]])) flag=1;
}

int main()
{
n=read();m=read();
for (int i=1;i<=n;i++) f[i]=i;
for (int i=1;i<=m;i++)
{
int x=read(),y=read();
addedge(x,y);
if (find(x)!=find(y)) x=find(x),y=find(y),s[y]+=s[x],f[x]=y;
s[find(x)]++;
}
LL ans=0;
for (int i=1;i<=n;i++)
if (!vis[i])
{
tot=t[0]=t[1]=t[2]=flag=0;
dfs(i);
if (flag) ans+=(LL)tot*tot;
else if (t[0]&&t[1]&&t[2]) ans+=(LL)t[0]*t[1]+(LL)t[1]*t[2]+(LL)t[2]*t[0];
else ans+=s[find(i)];
}
cout<<ans;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: