2015-2016ACM-ICPC NEER northern-subregional-contest C Concatenation 思维好题

来源:互联网 发布:香港小鱼儿最近域名 编辑:程序博客网 时间:2024/05/22 16:39

题目描述:

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

input

catdog

output

9

input

treeheap

output

14

题目分析:

有两个由小写字母组成的单词,其中你将第一个的前缀和后一个的后缀重新组成一个单词,请问有多少个新单词?
这题看起来很难,好像要用到KMP算法,其实仔细想想,
若不考虑其他情况,所有新单词就是由两个单词的长度乘积。但是有些情况是会产生重复,就是在两个串同时有相同的字符的时候,在两个串相同字符相遇的时候就会产生一个重复,如’tree’和’heap’中有两个’e’,在产生’treeap’中,第二个’e’会产生重复,和’treap’中’e’会产生重复。因此,只要统计前一个串的字母个数,将后串与前串相同的前串次数减掉就可以。

代码如下:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>typedef long long LL;using namespace std;char a[100010],b[100010];int sum[200];int main(){//    freopen("concatenation.in","r",stdin);//    freopen("concatenation.out","w",stdout);    while(cin>>a>>b)    {        int len1=strlen(a);        int len2=strlen(b);        LL ans=(LL)len1*(LL)len2;        memset(sum,0,sizeof(sum));        for (int i=1; i<len1; i++) sum[a[i]]++;        for (int i=0; i<len2-1; i++) ans-=sum[b[i]];        printf("%I64d\n",ans);    }    return 0;}
0 0