USACO2.3.3--Zero Sum
2013-02-07 13:18
260 查看
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.
View Code
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+71+2-3-4+5+6-71-2 3+4+5+6+71-2 3-4 5+6 71-2+3+4-5+6-71-2-3-4-5+6+7题解:先对每个数字之间添加'+'或者'-'或者空格。这个可以用深搜实现。然后再对表达式求值,如果表达式的和为零,那么就是符合要求的,输出即可。
丑陋的代码o(╯□╰)o
View Code
/* ID:spcjv51 PROG:zerosum LANG:C */ #include<stdio.h> #include<string.h> int n; char ss[50]; void print() { char s[50]; int i,len,lr,j,ans; ans=0; strcpy(s,ss); len=strlen(s); i=1; lr=1; if(s[i]==' ') { lr=lr*10+s[i+1]-'0'; j=i+2; while(s[j]==' ') { lr=lr*10+s[j+1]-'0'; j+=2; } i=j; } ans+=lr; while(i<len) { if(s[i]=='-') { j=i+2; lr=s[i+1]-'0'; while(s[j]==' ') { lr=lr*10+s[j+1]-'0'; j+=2; } i=j; ans-=lr; } if(s[i]=='+') { j=i+2; lr=s[i+1]-'0'; while(s[j]==' ') { lr=lr*10+s[j+1]-'0'; j+=2; } i=j; ans+=lr; } } if(ans==0) printf("%s\n",ss); } void dfs(int step,int last) { char str[3],ssr[50]; if(step==n) { print(); return; } sprintf(str,"%d",step+1); last=last*10+step+1; strcpy(ssr,ss); strcat(ss," "); strcat(ss,str); dfs(step+1,last); strcpy(ss,ssr); strcat(ss,"+"); strcat(ss,str); last=step+1; dfs(step+1,last); strcpy(ss,ssr); strcat(ss,"-"); strcat(ss,str); last=-(step+1); dfs(step+1,last); strcpy(ss,ssr); } int main(void) { freopen("zerosum.in","r",stdin); freopen("zerosum.out","w",stdout); scanf("%d",&n); strcpy(ss,"1"); dfs(1,1); return 0; }
相关文章推荐
- USACO2.3.3 Zero Sum (zerosum)
- USACO 2.3.3 Zero Sum
- Zero Sum_usaco2.3.3_dfs
- USACO 2.3.3 Zero Sum
- USACO2.3.3 Zero Sum (zerosum)
- JZOJ1268.【USACO题库】2.3.3 Zero Sum和为零
- USACO 2.3.3 Zero Sum 解题报告
- 1031. 【USACO题库】2.3.3 Zero Sum和为零
- USACO 2.3.3 Zero Sum
- 【USACO题库】2.3.3 Zero Sum和为零
- 【USACO题库】2.3.3 Zero Sum和为零
- USACO 2.3.3 Zero Sum
- USACO-Zero Sum
- usaco2.33Zero Sum
- USACO 2.3 Zero Sum
- USACO 2.3.3 罗马数字
- USACO-Zero Sum
- usaco-zero sum
- usaco 2.3.3 zerosum
- USACO:Zero Sum