J - Richness of words
Time Limit:500MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit Status Practice URAL 2045
Description
For each integer i from 1 to n, you must print a string s i of length n consisting of lowercase Latin letters. The string s i must contain exactly idistinct palindrome substrings. Two substrings are considered distinct if they are different as strings.
Input
The input contains one integer n (1 ≤ n ≤ 2000).
Output
You must print n lines. If for some i, the answer exists, print it in the form “ i : s i” where s i is one of possible strings. Otherwise, print “i : NO”.
Sample Input
input | output |
---|---|
4 |
1 : NO 2 : NO 3 : abca 4 : bbca |
题意:给你一个数字n(n<=2000),for(int i=1;i<=n;i++),如果存在一个长为n的字符串,且其中有i个回文串,则输出
该字符串,否则输出NO;
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <vector> #include <queue> #include <cstring> #include <string> #include <algorithm> using namespace std; typedef long long ll; typedef unsigned long long ull; #define MM(a,b) memset(a,b,sizeof(a)); #define inf 0x7f7f7f7f #define FOR(i,n) for(int i=1;i<=n;i++) #define CT continue; #define PF printf #define SC scanf const int mod=1000000007; const int N=1e6+10; char s[2005][2005]; int flag[2005]; int main() { int n; while(~scanf("%d",&n)) { MM(s,‘\0‘); if(n==1) {printf("1 : a\n");continue;} if(n==2) { printf("1 : NO\n"); printf("2 : ab\n"); continue; } for(int i=1;i<=3;i++) s[n][i]=‘a‘+i-1; for(int i=4;i<=n;i++) s[n][i]=‘z‘; int p=3; for(int i=n-1;i>=1;i--) { int j; for(j=1;j<=p;j++) s[i][j]=s[i+1][j]; if(s[i][p]==‘a‘) s[i][j]=‘b‘; if(s[i][p]==‘b‘) s[i][j]=‘c‘; if(s[i][p]==‘c‘) s[i][j]=‘a‘; for(j++;j<=n;j++) s[i][j]=‘z‘; p++; } for(int i=1;i<=2;i++) printf("%d : NO\n",i); for(int i=3;i<=n;i++) printf("%d : %s\n",i,s[i]+1); } return 0; }
分析:刚开始想的是比如n==30,,那么首先就是
aaaaabcdefg...xyz,
aaaaabcaefg....zyz
aaaaabcaafg....xyz;
这样下去,,但是其实这样不是最优的;
正确做法:考虑abc三个字符,无论怎样循环都是不会有回文出现的,比如abcabcabc....
那么对于n==30的情况;
abczzzzzz...z;//30
abcazzzzz...z;//29
abcabzzzz...z;//28
abcabczzz...z;//27
abcabcazz...z;//26
所以这样下去,每次都能保证这一个比上面一个减1,然后特判下2,3;