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; }
相关文章推荐
- AtCoder Grand Contest 006 F - Blackout
- AtCoder Grand Contest 006 D - Median Pyramid Hard 二分答案
- AtCoder Grand Contest 006 E - Rotate 3x3 树状数组
- 【AtCoder】(AtCoder Grand Contest 006)D - Median Pyramid Hard
- 单挑养成计划【2】 AtCoder Grand Contest 005
- AtCoder Grand Contest 020 B - Ice Rink Game(贪心+计算机乘法)
- AtCoder Grand Contest 020 C - Median Sum (背包问题+bitset )
- AtCoder Grand Contest 018 D - Tree and Hamilton Path 树的重心
- AtCoder Grand Contest 011 C - Squared Graph 乱搞
- AtCoder Grand Contest 004 C - AND Grid 构造
- Atcoder Grand Contest 017 F Zigzag
- Atcoder Grand Contest 021 题解
- [AtCoder Grand Contest 013] D: Pilling Up (agc013d)
- AtCoder Grand Contest 013
- AtCoder Grand Contest 016
- 【贪心】【堆】AtCoder Grand Contest 018 C - Coins
- AtCoder Grand Contest 018 F - Two Trees
- Atcoder Grand Contest 19 题解
- (NTT)AtCoder Grand Contest 019 E - Shuffle and Swap
- AtCoder Grand Contest 019 B: Reverse and Compare