单点时限: 2.0 sec
内存限制: 512 MB
问题描述
Merchants measured many commodities using weights and a two-pan balance. If you are using a limited set of weights, however, you can only measure certain quantities accurately. For example, suppose that you have only two weights: a 1-ounce weight and a 3-ounce weight. With these you can easily measure out 4 ounces, as shown in Figure1.
It is somewhat more interesting to discover that you can also measure out 2 ounces by shifting the 1-ounce weight to the other side, as shown in Figure2.
Write a program to determine whether it is possible to measure out the desired target amount with a given set of weights.
输入格式
The first line contains an integers n (1≤n≤10) – the size of the given set of weights.
The second line contains n integers (w1,w2,…,wn )(1≤wi≤100)
输出格式
输出格式
Output a binary string s, s.t.:
Note that s is 1-indexed.
样例:
input:
3 3 5 9
output:
11111111101101001
问题分析:
递归问题,枚举每个砝码放置的位置
判断 ( 物品重量 + 左边砝码 – 右边砝码 ) ==0 ?
枚举每个砝码的三种可能(放左边,放右边,不放),
每个砝码放置后,判断当前称重是否等于0?
代码解决部分:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef long long int lli;
int isPossible(int* w,int n,int target)
{
int x[]={1,-1,0};
int r=0,i;
if(target==0) return 1;
if(n==0) return 0;
for(i=0;i<3;i++)
{
r=isPossible(w+1,n-1,target+x[i]*w[0]);
if(r==1) return 1;
}
return 0;
}
int main()
{
int n,w[100];
int sum=0,target;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",w+i);
sum+=w[i];
}
for(int target=1;target<=sum;target++)
{
printf("%d",isPossible(w,n,target));
}
system("pause");
return 0;
}