cf Round #500 (Div. 2) B: And (思维+位运算)

本文详细解析了一道算法竞赛题目,目标是在给定的整数数组中,通过执行特定操作找到使两个整数相同的最少步骤。文章提供了清晰的思路和完整的C++代码实现,适合对算法竞赛感兴趣的学习者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

And

题意:

有整数n,x;

有n个整数a1,a2...an,可以对ai进行任意次ai&x;

求经过多少次操作可以使,整数中有两个是相同的。

思路:

占坑,等我想明白了再填。

AC代码如下:

#include <cstdio>
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;

int main()
{
    int n,x;
    while(cin>>n>>x)
    {
        set<int>s;
        set<int>s1;
        int a[100001];
        for(int i=0;i<n;i++)
		{
            cin>>a[i];
            s.insert(a[i]);
        }
        if(s.size()<n)//本来就有大于等于2个的值
		{
			cout<<0<<endl;
		}
        else
		{
            int flag=0;
            for(int i=0;i<n;i++)
			{
                int k=a[i]&x;
                if(k!=a[i]&&s.count(k))//&后改变并且原来就存在了,所以只需要1步操作
				{
					flag=1;
					break;
				}
            }
			if(flag==1)
			{
				cout<<1<<endl;
			}
			else
			{	
				for(int i=0;i<n;i++)
				{
					int k=a[i]&x;//&后有两个一样的,所以只需要2步操作
					if(s1.count(k))
					{
						flag=2;
						break;
					}
					s1.insert(k);
				}
				if(flag==2)
				{
					cout<<2<<endl;
				}
				else
				{
					cout<<-1<<endl;
				}
			}
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值