标签:
给一个N 表示1 2 3 ...N
求出所有 zero sum的情况
【简单Dfs 即可】 运算结果的时候我使用了一个stack...
比如N = 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 1-2-3-4-5+6+7
Source Code:
/* ID: wushuai2 PROG: zerosum LANG: C++ */ //#pragma comment(linker, "/STACK:16777216") //for c++ Compiler #include <stdio.h> #include <iostream> #include <fstream> #include <cstring> #include <cmath> #include <stack> #include <string> #include <map> #include <set> #include <list> #include <queue> #include <vector> #include <algorithm> #define Max(a,b) (((a) > (b)) ? (a) : (b)) #define Min(a,b) (((a) < (b)) ? (a) : (b)) #define Abs(x) (((x) > 0) ? (x) : (-(x))) #define MOD 1000000007 #define pi acos(-1.0) #define RV(num) ((num) > 0 ? 0 : 1) using namespace std; typedef long long ll ; typedef unsigned long long ull ; typedef unsigned int uint ; typedef unsigned char uchar ; template<class T> inline void checkmin(T &a,T b){if(a>b) a=b;} template<class T> inline void checkmax(T &a,T b){if(a<b) a=b;} const double eps = 1e-7 ; const int M = 660000 ; const ll P = 10000000097ll ; const int INF = 0x3f3f3f3f ; const int MAX_N = 20 ; const int MAXSIZE = 101000000; ofstream fout ("zerosum.out"); ifstream fin ("zerosum.in"); int N, b[11]; void solve(){ int i, j, t; vector <int> vec; vec.push_back(1); for(i = 2; i <= N; ++i){ int num = vec[vec.size() - 1]; if(num < 0){ num = vec[vec.size() - 2]; } if(b[i] == 1){ vec.pop_back(); vec.push_back(num * 10 + i); } else if(b[i] == 2){ vec.push_back(-1); vec.push_back(i); } else if(b[i] == 3){ vec.push_back(-2); vec.push_back(i); } else{ vec.push_back(i); } } int ans = vec[0]; for(i = 1; i < vec.size(); i += 2){ if(vec[i] == -1){ ans += vec[i + 1]; } else if(vec[i] == -2){ ans -= vec[i + 1]; } } if(ans == 0){ fout << 1; for(i = 2; i <= N; ++i){ if(b[i] == 1) fout << ‘ ‘; else if(b[i] == 2) fout << ‘+‘; else if(b[i] == 3) fout << ‘-‘; fout << i; } fout << endl; } } void change(int n){ int i, j; if(n == N + 1){ solve(); return; } for(i = 1; i <= 3; ++i){ b[n] = i; change(n + 1); } } int main() { int i, j, k, l, m, n, t, s, c, w, q, num; fin >> N; for(i = 2; i <= N; ++i){ b[i] = 1; } change(2); fin.close(); fout.close(); return 0; }
标签:
原文地址:http://www.cnblogs.com/wushuaiyi/p/4297202.html