美文网首页
PROB:zerosum

PROB:zerosum

作者: SylviaShen | 来源:发表于2017-08-25 19:16 被阅读0次

    题目来自 USACO
    题目翻译见 nocow


    题目很简单,自己都说了让我们暴搜。

    运算符最多 8 个,每个 3 种,果然大家都是 0.000 sec 就 AC 了。

    我这边也写得丑丑的。递归搜索(注意下 ascii 码顺序)。对表达式进行解析计算(我也不知道我怎么写的这一段,竟然就通过了),记录下左边的值、操作符、右边的值,如果下一个操作符是空格,就给右边添一位,是加减就把上次操作做了,记录新的操作符和右边。

    /*
    ID: 
    LANG: C++
    TASK: zerosum
    */
    
    #include <cstdio>
    #include <cstdlib>
    
    int N;
    FILE *fout;
    char operations[8];
    
    int parse(){
        char op = '+';
        int pre = 0, post = 1;
        for(int n = 2; n <= N; n ++){
            if(operations[n - 2] == ' '){
                post = post * 10 + n;
            }else{
                pre = (op == '+'? pre + post: pre - post);
                op = operations[n - 2];
                post = n;
            }   
        }
        pre = (op == '+'? pre + post: pre - post);
        return pre;
    }
    
    void search(int i){
        if(i == N - 1){
            if(parse() == 0){
                for(int i = 1; i < N; i ++)
                    fprintf(fout, "%d%c", i, operations[i - 1]);
                fprintf(fout, "%d\n", N);
            }
            return;
        }
        operations[i] = ' '; search(i + 1);
        operations[i] = '+'; search(i + 1);
        operations[i] = '-'; search(i + 1);
    }
    
    int main(){
        FILE *fin = fopen("zerosum.in", "r");
        fout = fopen("zerosum.out", "w");
    
        fscanf(fin, "%d", &N);
    
        search(0);
    
        return 0;
    }
    

    第一次提交 AC:

    Compiling...
    Compile: OK
    
    Executing...
       Test 1: TEST OK [0.000 secs, 4176 KB]
       Test 2: TEST OK [0.000 secs, 4176 KB]
       Test 3: TEST OK [0.000 secs, 4176 KB]
       Test 4: TEST OK [0.000 secs, 4176 KB]
       Test 5: TEST OK [0.000 secs, 4176 KB]
       Test 6: TEST OK [0.000 secs, 4176 KB]
       Test 7: TEST OK [0.000 secs, 4176 KB]
    
    All tests OK.
    

    相关文章

      网友评论

          本文标题:PROB:zerosum

          本文链接:https://www.haomeiwen.com/subject/sblpdxtx.html