Zero Sum
来源:互联网 发布:mac开机显示问号文件夹 编辑:程序博客网 时间:2024/06/05 14:10
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
题解 回溯法,回溯每一空的符号
#include<cstdlib>
#include<cstdio>#include<iostream>
void tt(int,int,int,int);
void out();
int a[10];
int n;
int main()
{
freopen("zerosum.in","r",stdin);
freopen("zerosum.out","w",stdout);
scanf("%d",&n);
tt(2,0,1,1);
return 0;
}
void out()//输出
{
printf("%d",1);
for (int i=2;i<=n;i++) //
{
if (a[i]==2) printf("%c",'+');
if (a[i]==3) printf("%c",'-');
if (a[i]==1) printf("%c",' ');
printf("%d",i);
}
std::cout<<'\n';
return;
}
void tt(int x,int k,int p,int f)
{
if (x==n+1)//边界;
{
if (k+p*f==0) out();
return;
}
for (int i=1;i<=3;i++)//枚举
{
a[x]=i;
switch (i)
{
case 1:tt(x+1,k,p*10+x,f);
break;
case 2:tt(x+1,k+p*f,x,1);
break;
case 3:tt(x+1,k+p*f,x,-1);
break;
}
}
}
0 0
- Zero Sum
- Zero Sum
- 【其他】【USACO】Zero Sum
- usaco-zero sum
- usaco: Zero Sum
- USACO Zero Sum
- usaco Zero Sum
- [usaco]2.3 Zero Sum
- usaco2.33Zero Sum
- USACO:Zero Sum
- USACO-Zero Sum
- USACO--2.3Zero Sum
- USACO 2.3 Zero Sum
- Zero Sum(DFS)
- USACO-Zero Sum
- USACO 2.3 Zero Sum
- USACO :Zero Sum解题报告
- USACO 2.3.3 Zero Sum
- 单例饿汉式与懒汉式的区别
- 如果你是dj
- IOS 应用评论机制
- web性能测试基本性能指标
- 【转】[置顶] 女友的心酸考博路
- Zero Sum
- 第三周作业
- c++
- 分析C语言中函数调用
- 解决<dl-ssl.google.com> != <www.google.com>
- PHP imagick扩展使用心得
- linux常见命令
- viewpager+fragment 如何管理fragment
- JQuery里的原型prototype分析