USACO-Zero Sum

来源:http://ace.delos.com/usacoprob2?a=UGksUWcO9ZG&S=zerosum

简单的DFS,秒杀。

主要是不清楚C++中是否有函数可以直接计算表达式,所以自己写了个简单的计算函数。

搜索时按照空格,加号,减号的顺序,连排序都省了。

/*
ID:ay27272
PROG:zerosum
LANG:C++
*/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>

using namespace std;

int n,sum;
string result[100];
string f;

int number(int h,int &i)   //返回一个数字,包括空格的处理,当然当前处理到的位置也要返回,所以用了一个i的引用
{
    int x=0;
    i=h;
    while (i<f.length() && f[i]!='+' && f[i]!='-')
    {
        if (f[i]!=' ')
            x=x*10+int(f[i]-'0');
        i++;
    }
    return x;
}

bool calc() //直接按照运算符号进行运算
{
    int i,x=number(0,i);
    int temp,k;
    while (i<f.length())
    {
        k=i;
        temp=number(i+1,i);
        if (f[k]=='+') x+=temp;
        else if (f[k]=='-') x-=temp;
    }
    return !x;
}

void dfs(int x)
{
    if (x>n)
    {
        if (calc())
            result[++sum]=f;
        return;
    }
    string tmp=f;

    f=f+' '+char(x+'0');
    dfs(x+1);
    f=tmp;

    f=f+'+'+char(x+'0');
    dfs(x+1);
    f=tmp;

    f=f+'-'+char(x+'0');
    dfs(x+1);
    f=tmp;
}

int main()
{
    freopen("zerosum.in","r",stdin);
    freopen("zerosum.out","w",stdout);
    cin>>n;
    sum=0;
    f="1";
    dfs(2);

    for (int i=1;i<=sum;i++)
        cout<<result[i]<<endl;

    return 0;
}
posted @ 2012-11-17 00:34  ay27  阅读(175)  评论(0编辑  收藏  举报