Algorithm - Weigh once to find the number of defective boxes

Problem Description:

        There are 10 boxes of products, each box contains 1,000 pieces, and the genuine products are 100 grams each. Several of the boxes are defective products. Each piece of defective product is 10 grams lighter than the genuine product. I asked if I could use a scale to weigh just once to find out which boxes were defective products.

Algorithm analysis:

        Number the 10 boxes respectively. Take 2^0 pieces (1 piece) from box No. 1, 2^1 pieces (2 pieces) from box No. 2, 2^2 pieces (4 pieces) from box No. 3, and take 2^2 pieces (4 pieces) from box No. 4. 2^3 pieces (8 pieces)..., take 2^9 pieces (512 pieces) from box No. 10, and so on. Then use the variable w1 to store the ideal total weight, and w2 to store the actual total weight. Use w1-w2 to calculate the difference, and use the difference to find out which box number is defective (if it is defective, all 1,000 pieces in the box are defective).

        For example:

  • 轻10克1号箱为次品。(因为仅有1号箱取出一件,一件次品与正品的质量差为10g)

  • 轻20克2号箱为次品。(仅有2号箱是取出两件,而不能是一号箱和2号箱各一件,因为2号箱若有次品,则全部都为次品,不能为一正品一次品)

  • 轻30克1,2号箱为次品。

  • 轻40克3号箱为次品。

  • 轻50克1,3号箱为次品

        And so on (you can refer to the binary idea, for example, the difference of 50g means that 5 pieces are defective products, and the binary representation of 5 is 00000 00101, then boxes 1 and 3 are defective products, and the solution to this question is analogous to binary .Similarly, if the difference is 60g, then the binary number of 6 is 00000 00110, then boxes 3 and 2 are defective products)

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n;
    //用于输入箱子数量
    cout<<"输入箱子数量:";
    cin>>n;
    long w1 = 0; //用于存放理想总重量
    long w2 = 0; //用于存放实际称得重量
    int t = 1;
    //求出总件数
    for(int i=0;i<n;i++){
        w1 = w1 + t;
        cout<<i+1<<"号箱取出:"<<t<<"件"<<endl;
        t = t * 2;
    }
    //将总件数乘100g求出总的理想重量
    w1 = w1 * 100;
    cout<<"理想总重量为:"<<w1<<"g"<<endl;
    cout<<"请输入实际称得重量:";
    cin>>w2;
    //计算与实际重量差值
    w1 = w1 - w2;
    //求得次品件数
    w1 = w1 / 10;
    //求次品箱号
    while(w1>0){
        int k=0;
        int t=1;
        //计算最接近当前件数w1的2^k,则k+1号箱为次品箱
        while(w1-t>=0){
            t = t * 2;
            ++k;
        }
        w1 = w1 - t/2;
        cout<<k<<"号箱是次品"<<endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42823298/article/details/126618776