SDUT 算法训练赛 contest 5(2^x==2^y,map存储)

本文介绍了一种算法,用于从一组整数中找到三个不同的数,使得它们之间的差为2的幂次,并提供了详细的实现代码。通过使用哈希表和集合等数据结构来优化查找过程。

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





wa&&tle:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[200005],ans=0,idex;
map<ll,pair<ll,ll> >mp;
map<ll,ll>mmp;
int main()
{
    int n;
    bool flag1=0;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
        mmp[abs(a[i])]=a[i];
    }
    for(int i=0; i<n; i++)
        for(int j=i+1; j<n; j++)
        {
        if(mp.count(abs(a[i]-a[j])))
        
            mp[abs(a[i]-a[j])].first= a[i];
            mp[abs(a[i]-a[j])].second= a[j];
            }
    ll temp=1;
    for(int k=0; k<30; k++)
    {
        if(mmp.count(temp))
            idex=mmp[temp];
        if(mp.count(temp))
        {
            ans=temp;
            for(int i=0; i<n; i++)
            {
                if(abs(mp[temp].first-a[i])==temp&&a[i]!=mp[temp].second)
                {
                    ans=a[i];
                    flag1=1;
                    break;
                }
                if(abs(mp[temp].second-a[i])==temp&&a[i]!=mp[temp].first)
                {
                    ans=a[i];
                    flag1=1;
                    break;
                }
            }
        }
        if(flag1)
            break;
        temp = temp << 1;
    }
    if(flag1)
        cout<<3<<endl<<mp[temp].first<<" "<<mp[temp].second<<" "<<ans<<endl;
    else if(ans!=0)
        cout<<2<<endl<<mp[ans].first<<" "<<mp[ans].second<<endl;
    else
        cout<<1<<endl<<idex<<endl;
    return 0;
}

//THE most important is translate the view;
#include<bits/stdc++.h>
using namespace std;
const int maxn = 200005;
set<int >T;
int a[maxn];
int main()
{
    int n,x1,x2,ans=0;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
        T.insert(a[i]);
    }
    for(int i=0; i<n; i++)
        for(int k=0; k<31; k++)
        {
            if(T.count(a[i]+(1<<k))&&T.count(a[i]-(1<<k)))
            {
                cout<<3<<endl<<a[i]<<" "<<a[i]+(1<<k)<<" "<<a[i]-(1<<k)<<endl;
                return 0;
            }
            else if(T.count(a[i]+(1<<k))&&ans==0)
            {
                x1=a[i];
                x2=a[i]+(1<<k);
                ans=2;
            }
        }
    if(ans==2)
        cout<<ans<<endl<<x1<<" "<<x2<<endl;
    else
        cout<<1<<endl<<a[0];
    return 0;
}
用一个数的和加上

Powers of Two

  去找存不存在,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值