URAL 2045 Richness of words (回文子串,贪心)
題目鏈接:
http://acm.hust.edu.cn/vjudge/contest/126823#problem/J
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 i distinct 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的字符串(可以放26個小寫字母):
要求Si中不同回文子串的個數恰為i.
題解:
首先容易明確:n個相同字符組成的字符串的回文子串恰有n個.
那么對于小于n的情況,要想辦法在上述基礎上減少不同回文子串的個數.
減少的方式是使其出現重復的串. 而為了使得重復的串之間不構成新得回文串,必須插入不相同的字符.
可以證明,當插入連續的"bc"后,無論怎樣都不可能構成新的回文串.
對于Si: 先輸出i-2個'a',再輸出"bc", 此時的i個字符恰好構成i個回文字串,為了使后面的字符不構成新回文串,可以不斷填充"abc".
注意,此題時限比較嚴格,容易TLE.
代碼:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <queue> #include <map> #include <set> #include <vector> #define LL long long #define eps 1e-8 #define maxn 210000 #define mod 100000007 #define inf 0x3f3f3f3f #define IN freopen("in.txt","r",stdin); using namespace std;int n;int main(int argc, char const *argv[]) {//IN;while(scanf("%d", &n) != EOF){if(n == 1) {printf("1 : a\n");continue;}if(n == 2) { printf("1 : NO\n");printf("2 : ab\n");continue;}printf("1 : NO\n");printf("2 : NO\n");for(int i=3; i<=n; i++) {printf("%d : ", i);for(int j=1; j<=i-2; j++) putchar('a');printf("bc");for(int j=i+1,k=0; j<=n; j++,k=(k+1)%3) {if(k==0) putchar('a');if(k==1) putchar('b');if(k==2) putchar('c');}printf("\n");}}return 0; }轉載于:https://www.cnblogs.com/Sunshine-tcf/p/5746757.html
總結
以上是生活随笔為你收集整理的URAL 2045 Richness of words (回文子串,贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第二章API的理解和使用
- 下一篇: 201706问题记录