[Nowcoder 217040] CCA's dictionary

CCA's dictionary

Title link: nowcoder 217040

To Niu Ke:

——>Click me to jump<——

General idea

There are some words of length not more than 2 in the dictionary.
Then every time a word is given, you are asked how many words in the dictionary you can get this word by swapping adjacent letters (or not swapping).

Ideas

Because the length does not exceed two, we consider direct statistics.

You can make an array fa, b f_{a,b}fa,b, Record ab abThe word a b is used as the answer to the inquiry. (If the word has only one letter, thenbbb is0 00 )
Then we consider that the number in a dictionary is not read, and it isffcorresponding to its flipped shapef plus one.
There are special cases where you don't need to add the flip shape, that is, the flip shape is the same as before, that is, only one character or two characters are the same.

In fact, if it is bigger, you can use hash to do it.

Code

#include<cstdio>
#include<cstring>

using namespace std;

int n, ans[31][31];
char c[5], cn;

int main() {
    
    
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
    
    
		scanf("%s", &c);
		cn = strlen(c);
		if (cn == 1) ans[c[0] - 'a' + 1][0]++;
			else {
    
    
				ans[c[0] - 'a' + 1][c[1] - 'a' + 1]++;
				if (c[0] != c[1]) ans[c[1] - 'a' + 1][c[0] - 'a' + 1]++;
				//如果单词两个字母一样,那翻不翻转都是那样,就不用再加
			}
	}
	
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
    
    
		scanf("%s", &c);
		cn = strlen(c);
		if (cn == 1) printf("%d\n", ans[c[0] - 'a' + 1][0]);
			else printf("%d\n", ans[c[0] - 'a' + 1][c[1] - 'a' + 1]);
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/115218582