题目链接:点击打开链接
Jim has a balance and N weights. (1≤N≤20)
The balance can only tell whether things on different side are the same weight.
Weights can be put on left side or right side arbitrarily.
Please tell whether the balance can measure an object of weight M.
For each test case :
The first line is N, means the number of weights.
The second line are N number, i'th number wi(1≤wi≤100) means the i'th weight's weight is wi.
The third line is a number M. Mis the weight of the object being measured. Output You should output the "YES"or"NO". Sample Input
1 2 1 4 3 2 4 5Sample Output
NO YES YESHint
For the Case 1:Put the 4 weight alone For the Case 2:Put the 4 weight and 1 weight on both side
先记一下我的深搜代码吧
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=1e5+5;
typedef long long LL;
int a[25],n,flag,weight;
void dfs(int step,int ans)
{
if(ans==weight)
{
printf("YES\n");
flag=1;
return ;
}
if(step==n||flag)
return ;
for(int i=0;i<3;i++)
{
if(i==0)
{
ans+=a[step];
dfs(step+1,ans);
}
if(i==1)
{
ans-=a[step];
dfs(step+1,ans);
}
if(i==2)
dfs(step+1,ans);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int m;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
flag=0;
scanf("%d",&weight);
dfs(0,0);
if(flag==0)
printf("NO\n");
}
}
}
暴力打表
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
bool vis1[2010],vis2[2010];
int a[2010];
int main()
{
int t,m,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
memset(vis1,false,sizeof(vis1));
memset(vis2,false,sizeof(vis2));
vis1[0]=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<=2000;j++)
{
if(vis1[j])
{
vis2[j]=true;
vis2[a[i]+j]=true;
vis2[abs(a[i]-j)]=true;
}
}
for(int j=0;j<=2000;j++)
{
vis1[j]=vis2[j];
// vis2[j]=0;
}
}
int m;
scanf("%d",&m);
while(m--)
{
int p;
scanf("%d",&p);
if(vis1[p])
printf("YES\n");
else printf("NO\n");
}
}
}
神奇的DP
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[22][4110];
int main()
{
int t,m,n,a[22];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
memset(dp,0,sizeof(dp));
dp[0][2000]=1;
for(int i=0;i<n;i++)
{
for(int j=a[i];j<=4000-a[i];j++)
{
if(dp[i][j])//i代表第几种重量的砝码,j代表该种硬币可以确定的重量
{
//由上一种重量传递到下一种重量,一直这样承接下去,最后dp[n][]是否为真即可
dp[i+1][j]=1;
dp[i+1][j+a[i]]=1;
dp[i+1][j-a[i]]=1;
}
}
}
scanf("%d",&m);
while(m--)
{
int p;
scanf("%d",&p);
if(dp[n][2000-p]||dp[n][2000+p])
printf("YES\n");
else printf("NO\n");
}
}
}