CodeForces 1307 C Cow and Message dp

一、内容

Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string sof lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 1, 3, and 5, which form an arithmetic progression with a common difference of 2. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of Sare distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 3times, b is hidden 2 times, ab is hidden 6 times, aa is hidden 3 times, bb is hidden 1 time, aab is hidden 2 times, aaa is hidden 1 time, abb is hidden 1 time, aaab is hidden 1 time, aabb is hidden 1 time, and aaabb is hidden 1 time. The number of occurrences of the secret message is 6
.

Input

The first line contains a string sof lowercase Latin letters (1≤|s|≤105 ) — the text that Bessie intercepted.

Output

Output a single integer  — the number of occurrences of the secret message.

二、思路

  • 首先最多次数肯定是出现在字符长度为1 或者 2 上面。 后面的字符越多次数肯定越少。所以我们统计1 或 2个字符出现的次数即可。
  • ans1[c]: 代表c字符出现的次数 。 ans2[i][j]: 代表字符 ij 出现的次数。

三、代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
char s[N];
ll ans1[26], ans2[26][26]; //第一个代表单一字符的数量 
int main() {
	scanf("%s", s);
	int n = strlen(s);
	for (int i = 0; i < n; i++) {
		int c = s[i] - 'a';
		for (int j = 0; j < 26; j++) {
			ans2[j][c] += ans1[j]; //jc 代表这2个字符出现的次数 加上以前j字符出现次数 
		}
		ans1[c]++; //c出现的次数增加 
	} 
	ll ans = 0;
	for (int i = 0; i < 26; i++) ans = max(ans, ans1[i]);
	for (int i = 0; i < 26; i++) {
		for (int j = 0; j < 26; j++) ans = max(ans, ans2[i][j]);//找出2个字符中的最大的一个 
	} 
	printf("%lld", ans);
	return 0;
} 
发布了456 篇原创文章 · 获赞 466 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_41280600/article/details/104389695