[vijos1026]毒药?解药?

下面那个人完全暴露了我的兴趣啊!!!
叫你推荐个轻小说有必要这么公开处刑吗!!!

题目(vijos)
这题直接纯粹bfs就完事了。
当然,加个hash优化也是可以的,这样可以避免重复。
( ͡° ͜ʖ ͡° )

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
int n,m;
int a[105][15];
int vis[500005];
int ans;
struct node{
	int s[15];// 0表有病,1表正常
	int step;
}st,en;
int enval;
int mi(int a,int b)
{
	for (int i=1;i<=b;++i)
		a*=2;
	return a;
}
int code(node x)
{
	int tmp=1;int k=1;
	for (int i=1;i<=n;++i)
	{
		if (x.s[i]) tmp=tmp+mi(2,k);
		++k;
	}
	return tmp;
}
int bfs()
{
	queue <node> q;
	q.push(st);
	vis[code(st)]=1;
	while (!q.empty())
	{
		node u=q.front();
		q.pop();
		int hashu=code(u);
		if (hashu==enval) return u.step;
		for (int i=1;i<=m;++i)
		{
			node now=u;
			for (int j=1;j<=n;++j)
			{
				if (a[i][j]==-1)
				{
					if (now.s[j]==0) continue;
					if (now.s[j]==1) now.s[j]=0;
				}
				if (a[i][j]==0) continue;
				if (a[i][j]==1)
				{
					if (now.s[j]==0) now.s[j]=1;
					if (now.s[j]==1) continue;
				}
			}
			int hashnow=code(now);
			if (!vis[hashnow])
			{
				now.step=u.step+1;
				q.push(now);
				vis[hashnow]=1;
			}
		}
	}
	return -1;
}
int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<=m;++i)
		for (int j=1;j<=n;++j)
			scanf("%d",&a[i][j]);
	memset(st.s,0,sizeof st.s);
	for (int i=1;i<=n;++i)
		en.s[i]=1;
	enval=code(en);
	int ans=bfs();
	if (ans==-1)
		printf("The patient will be dead.");
	else
		printf("%d",ans);
	return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注