题解:B4175 [BCSP-X 2024 6 月初中组] 打孔纸带

· · 题解

B4175 [BCSP-X 2024 6 月初中组] 打孔纸带

思路

题面说了,结果应是两位 \text{and} 或 \text{or} 或 \text{xor},那我们列个表。

||\text{and}|\text{or}|\text{xor}| |:-:|:-:|:-:|:-:| |0 和 0|0|0|0| |0 和 1|0|1|1| |1 和 1|1|1|0|

我们发现:

所以,如果纸条里包含第二种和第三种情况时,即有一个 0 和两个 1 时,符合题意。

综上,遍历所有纸条的每一位,若不够一个 0 和两个 1,就把缺少的数量记录一下,每一位取最大值即可。

其余解释说明详见代码。

Code

#include<bits/stdc++.h>
using namespace std;

int n,m,ans=0;
string s[55];

main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
      cin>>s[i];
    m=s[1].size(); // 所有串长度都一样
    for(int j=0;j<m;j++) // 遍历串的每一位
    {
        int c0=0,c1=0; // 0和1的个数
        for(int i=1;i<=n;i++) // 遍历所有的串的第j位
        {
            if(s[i][j]=='0')
              c0++;
            else
              c1++;
        }
        if(!c1) // 没1(都是0),得加俩1
          ans=max(ans,2);
        if(c1==1) // 只有一个1(需要俩1),得加一个1
          ans=max(ans,1);
        if(!c0) // 没0(都是1),得加一个0
          ans=max(ans,1);
    }
    return !printf("%d\n",ans);
}