UESTC 548 Cow IDs (二进制的排列 组合数 STL)

本文介绍了一种算法,用于找到第N小的二进制数,该数由K个1和若干个0组成。通过计算排列组合并使用next_permutation函数来生成所需的二进制数。

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

Cow IDs

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

Being a secret computer geek, Farmer John labels all of his cows with binary numbers. However, he is a bit superstitious, and only labels cows with binary numbers that have exactly KK 1 bits (1K101≤K≤10). The leading bit of each label is always a 1 bit, of course. FJ assigns labels in increasing numeric order, starting from the smallest possible valid label -- a KK-bit number consisting of all 1 bits. Unfortunately, he loses track of his labeling and needs your help: please determine the NthNth label he should assign (1N1071≤N≤107).

Input

  • Line 11: Two space-separated integers, NN and KK.

Output

  • Line 11: Output the NthNth label he should assign

Sample input and output

Sample Input Sample Output
7 3
10110

Source

USACO Feb 2012

大体题意:
给你N 和K ,让你求一个二进制数,包含K个1,其余只能是0,求第N小的数!

思路:
先求出此时的N和K时,有多少个0 有多少1组成,N不断的减,(最后N的意义就是在当前0和当前1的数第几个小的)然后构建一个最小的数,比如说有3个1 和2 个0 组成吧,那么最小的数就是10011,然后利用next_permutation函数求n次即可!
最后,输出字符串即可!

注意:
数组要开大点,100W差不多就可以了!
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1000000 + 10;
char s[maxn];
int main(){
	int n,k,m=0;
	scanf("%d%d",&n,&k);
	int star = 1;
	for ( ; n > star ; ++m){
		n-=star;
		star = star * (k+m)/(m+1);
	}
	s[0]='1';
	for (int i = 1; i < k + m; ++i){
		if (i <= m)s[i]='0';
		else s[i] = '1';
	}
	s[k+m]=0;
	while(--n && next_permutation(s+1,s+k+m));
	printf("%s\n",s);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值