USACO Section 2.3 Zero Sum(dfs+双向队列)

Zero Sum

Consider the sequence of digits from 1 through N (where N=9) in increasing order: 1 2 3 ... N.

Now insert either a `+' for addition or a `-' for subtraction or a ` ' [blank] to run the digits together between each pair of digits (not in front of the first digit). Calculate the result that of the expression and see if you get zero.

Write a program that will find all sequences of length N that produce a zero sum.

PROGRAM NAME: zerosum

INPUT FORMAT

A single line with the integer N (3 <= N <= 9).

SAMPLE INPUT (file zerosum.in)

7

OUTPUT FORMAT

In ASCII order, show each sequence that can create 0 sum with a `+', `-', or ` ' between each pair of numbers.

SAMPLE OUTPUT (file zerosum.out)

1+2-3+4-5-6+7
1+2-3-4+5+6-7
1-2 3+4+5+6+7
1-2 3-4 5+6 7
1-2+3+4-5+6-7
1-2-3-4-5+6+7
题意:添加 '+'、'-'、' ' 这三个字符,使得最后结果为 0。把所以满足条件的方式都输出来。
分析:dfs 爆搜所有的情况。然后就是变成了给定符合判断是否等于 0,首先处理掉空格,然后再进行加减。
View Code
/*
  ID: dizzy_l1
  LANG: C++
  TASK: zerosum
*/
#include<iostream>
#include<queue>
#include<cstdio>

using namespace std;

int op[15],n;
char a[5]={'0',' ','+','-'};

bool judge()
{
    int i,t,sum=0;
    deque<int>dq1,dq2;
    dq1.push_back(1);
    for(i=1;i<n;i++)
    {
        if(op[i]==1)
        {
            t=dq1.back();dq1.pop_back();
            t=t*10+i+1;
            dq1.push_back(t);
        }
        else
        {
            dq1.push_back(i+1);
            dq2.push_back(op[i]);
        }
    }
    sum=dq1.front();dq1.pop_front();
    int tq1,tq2;
    while(!dq2.empty())
    {
        tq1=dq1.front();dq1.pop_front();
        tq2=dq2.front();dq2.pop_front();
        if(tq2==2) sum+=tq1;
        else if(tq2==3) sum-=tq1;
    }
    if(sum==0) return true;
    else return false;
}

void output()
{
    int i;
    for(i=1;i<n;i++)
    {
        printf("%d%c",i,a[op[i]]);
    }
    printf("%d\n",n);
}

void DFS(int p)
{
    int i;
    if(p==n)
    {
        if(judge())output();
        return ;
    }
    for(i=1;i<=3;i++)
    {
        op[p]=i;
        DFS(p+1);
    }
}

int main()
{
    freopen("zerosum.in","r",stdin);
    freopen("zerosum.out","w",stdout);
    while(scanf("%d",&n)==1)
    {
        DFS(1);
    }
    return 0;
}
posted @ 2012-09-05 14:00  mtry  阅读(661)  评论(0)    收藏  举报