USACO 2.3.3 Zero Sum 解题报告
Zero Sum
Consider the sequence of digits from 1 through N (where N=9) in increasing order: 1 2 3 ... N.
Now insert either a `+' for addition or a `-' for subtraction or a ` ' [blank] to run the digits together between each pair of digits (not in front of the first digit). Calculate the result that of the expression and see if you get zero.
Write a program that will find all sequences of length N that produce a zero sum.
PROGRAM NAME: zerosum
INPUT FORMAT
A single line with the integer N (3 <= N <= 9).
SAMPLE INPUT (file zerosum.in)
7
OUTPUT FORMAT
In ASCII order, show each sequence that can create 0 sum with a `+', `-', or ` ' between each pair of numbers.
SAMPLE OUTPUT (file zerosum.out)
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
题目意思很简单个,就是在序列1…N中每两个连续的数字间指定一个操作符(+、-或空格),使得最后的结果为0 输出这样的结果(有多个就按ASCII 码的顺序输出)
这题可以用DFS直接求解,通过在每两个连续的数间指定可能的运算符(按空格,+,-的顺序指定)。当运算到最后一个数时如果结果为0,则输出
参考代码
/* ID:shiryuw1 PROG:zerosum LANG:C++ */ #include<iostream> #include<cstdlib> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int n; struct prog{ char c[10]; int pre; int next; char op; int k; }; int add (int a,int b,char c) { switch(c) { case 0:return a;break; case '+':return a+b;break; case '-':return a-b;break; } } void DFS(prog ans) { int i; if(ans.k==n) { if(add(ans.pre,ans.next,ans.op)==0) { for(i=1;i<=n;i++) { if(i!=1) cout<<ans.c[i]; cout<<i; } cout<<endl; } return ; } ans.k++; prog tmp; if(ans.op==0) { tmp=ans; tmp.c[tmp.k]=' '; tmp.pre=tmp.pre*10+tmp.k; DFS(tmp); tmp=ans; tmp.c[tmp.k]='+'; tmp.next=tmp.k; tmp.op='+'; DFS(tmp); tmp=ans; tmp.c[tmp.k]='-'; tmp.next=tmp.k; tmp.op='-'; DFS(tmp); } else { tmp=ans; tmp.c[tmp.k]=' '; tmp.next=tmp.next*10+tmp.k; DFS(tmp); tmp=ans; tmp.c[tmp.k]='+'; tmp.pre=add(tmp.pre,tmp.next,tmp.op); tmp.next=tmp.k; tmp.op='+'; DFS(tmp); tmp=ans; tmp.c[tmp.k]='-'; tmp.pre=add(tmp.pre,tmp.next,tmp.op); tmp.next=ans.k; tmp.op='-'; DFS(tmp); } } int main() { freopen("zerosum.in","r",stdin); freopen("zerosum.out","w",stdout); cin>>n; prog ans; ans.k=1; ans.pre=1; ans.op=0; ans.next=0; ans.c[0]=0; DFS(ans); return 0; }
作者:ACShiryu
出处:http://www.cnblogs.com/ACShiryu/
若非注明,本博客文章均为原创,版权归作者和博客园共有,欢迎转载,但必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
该文章也同步发布在我的新浪微博中-ACShiryu's weibo,欢迎收听。