首页 > ACM题库 > HDU-杭电 > HDU 4731-Minimum palindrome[解题报告]HOJ
2015
09-17

HDU 4731-Minimum palindrome[解题报告]HOJ

Minimum palindrome

问题描述 :

Setting password is very important, especially when you have so many "interesting" things in "F:\TDDOWNLOAD".
We define the safety of a password by a value. First, we find all the substrings of the password. Then we calculate the maximum length of those substrings which, at the meantime, is a palindrome.
A palindrome is a string that will be the same when writing backwards. For example, aba, abba,abcba are all palindromes, but abcab, abab are not.
A substring of S is a continous string cut from S. bcd, cd are the substrings of abcde, but acd,ce are not. Note that abcde is also the substring of abcde.
The smaller the value is, the safer the password will be.
You want to set your password using the first M letters from the alphabet, and its length should be N. Output a password with the smallest value. If there are multiple solutions, output the lexicographically smallest one.
All the letters are lowercase.

输入:

The first line has a number T (T <= 15) , indicating the number of test cases.
For each test case, there is a single line with two integers M and N, as described above.(1 <= M <= 26, 1 <= N <= 105)

输出:

The first line has a number T (T <= 15) , indicating the number of test cases.
For each test case, there is a single line with two integers M and N, as described above.(1 <= M <= 26, 1 <= N <= 105)

样例输入:

2
2 2
2 3

样例输出:

Case #1: ab
Case #2: aab

题意:

要求只用前m个字母,构造一个长为n的序列;

使所有子序列中回文长度最小,字典尽量小;

思路:

很明显;如果可以用的字母大于3;

那就一直abcabcabcabc….就好了;回文长度只有1;

如果只能用1个字母,更没什么好说;

现在处理两个字母的情况;

因为aababb由两个a一个b加上一个a两个b,这样一个两个一直交替肯定是最小的了,回文长度只有4;

但是序列长度小于等于8的要特判一下;

然后就是先输出aa,然后不断输出aababb(因为输出aa后,开头4个a,回文也是4,而且使字典序下降)

最后余出来几位就输入aaaab就行;

AC代码:

#include<cstdio>
#include<cstring>

const int N = 100005;
int n,m;

int main() {
	int t;
	int cas = 1;
	scanf("%d",&t);
	while(t--) {
		scanf("%d%d",&m,&n);
		printf("Case #%d: ",cas++);
		if(m == 1) {
			for(int i = 0; i < n; i++)
				printf("a");
			printf("\n");
		}else if(m == 2) {
			if(n == 1)
				printf("a");
			else if(n == 2)
				printf("ab");
			else if(n == 3)
				printf("aab");
			else if(n == 4)
				printf("aabb");
			else if(n == 5)
				printf("aaaba");
			else if(n == 6)
				printf("aaabab");
			else if(n == 7)
				printf("aaababb");
			else if(n == 8)
				printf("aaababbb");
			else{
				char temp[] = {"aababb"};
				printf("aa");
				int mod = (n - 2) % 6;
				int c = (n - 2) / 6;
				for(int i = 0; i < c; i++) {
					printf("%s",temp);
				}
				if(mod <= 4) {
					for(int i = 1; i <= mod; i++) 
						printf("a");
				}
				if(mod == 5)
					printf("aaaab");
			}
			printf("\n");
		}else {
			for(int i = 0; i < n; i++)
				printf("%c",'a' + (i % 3));
			printf("\n");
		}
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

参考:http://blog.csdn.net/yeyeyeguoguo/article/details/44422743