享受遞歸的瀟灑 USACO zerosum


/*
ID:fairyroad
TASK:zerosum
LANG:C++
*/
#include<fstream>
#include<vector>
using namespace std;
ifstream fin("zerosum.in");
ofstream fout("zerosum.out");

int N;

void dfs(int n, int sum, int curr, vector<char> path) // vector passed by value
{
    if(n==N)
    {
        if(sum+curr == 0)
        {
            for(int i = 1; i < N; ++i)
                fout<<i<<path[i];
            fout<<N<<"\n";
        }
        return;
    }
    else
    {
        const int next = n+1;

        path[n] = ' ';
        dfs(n+1, sum, curr*10+(curr>0?next:-next), path);

        path[n] = '+';
        dfs(n+1, sum+curr, next, path);

        path[n] = '-';
        dfs(n+1, sum+curr, -next, path);
    }
}

int main()
{
    fin>>N;
    vector<char> start(N, 0);

    dfs(1, 0, 1, start);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章