• usaco-2.3-zerosum-pass


    递归,递归:

    /*
    ID: qq104801
    LANG: C++
    TASK: zerosum
    */
    
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    int N;
    
    void dfs(int n,int sum,int curr,vector<char> path)
    {
        if(n==N)
        {
            if(sum+curr==0)
            {
                for(int i=1;i<n;++i)
                    cout<<i<<path[i];
                cout<<N<<endl;
            }
        }
        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);
        }
    }
    
    void test()
    {    
        freopen("zerosum.in","r",stdin);
        freopen("zerosum.out","w",stdout);
        cin>>N;
        vector<char> start(N,0);
        dfs(1,0,1,start);
    }
    
    int main () 
    {        
        test();        
        return 0;
    }

    test data:

    USER: cn tom [qq104801]
    TASK: zerosum
    LANG: C++
    
    Compiling...
    Compile: OK
    
    Executing...
       Test 1: TEST OK [0.011 secs, 3516 KB]
       Test 2: TEST OK [0.003 secs, 3516 KB]
       Test 3: TEST OK [0.003 secs, 3516 KB]
       Test 4: TEST OK [0.003 secs, 3516 KB]
       Test 5: TEST OK [0.003 secs, 3516 KB]
       Test 6: TEST OK [0.008 secs, 3516 KB]
       Test 7: TEST OK [0.011 secs, 3516 KB]
    
    All tests OK.
    
    YOUR PROGRAM ('zerosum') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations.
    
    Here are the test data inputs:
    
    ------- test 1 ----
    3
    ------- test 2 ----
    4
    ------- test 3 ----
    5
    ------- test 4 ----
    6
    ------- test 5 ----
    7
    ------- test 6 ----
    8
    ------- test 7 ----
    9
    
    Keep up the good work!
    Thanks for your submission!
    /***********************************************

    看书看原版,原汁原味。

    不会英文?没关系,硬着头皮看下去慢慢熟练,才会有真正收获。

    没有原书,也要网上找PDF来看。

    网上的原版资料多了去了,下载东西也到原始下载点去看看。

    你会知其所以然,呵呵。

    ***********************************************/

  • 相关阅读:
    2013年元旦新年好
    2012第52周三阴雨
    2013第1周四雪
    2013年元旦新年好
    2013第1周三阴冷
    2012第52周日晴冷
    2012周六补记
    PHP怎么调用其他类的方法
    面向对象复习笔记(一)
    Laravel 引入自定义类库或第三方类库
  • 原文地址:https://www.cnblogs.com/dpblue/p/3958051.html
Copyright © 2020-2023  润新知