【BFS】CODE[VS] 2594 解药还是毒药 (状态压缩优化BFS)

点击进入Smart制药坊


关于状压:可以先看我之前写的一篇

这里我们用一个数的二进制位表示的是,当前状态下患有什么病,初始化全患上
例如01011,就是 (不患,患,不患,患,患)
这里我们用到^(异或)运算符
1^1 = 0
1^0 = 1
0^0 = 0
0^1 = 1
所以每当我们取一种药的时候,就枚举这个药可以治疗的病,若& = 1,我们就与该位置^ = 0,反之若会患上该病,也是这样^ = 1,表示患上该病

代码如下:

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

const int maxn = 300;

using namespace std;

int n,m;
int sum;
int dist[2048];
bool inq[2048];
int cc[maxn][maxn];

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

return f*data;
}

queue<int >q;

inline void bfs(int x)
{
    memset(dist,0,sizeof(dist));
    memset(inq,0,sizeof(inq));
    q.push(x);  
    inq[x] = 1;
    dist[x] = 0;
    while(!q.empty())
    {
        int now = q.front();
        q.pop();
        for(int i = 1;i <= m;i++)
        {
            int k = now;
            for(int j = 0;j < n;j++)
            {
                if(cc[i][j] == 1) {if(k&(1 << j)) k = k^(1 << j);}
                else if(cc[i][j] == -1) {if(!(k&(1 << j))) k = k^(1 << j);}
            }
            //cout<<k<<endl;
            //cout<<"dist of k is "<<dist[k]<<endl; 
            if(!inq[k])
            {
                dist[k] = dist[now]+1;
                inq[k] = 1;
                q.push(k);
            }
            //cout<<k<<endl; 
            if(k == 0)
            {
                printf("%d\n",dist[k]);
                exit(0) ;
            }
        }   

    }
    printf("The patient will be dead.\n");
    return ;
}

int main()
{
    n = read();
    m = read();
    for(int i = 1;i <= m;i++)
        for(int j = 0;j < n;j++)
            cc[i][j] = read();
    //cout<<(1 << n)-1<<endl;
    bfs((1 << n)-1);    
return 0;
}

THE END

By Peacefuldoge

http://blog.csdn.net/loi_peacefuldog?viewmode=list

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值