HDUOJ -I love string

题目链接:https://acm.hdu.edu.cn/showproblem.php?pid=6965

Problem Description
Mr X likes to play string games.

Mr X has an operation sequence. This operation sequence can be written as a string. For each operation, the next character of the operation sequence can be inserted before or after the current string. For example, my operation sequence is “aabac”, suppose the sequence obtained after the first four operations is “baaa”, then after the last operation, the string may become “baaac” or “cbaaa”. It can be seen that there is only one operation method for the first operation. For other operations, there are only two methods of operation.

For each operation method, there will be a score. The smaller the lexicographic order of the final string, the higher the final score.

Then, for a given operation sequence, how many operation methods can get the maximum score.

The two operation methods are different. If and only if there is a certain operation (not the first operation), one operation will be inserted before the current string, and the other operation will be inserted after the current string.

Input
Enter a positive integer T ( T ≤ 10 ) T (T≤10) T(T≤10) on the first line to represent the number of test cases.

For each test case:

the first line contains a integer n ( 1 ≤ n ≤ 100000 ) n (1≤n≤100000) n(1≤n≤100000) to represent the length of the string.

the second line contains a string of lowercase letters , which represents the sequence of operations.

Output
For each test case, output a line of a positive integer to represent the number of schemes, and the answer is modulo 1 0 9 + 7 10^9+7 109+7

Sample Input
1
5
abcde

Sample Output
1

题目大意:
给定一个源串,需要按照规则去生成一个新串。
规则如下:
将源串的第一个字符放到新串的开头或者末尾(新串一开始是空的,此时只能放在开头)。操作之后,若源串仍然非空,则对其新的第一个字符继续上述操作。对于每一次的选择(放在开头或者末尾),都视作一个操作,那么执行到源串为空,可以得到一个操作序列。

请问:我们有多少不同的操作序列可以使得生成的新串字典序最小?
对于两个操作序列,只要有任意一个位置进行了不同的操作,都视作二者不同。否则视作二者相同。

思路:
为了使得字典序最小,我们在生成新串时不会将字典序大于开头的字符放在新串的开头。若是字符字典序小于新串开头的字符,则必然放在开头。若是字符与新串开头字符相等,而新串末尾字典序又大于该字符,那么也只能将字符放在新串开头。
所以,我们只有在一种情况下有得选择,就是新串开头和新串末尾字符相同,也和我们目前要放置的字符相同。此时我们将其放在前还是后得到的结果都是一样的,但是操作序列上出现了分叉,总的不同的操作序列变成了原来的两倍。一旦遇到了不同的字符,破坏了三者相等的局面,后面的操作序列都将没得选择。
因此我们只需要统计源串中最长的同字符前缀,设其长度为k,
答案就是2的k-1次幂取模后的结果

AC代码:

#include<iostream>
#include<cstdio>
#include<string>
const long long mod = 1e9 + 7;
using namespace std;

char ans[100005];
int main(void) {
    int t; cin >> t;
    while (t--) {
        int n; cin >> n;
        scanf("%s", ans + 1);
        long long res = 1;
        for (int i = 2; i <= n; i++) {
            if (ans[i] != ans[1])break;
            res *= 2;
            res %= mod;
        }
        cout << res << endl;
    }
}
上一篇:2021.5.20(刷题-前K个高频单词)


下一篇:线程实现