51nod 2512 重排列得到2的幂 递归搜索

点击打开链接

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
char s[15];
int cnt;
LL solve[50];
bool done[15];
bool dfs(int c,char sol[])
{
    if(c==cnt) {
        sol[c]='\0';
        if(sol[0]=='0') return false;
        else {
            LL sum=0;
            for(int i=0;i<c;i++)
            {
                sum=sum*10+(sol[i]-'0');
            }
            if(*lower_bound(solve,solve+30+1,sum)==sum) return true;
            return false;
        }
    }
	for(int i=0;i<cnt;i++)
	{
		if(!done[i]) {
			sol[c]=s[i];
			done[i]=true;
			if(dfs(c+1,sol)) return true;
			done[i]=false;
		}
	}
	return false;
}
int main()
{
    solve[0]=1;
	solve[1]=2;
	for(int i=2;i<=30;i++)
	{
		solve[i]=solve[i-1]*2;
	}
	LL n;
	scanf("%lld",&n);
	cnt=0;
	while(n)
	{
		s[cnt++]='0'+n%10;
		n/=10;
	}
	s[cnt]='\0';
	int len=0;
	for(int i=0;i<cnt;i++)
        if(s[i]=='0') len++;
        if(len>1) {
        cout<<"false"<<endl;
        return 0;
        }
	char sol[15];
	memset(done,false,sizeof(done));
	if(dfs(0,sol)) cout<<"true"<<endl;
	else cout<<"false"<<endl;
	return 0;
}

也可以直接使用库函数 next_permutation()生成全排列

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
char s[15];
int cnt=0;
LL solve[50];
int main()
{
    solve[0]=1;
	solve[1]=2;
	for(int i=2;i<=30;i++)
	{
		solve[i]=solve[i-1]*2;
	}
	LL n;
	scanf("%lld",&n);
	cnt=0;
	while(n)
	{
		s[cnt++]='0'+n%10;
		n/=10;
	}
	s[cnt]='\0';
	sort(s,s+cnt);
	do{
            LL sum=0;
            for( int i = 0; i < cnt ;i++ )
                sum = sum * 10 + ( s [ i ] - '0' );
            if(*lower_bound(solve,solve+30+1,sum)==sum) {
                cout<<"true"<<endl;
                return 0;
            }
	} while(next_permutation( s,s + cnt ));
	cout<<"false"<<endl;
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值