问题描述
Eibwen is a newbie in Python.
You might know that when you input a number in the command line, your Python program will receive a string containing that number instead of a number that can be used to calculate. This is an interesting feature that a newbie might not know.
Eibwen wants to find the maximum of some given numbers, so he writes a program to sort the list of the numbers and print the last element in the sorted list. However, as a newbie, Eibwen doesn't know the feature. He actually sorts the list of number strings in lexicographical order and prints the last string in the list.
Now Eibwen runs his program, inputs all the integers from 1 to n, and finds his program really slow. Could you help him find out the expected output of his program?
输入格式
The only line contains an integer n (1≤n≤101000000) — the size of Eibwen's input.
输出格式
Print the expected output of Eibwen's program in a single line, which actually is the lexicographically maximum from 1 to n.
样例输入
616
样例输出
99
题解
求1~n字典序最大的数
按字典序求出最大的数,显然越高位(越靠前)的数字要越大,而最大的个位数是9,所以这个数前面要有尽可能多的9,且不能超过最大值n
令一个数的每一位都是9,且不超过n,那么这个数的位数应比n少一位(如果位数相等这个数会超过n)
但是当n为998时,上述算法得出的结果为99,而事实上最大的数应是998,于是发现答案不一定全是9
设n有k位,那么显然所有k-1位的数都比n小,而这些数中字典序最大的数是每一位都是9,所以前k-1位必定每一位上都是9
由于字典序决定大小的不是长度而是排在前面的数字,如果答案是k位,那么必定只有最后一位不是9,而这个数还要满足不大于n,所以只有当n只有最后一位不是9时,n会是字典序最大的数
1 #include <cstring> 2 #include <cstdio> 3 int len; 4 char s[1000005]; 5 int main() 6 { 7 int i; 8 scanf("%s",s); 9 len=strlen(s); 10 if (len==1) printf("%s",s); 11 else 12 { 13 bool ok=1; 14 for (i=0;i<len-1;i++) 15 if (s[i]!='9') 16 { 17 ok=0; 18 break; 19 } 20 if (ok) printf("%s",s); 21 else 22 for (i=1;i<len;i++) 23 printf("9"); 24 } 25 return 0; 26 }
标签:newbie,蔚来,list,多校,number,program,Lexicographical,Eibwen,字典 From: https://www.cnblogs.com/rabbit1103/p/16608164.html