您的位置:首页 > 其它

【BFS】CODE[VS] 1535 封锁阳光大学(二分图BFS染色)

2016-10-30 11:17 337 查看
点击进入异世界

关于二分图染色详情请回戳我的上一篇博文【DFS】CODE[VS] 1535 封锁阳光大学 (二分图染色)

BFS代码也很好写,思路跟DFS基本一样,只不过在搜的时候,我们要从一个点出发遍历完整个连通子图

基本的BFS

代码如下(略丑,比DFS慢一些):

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

const int maxn = 320010;

using namespace std;

int tot;
int ans;
int n,m;
int color[maxn];
int head[maxn];
int sum[3];
bool motherfucker;
bool vis[maxn];

struct node{
int f;
int t;
int next;
}e[maxn << 1];

inline void build(int ff,int tt)
{
tot++;
e[tot].f = ff;
e[tot].t = tt;
e[tot].next = head[ff];
head[ff] = tot;
}

queue<int >q;

void bfs(int s)
{
q.push(s);
vis[s] = 1;
color[s]= 1;
sum[1]++;
while(!q.empty())
{

int u = q.front();
if(u == 0)
continue;
q.pop();
for(int i = head[u];i != -1;i = e[i].next)
{
int v = e[i].t;
if(v == 0)
continue;
if(vis[v] == 0)
{
if(color[u] == 1)
{
color[v] = 2;
sum[2]++;
vis[v] = 1;
q.push(v);
}
else if(color[u] == 2)
{
color[v] = 1;
sum[1]++;
vis[v] = 1;
q.push(v);
}

}
else
{
if(color[v] == color[u])
{
motherfucker = 1;
}
}

}
}
}

int main()
{
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i = 1;i <= m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
build(a,b);
build(b,a);
}
vis[0] = 1;
for(int i = 1;i <= n;i++)
{
sum[1] = sum[2] = 0;
if(vis[i] == 0)
{
bfs(i);
ans += min(sum[1],sum[2]);
}
}
if(motherfucker == 1)
{
printf("Impossible\n");
return 0;
}
printf("%d\n",ans);

return 0;
}


THE END

By Peacefuldoge

http://blog.csdn.net/loi_peacefuldog
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息