1330 封锁阳光大学
封锁尽量多的路,并且不发生冲突,很明显是个二分图
和关押罪犯有点像
首先,我们要明白,这个图不一定联通,那么我们就能将这个图,切开成多个子图进行处理,那么如果是一个连通图,怎么切割?!
不要慌张,先理解,每一条边都有且仅有一个被它所连接的点被选中
所以相邻的点连成不同的颜色
#include<cstdio>
#include<iostream>
#include<cmath>
#include<string>
#include<string>
#include<algorithm>
using namespace std;
struct Edge
{
int t;
int nexty;
}edge[200000];
int head[20000];
int cnt=0;
void add(int a,int b)//邻接表
{
cnt++;
edge[cnt].t=b;
edge[cnt].nexty=head[a];
head[a]=cnt;
}
bool used[20000]={0};//标记
int col[20000]={0};//每一个点的颜色
int sum[2];//两种染色的点数
bool dfs(int node,int color)//染色
{
if(used[node])//已经被染色,跳过
{
if(col[node]==color)return true;//原来的颜色
return false;//冲突,不可行
}
used[node]=true;//标记染色
sum[col[node]=color]++;//记录颜色个数
bool tf=true;//旗帜
for(int i=head[node];i!=0&&tf;i=edge[i].nexty)//遍历连边
{
tf=tf&&dfs(edge[i].t,1-color);//是否可以继续染色
}
return tf;//判断
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int a,b;
while(m--)
{
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);//反向存储
}
int ans=0;
for(int i=1;i<=n;i++)
{
if(used[i])continue;//如果此点已被包含为一个已经被遍历过的子图,则不需重复遍历
sum[0]=sum[1]=0;//初始化
if(!dfs(i,0))//如果不能染色
{
printf("Impossible");
return 0;//结束程序
}
ans+=min(sum[0],sum[1]);//取最小值
}
printf("%d",ans);
return 0;
}
图论应用:二分图染色问题
本文探讨了一种图论问题,即如何在不引起冲突的情况下封锁阳光大学的路径,将其转换为二分图染色问题。通过邻接表建立图,并采用深度优先搜索实现染色算法,寻找最小封锁数量。若图不连通,可以分别处理子图。最终,程序计算并输出了最少需要封锁的路径数。
1169

被折叠的 条评论
为什么被折叠?



