Newcoder 70 D.幸运数字Ⅳ(组合数学)

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

Description

定义一个数字为幸运数字当且仅当它的所有数位都是 4 4 或者 7 7

比如说, 47 744 4 47、744、4 都是幸运数字而 5 17 467 5、17、467 都不是。

现在想知道在 1... n 1...n 的第 k k 小的排列中,有多少个幸运数字所在的位置的序号也是幸运数字。

Input

第一行两个整数 n , k n,k

( 1 n , k 1 0 9 ) (1\le n,k \le 10^9)​

Output

一个数字表示答案。

如果 n n 没有 k k 个排列,输出 1 -1

Sample Input

7 4

Sample Output

1

Solution

虽然此处 n n 很大,但是由于 k k 不大,故字典序第 k k 小的排列其前面的大部分数字都不变,最多后面十几个数字顺序改变,用康托展开即可得到后面乱序的十几个数字,这些数字直接暴力判断是否对答案有贡献,前面的 1 1 ~ x x 这些数字, i i 就在第 i i 个位置上,所以它们对答案的贡献就是幸运数字的个数,直接枚举九位是 4 4 还是 7 7 然后得到一个幸运数字判断其是否在该区间即可

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=22;
int fact[maxn],g[maxn];
bool check(int x)
{
	while(x)
	{
		if(x%10!=4&&x%10!=7)return 0;
		x/=10;
	}
	return 1;
}
int Solve(int n)
{
	g[0]=1;
	for(int i=1;i<9;i++)g[i]=10*g[i-1];
	int ans=0;
	for(int k=1;k<=9;k++)
	{
		int N=1<<k;
		for(int i=0;i<N;i++)
		{
			int temp=0;
			for(int j=0;j<k;j++)
				if(i&(1<<j))temp+=4*g[j];
				else temp+=7*g[j];
			if(temp<=n)ans++; 
		}
	}
	return ans;
}
int main()
{
	fact[0]=1;
	for(int i=1;i<=12;i++)fact[i]=i*fact[i-1];
	int n,k;
	while(~scanf("%d%d",&n,&k))
	{
		k--;
		int x=0;
		for(int i=12;i>=0;i--)
			if(k>=fact[i])
			{
				x=i+1;
				break;
			}
		if(x>n)printf("-1\n");
		else
		{
			int mark[maxn],a[maxn];
			memset(mark,0,sizeof(mark));
			for(int i=x-1;i>=0;i--)
			{
				int t=k/fact[i];
				k%=fact[i];
				for(int j=0;j<x;j++)
					if(!mark[j])
					{
						t--;
						if(t<0)
						{
							mark[j]=1;
							a[x-1-i]=j;
							break;
						}
					}
			}
			int ans=Solve(n-x);
			for(int i=0;i<x;i++)
				if(check(n-x+1+i)&&check(n-x+1+a[i]))ans++;
			printf("%d\n",ans);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/V5ZSQ/article/details/83244231
70