51nod 1095 Anigram单词 stl map

基准时间限制:1 秒 空间限制:131072 KB 分值: 10  难度:2级算法题
 收藏
 关注
一个单词a如果通过交换单词中字母的顺序可以得到另外的单词b,那么定义b是a的Anigram,例如单词army和mary互为Anigram。现在给定一个字典,输入Q个单词,从给出的字典中找出这些单词的Anigram。
Input
第1行:1个数N,表示字典中单词的数量。(1 <= N <= 10000)
第2 - N + 1行,字典中的单词,单词长度 <= 10。
第N + 2行:查询的数量Q。(1 <= Q <= 10000)
第N + 3 - N + Q - 2行:用作查询的单词,单词长度 <= 10。
Output
共Q行,输出Anigram的数量,相同的2个单词不算Anigram,如果没有输出0。
Input示例
5
add
dad
bad
cad
did
3
add
cac
dda
Output示例
1
0
2


刚开始的想法 存一个字典

用全排列枚举单词出现情况

超时代码 ↓

#include <iostream>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;
int main()
{
	map <string, int> words; 
	map <string, int> times;
	int N;
	char tmp[20];
	cin>>N;
	while(N--)
	{
		cin>>tmp;
		words[tmp] = 1;
	}
	cin>>N;
	int ans, len, flag;
	while(N--)
	{
		flag = 0;
		cin>>tmp;
		ans = 0;
		len = strlen(tmp);
		if(words[tmp] == 1)
		{
			flag = 1;
		}
		sort(tmp,tmp + len);
		do
		{
		//	cout<<tmp<<endl;
			if(words[tmp] == 1)
			{
				ans++;
			}
			
		}while(next_permutation(tmp,tmp + len));
		if(ans > 0 && flag == 1)
			ans --;
		cout<<ans<<endl;
	}
	return 0;
}

发现如果两个不同的单词有序相等的话 

即 dda 和 dad

在排序后都是add add

其实是等价的

所以可以归为一个单词计算

所以只要解决字典中单词与输入判断单词完全相同的情况即可

扫描二维码关注公众号,回复: 953101 查看本文章

ac代码如下↓

#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
int main()
{
	int N, len, ans, flag;
	cin>>N;
	char txt[15];
	map <string, int> rwords;
	map <string, int> swords;
	while(N--)
	{
		cin>>txt;
		len = strlen(txt);
		rwords[txt] = 1;
		sort(txt,txt + len);
		swords[txt] ++;
	}
	cin>>N;
	while(N--)
	{
		flag = 0;
		ans = 0;
		cin>>txt;
		if(rwords[txt] == 1)
			flag = 1;
		len = strlen(txt);
		sort(txt,txt + len);
		if(swords[txt] > 0)
			ans = swords[txt];
		if(ans > 0 && flag == 1)
			ans --;
		cout<<ans<<endl;
	}
	return 0;
}




猜你喜欢

转载自blog.csdn.net/zeolim/article/details/80164833