蓝桥杯——分考场

题目链接

思路:将每个学生抽象成点,联系抽象成边,构造无向图,把教室抽象成点要上的颜色,于是这道题就是图染色问题,求图的色数。可以用DFS搜索。

#include <bits/stdc++.h>

using namespace std;
const int maxn = 110;
int G[maxn][maxn],color[maxn],ans=maxn,n;

bool judge(int v,int Color)
{
    for(int i=1;i<=n;i++)
        if(G[v][i]&&color[i]==Color)
            return false;
    return true;
}

void dfs(int v,int cnt)
{
    if(cnt>=ans)//剪枝
        return;

    if(v>n)
    {
        ans=min(ans,cnt);//更新答案
        return;
    }

    for(int i=1;i<=cnt;i++)//遍历当前的所有颜色
    {
        if(judge(v,i))//判断当前点是否能上这个颜色
        {
            color[v]=i;
            dfs(v+1,cnt);
        }
    }
    //当前点上新的颜色,这种情况也有可能产生最优解
    color[v]=cnt+1;
    dfs(v+1,cnt+1);
    color[v]=0;
}
int main()
{
    int k,x,y;
    cin>>n>>k;
    for(int i=0;i<k;i++)
    {
        cin>>x>>y;
        G[x][y]=G[y][x]=1;
    }
    dfs(1,0);
    cout<<ans;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值