链接:https://www.nowcoder.com/questionTerminal/12b1b8ef17e1441f86f322b250bff4c0?source=relative
来源:牛客网
小易在学校中学习了关于字符串的理论, 于是他基于此完成了一个字典的项目。
小易的这个字典很奇特, 字典内的每个单词都包含n个’a’和m个’z’, 并且所有单词按照字典序排列。
小易现在希望你能帮他找出第k个单词是什么。
输入描述:
输入包括一行三个整数n, m, k(1 <= n, m <= 100, 1 <= k <= 109), 以空格分割。
输出描述:
输出第k个字典中的字符串,如果无解,输出-1。
示例1
输入
2 2 6
输出
zzaa
说明
字典中的字符串依次为aazz azaz azza zaaz zaza zzaa
fun函数数为了求排列组合的。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long k = sc.nextInt();
char[] res = new char[m + n];
for(int i = 0; i < m + n; ++i){
res[i] = 'z';
}
int xuan = n - 1;
int total = m + n - 1;
long sum_temp = 0;
boolean flag_while = true;
while(true){
long temp = fun(xuan, total);
//long temp = pz(xuan, total - xuan, k);
sum_temp += temp;
if(sum_temp < k){
--total;
if(total < xuan){
flag_while = false;
break;
}
}else if(sum_temp == k){
res[m + n - total - 1] = 'a';
for(int i = 0; i < xuan; ++i){
res[m + n - 1 - i] = 'a';
}
break;
}else{
sum_temp -= temp;
res[m + n - total - 1] = 'a';
--xuan;
--total;
if(total < xuan){
flag_while = false;
break;
}
}
}
if(flag_while == true){
for(int i = 0; i < res.length; ++i){
System.out.printf("%c", res[i]);
}
}else{
System.out.printf("-1");
}
}
public static long fun(int xuan, int total){
double fenmu = 1;
int size = Math.min(xuan, total - xuan);
for(int i = 0; i < size; ++i){
fenmu *= (total - i);
fenmu /= (i + 1);
}
return (long)fenmu;
}
}
但是如果讲fun函数稍稍改动一下,结果就不对了
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
long k = sc.nextInt();
char[] res = new char[m + n];
for(int i = 0; i < m + n; ++i){
res[i] = 'z';
}
int xuan = n - 1;
int total = m + n - 1;
long sum_temp = 0;
boolean flag_while = true;
while(true){
long temp = fun(xuan, total);
//long temp = pz(xuan, total - xuan, k);
sum_temp += temp;
if(sum_temp < k){
--total;
if(total < xuan){
flag_while = false;
break;
}
}else if(sum_temp == k){
res[m + n - total - 1] = 'a';
for(int i = 0; i < xuan; ++i){
res[m + n - 1 - i] = 'a';
}
break;
}else{
sum_temp -= temp;
res[m + n - total - 1] = 'a';
--xuan;
--total;
if(total < xuan){
flag_while = false;
break;
}
}
}
if(flag_while == true){
for(int i = 0; i < res.length; ++i){
System.out.printf("%c", res[i]);
}
}else{
System.out.printf("-1");
}
}
public static long fun(int xuan, int total){
double fenmu = 1;
int size = Math.min(xuan, total - xuan);
for(int i = 0; i < size; ++i){
fenmu *= (total - i) / (i + 1);
}
return (long)fenmu;
}
}