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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37428263/article/details/89015665

点击打开链接

#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;
}

猜你喜欢

转载自blog.csdn.net/m0_37428263/article/details/89015665