您的位置:首页 > 其它

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.

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: