砝码称重

题目描述

5个砝码,用天平称重时,我们希望用尽可能少的砝码组合称出尽可能多的重量。

如果只有 5个砝码,重量分别是 1392781。则它们可以组合称出 1 到 121 之间任意整数重量(砝码允许放在左右两个盘中)。

本题目要求编程实现:对用户给定的重量,给出砝码组合方案。

输入输出样例

样例输入 #1

1

样例输出 #1

1

样例输入 #2

5

样例输出 #2

9-3-1

样例输入 #3

19

样例输出 #3

27-9+1

提示

要求程序输出的组合总是大数在前小数在后。

可以假设用户的输入的数字符合范围1~121。

这题两个方法,搜索和贪心,第一个是搜索第二个是贪心哦(发出来单纯是因为我在这题耗了40多分钟)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=100;
 4 int n,a[5]={1,3,9,27,81},f[N];
 5 string s;
 6 bool vis;
 7 void dfs(int st,int t,int num,int step)
 8 {
 9     if(vis) return;
10     if(num==t)
11     {
12         for(int i=0;i<step+1;i++)
13         {
14             if(i<step) cout<<f[i]<<s[i];
15             else cout<<f[i];
16         }
17         vis=true;
18     }
19     if(num>t) for(int i=st-1;i>=0;i--)
20     {
21         f[step+1]=a[i],s[step]='-';
22         dfs(i,t,num-a[i],step+1);
23         f[step+1]=0;
24     }
25     else for(int i=st-1;i>=0;i--)
26     {
27         f[step+1]=a[i],s[step]='+';
28         dfs(i,t,num+a[i],step+1);
29         f[step+1]=0;
30     }
31     return;
32 }
33 int main()
34 {
35     cin>>n;
36     int p;
37     if(n<=81)
38     {for(int i=0;i<5;i++) if(a[i]>=n){p=i;break;}}
39     else p=4;
40     f[0]=a[p];
41     dfs(p,n,a[p],0);
42     return 0;
43 }
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=100000;
 4 int n,k,res,a[5]={1,3,9,27,81};
 5 int main()
 6 {
 7     cin>>n;
 8     if(n<=81)
 9     {for(int i=0;i<5;i++) if(a[i]>=n) {k=i;break;}}//找到最接近的
10     else k=4;
11     res=a[k];
12     cout<<a[k];
13     int num=0;
14     while(res!=n)
15     {
16         int x,c;
17         for(int i=0;i<4;i++)
18             if(a[i]<=abs(n-res)&&a[i+1]>=abs(n-res)) {x=i;break;}//找到处于这之间的
19         if(abs(a[x]-res+n)>abs(a[x+1]-res+n)) c=x+1;//找到最接近的那个
20         else c=x;
21         if(res>n) cout<<'-'<<a[c],res-=a[c];//判断
22         else cout<<'+'<<a[c],res+=a[c];
23     }
24     return 0;
25 }

 

 

posted @ 2023-05-27 18:39  o-Sakurajimamai-o  阅读(84)  评论(0)    收藏  举报
-- --