poj 1176 Party Lamps dfs

从下午比赛加写这道题写到现在,实在是眼冒金星了,特别是这道题,把我写惨了,一个小错找了半天啊,半天..

而且,代码写的好烂..

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

int n,m,a,b,flag,k;
int on[105],off[105],lamp[105];

struct node{
	char s[105];
}keep[100];

int cmp(node ar,node br)
{
	return strcmp(ar.s,br.s)<0;
}

void f(int x)
{
	int i;
	if(x==1)
	{
		for(i=1;i<=m;i++)
			if(lamp[i]==0)lamp[i]=1;
			else lamp[i]=0;
	}
	else if(x==2)
	{
		for(i=1;i<=m;i++)
			if(i%2==1)
			{
				if(lamp[i]==0)lamp[i]=1;
				else lamp[i]=0;
			}
	}
	else if(x==3)
	{
		for(i=1;i<=m;i++)
			if(i%2==0)
			{
				if(lamp[i]==0)lamp[i]=1;
				else lamp[i]=0;
			}
	}
	else
	{
		for(i=0;i*3+1<=m;i++)
			if(lamp[i*3+1]==0)lamp[i*3+1]=1;
			else lamp[i*3+1]=0;
	}
}

int ju()
{
	int i;
	char str[105];
	for(i=1;i<=m;i++)
		str[i-1]=lamp[i]+'0';
	str[m]='\0';
	for(i=0;i<k;i++)
	{
		if(strcmp(str,keep[i].s)==0)return 0;
	}
	strcpy(keep[k].s,str);
	k++;
	return 1;
}

int judge()
{
	int i;
	for (i=1;i<b-1;i++)
		if(lamp[off[i]]==1)return 0;
	for (i=1;i<a-1;i++)
		if(lamp[on[i]]==0)return 0;
	if(!ju())return 0;
	return 1;
}

void dfs(int i)
{
	int j;
	if(i==n)
	{
		if(judge())flag=1;
		return;
	}
	for (j=1;j<=4;j++)
	{
		f(j);
		dfs(i+1);
		f(j);
	}
}

int main()
{
	int i;
	while (scanf("%d",&m)!=EOF)
	{
		scanf("%d",&n);
		a=b=0;
		while(on[a++]!=-1)scanf("%d",&on[a]);
		while(off[b++]!=-1)scanf("%d",&off[b]);
		if(n>4)
		{
			if(n%2)n=3;
			else n=4;
		}
		for(i=1;i<=m;i++)lamp[i]=1;
		flag=k=0;
		dfs(0);
		if(!flag)printf("IMPOSSIBLE\n");
		else
		{
			sort(keep,keep+k,cmp);
			for (i=0;i<k;i++)
			{
				printf("%s\n",keep[i].s);
			}
		}
	}
	return 0;
}
posted @ 2011-10-22 23:02  104_gogo  阅读(317)  评论(0编辑  收藏  举报