Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Re:原理 本质上就是个排列数的方法,他这个更针对具体情况O(1)时间,我贴下自己的代码。。

Posted by NtNlyCoder at 2015-11-19 10:00:55 on Problem 2453
In Reply To:原理 Posted by:huicpc0860 at 2010-04-07 20:50:24
O(logN*log(logN))
//O(logN*log(logN))
#include <cstdio>
#include <algorithm>
#define N 22
using namespace std;

int num;
int bin[N],k;
int dec;

void ToBinary()
{
	k = 0;
	while(num)
	{
		bin[k++] = num % 2;
		num /= 2;
	}
	int i;
	for(i=0;i<k/2;i++)
	{
		int t = bin[i];
		bin[i] = bin[k-1-i];
		bin[k-1-i] = t;
	}
}

void ToDecimal()
{
	dec = 0;
	int power = 1;
	int i;
	for(i=k-1;i>=0;i--)
	{
		dec += bin[i] * power;
		power *= 2;
	}
}

//排列数(变型)
bool Next()
{
	int u,v;
	if(k==1)
	{
		bin[0] = 1;
		bin[k++] = 0;
		return true;
	}
	for(u=k-2;u>=0;u--)
	{
		if(bin[u]<bin[u+1])
		{
			break;
		}
	}
	if(u==-1)
	{
		int i;
		for(i=k;i>=1;i--)
		{
			bin[i] = bin[i-1];
		}
		bin[0] = 0;
		k++;
		return false;
	}
	for(v=k-1;v>u;v--)
	{
		if(bin[v]>bin[u])
		{
			break;
		}
	}
	int t = bin[u];
	bin[u] = bin[v];
	bin[v] = t;
	sort(bin+u+1,bin+k);
	return true;
}

int main()
{
	while(scanf("%d",&num)!=EOF)
	{
		if(!num)
		{
			break;
		}
		ToBinary();
		while(!Next());
		ToDecimal();
		printf("%d\n",dec);
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator