输入正整数t,n,然后是n个正整数(单调非递增),若n个数中某几个数的和是t,输出这些加法表达式(表达式不重复输出),无解输出NONE
2015-11-25 18:15
429 查看
输入:
4 7 4 4 3 2 2 1 1
输出:
Sum of 4:
4
3+1
2+2
2+1+1
输入:
5 3 2 1 1
输出:
sum of 5:
NONE
#include<stdio.h>
int a[100],b[100],c[100],sum[100];
int n,t,ans,last;
//bool tr;
void dfs(int s,int tt,int x)
{
int i;
if(x>t)
return;
if(t-x>sum[tt])
return;
if(x==t)
{
ans++;
for(i=0;i<tt-1;i++)
printf("%d+",b[i]);
printf("%d\n",b[i]);
last=b[i];
return;
}
for(i=s;i<n;i++)
{
if((tt==0)&&(c[a[i]]!=0))
continue;
if(tt==0)
c[a[i]]=1;
if(last==a[i])
continue;
b[tt]=a[i];
dfs(i+1,tt+1,x+a[i]);
b[t]=0;
if(t==0)
c[a[i]]=0;
}
}
int main()
{
int i;
scanf("%d%d",&t,&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=n-1;i>=0;i--)
sum[i]=sum[i+1]+a[i];
dfs(0,0,0);
if(ans==0)
{
printf("NONE");
}
return 0;
}
4 7 4 4 3 2 2 1 1
输出:
Sum of 4:
4
3+1
2+2
2+1+1
输入:
5 3 2 1 1
输出:
sum of 5:
NONE
#include<stdio.h>
int a[100],b[100],c[100],sum[100];
int n,t,ans,last;
//bool tr;
void dfs(int s,int tt,int x)
{
int i;
if(x>t)
return;
if(t-x>sum[tt])
return;
if(x==t)
{
ans++;
for(i=0;i<tt-1;i++)
printf("%d+",b[i]);
printf("%d\n",b[i]);
last=b[i];
return;
}
for(i=s;i<n;i++)
{
if((tt==0)&&(c[a[i]]!=0))
continue;
if(tt==0)
c[a[i]]=1;
if(last==a[i])
continue;
b[tt]=a[i];
dfs(i+1,tt+1,x+a[i]);
b[t]=0;
if(t==0)
c[a[i]]=0;
}
}
int main()
{
int i;
scanf("%d%d",&t,&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=n-1;i>=0;i--)
sum[i]=sum[i+1]+a[i];
dfs(0,0,0);
if(ans==0)
{
printf("NONE");
}
return 0;
}
相关文章推荐
- js ajax 返回值问题
- Python正则表达式指南
- linux java环境搭建--安装jdk
- HNACM(六)--第二题 外星人的供给站
- Python3.4 django使用mysql
- swift中基本运算符的一些特性
- ajax跨域问题
- GridView的高度,嵌套使用注意
- HTTP协议/IIS 原理及ASP.NET运行机制浅析【图解】
- Android中visibility属性VISIBLE、INVISIBLE、GONE的区别
- 运维二
- 数据结构基础6.2:图的遍历
- redis的小测试工程
- 《Arithmetic Puzzles》
- linux下mysql中文乱码(中文问号)解决办法
- hdu 4496 D-City(并查集)
- 黑马程序员——泛型
- Web前端
- -lt -gt -ge -le -eq的意义
- [leetcode] Best Time to Buy and Sell Stock