POJ 1950 dfs

http://poj.org/problem?id=1950

题意:就是1~N的数加上符号,是最后结果为0,‘+' , '-' , '.'其中'.'不是乘号 如1.2表示12

读完题觉得很一般,但是做的时候被绕进去了

代码:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
char ch[3]={'+','-','.'};
int a[20],b[20];
long long pre[20];
int n,cnt;

void dfs(int pos,long long ans)
{
    int i,j,k;
    if(pos==n&&ans!=0)return ;

    if(pos==n&&ans==0)
    {
        cnt++;
        if(cnt>20)return ;
        for(i=1;i<n;i++)
           printf("%d %c ",a[i],ch[b[i]]);
        printf("%d\n",a[i]);
        return;
    }

    pos++;
    int f1,f2;
    if(pos>1)
    {
         f1=b[pos-1];
         int h,H;
         if(f1==0) ans+=a[pos],pre[pos+1]=a[pos];
         if(f1==1) ans-=a[pos],pre[pos+1]=a[pos];

         if(f1==2)
         {
           f2=b[pos-2];
           h=pre[pos];//i的前一个数
           if(a[pos]<10)  H=h*10+a[pos];
           if(a[pos]>=10)  H=h*100+a[pos];
           if(f2==0){ans-=h;ans+=H;}
           if(f2==1){ans+=h;ans-=H;}
           if(f2==2)
           {
               int p=pos-2;
               while(f2==2)
               {
                   f2=b[--p];
               }
               if(f2==0){ans-=h;ans+=H;}
               if(f2==1){ans+=h;ans-=H;}
           }
           pre[pos+1]=H;
         }
    }
    if(pos==1)
    {
        ans=a[1];
        pre[2]=a[1];
    }
    if(pos==n) dfs(pos,ans);
    if(pos<n)
    {
       for(j=0;j<3;j++)
      {
        b[pos]=j;
        dfs(pos,ans);
      }
    }

    return ;
}

int main()
{
   int i;
   while(~scanf("%d",&n))
   {
       for(i=1;i<=n;i++)
          a[i]=i;
       cnt=0;
       b[0]=0;
       dfs(0,0);
       printf("%d\n",cnt);
   }
   return 0;
}

  

posted @ 2012-03-25 12:35  快乐.  阅读(163)  评论(0编辑  收藏  举报