第二次组队赛补题Problem C. Concatenation**

补题**:Problem C. Concatenation**
Input file: concatenation.in
Output file: concatenation.out
Time limit: 2 seconds
Memory limit: 256 megabytes
Famous programmer Gennady likes to create new words. One way to do it is to concatenate existing
words. That means writing one word after another. For example, if he has words “cat” and “dog”, he
would get a word “catdog”, that could mean something like the name of a creature with two heads: one
cat head and one dog head.
Gennady is a bit bored of this way of creating new words, so he has invented another method. He takes
a non-empty prefix of the first word, a non-empty suffix of the second word, and concatenates them. For
example, if he has words “tree” and “heap”, he can get such words as “treap”, “tap”, or “theap”. Who
knows what they could mean?
Gennady chooses two words and wants to know how many different words he can create using his new
method. Of course, being a famous programmer, he has already calculated the answer. Can you do the
same?
Input
Two lines of the input file contain words chosen by Gennady. They have lengths between 1 and 100 000
characters and consist of lowercase English letters only.
Output
Output one integer — the number of different words Gennady can create out of words given in the input
file.
Examples
concatenation.in concatenation.out
cat
dog
9
tree
heap
14
题意:给出两个单词,选取第一个单词的非空前缀和第二个单词的非空后缀组成一个新的单词,注意是非空的
解题思路:如果不考虑组成单词的重复问题,那么可以组成的新的单词共有nm个,但是要考虑单词的重复问题,并且前缀和后缀又是非空的,所以记录第一个单词(除去第一个字母)
里和第二个单词(除去最后一个字母)里的共有字母s[i]个数a[i]和b[i],然后用n
m分别减去每个共有字母个数乘机(a[i]*b[i])
代码如下:
#include
#include
#include
#include
using namespace std;
int main()
{
freopen(“concatenation.in”,“r”,stdin);
freopen(“concatenation.out”,“w”,stdout);
char s[100010], ss[100010];
long long a[150], b[150];
long long n, m, i;
long long ans;
cin >> s >> ss;
n = strlen(s);
m = strlen(ss);
ans = n * m;
memset(b, 0, sizeof(b));
memset(a, 0, sizeof(a));
for (i = 1; i < n; i++)
{
int f = s[i] - ‘a’;
a[f]++;
}
for (i = 0; i < m-1; i++)
{
int f = ss[i] - ‘a’;
b[f]++;
}
for (i = 0; i < 26; i++)
{
ans -= a[i] * b[i];
}
cout << ans << endl;
return 0;
}

你可能感兴趣的:(第二次组队赛补题Problem C. Concatenation**)