HDU1247 Hat’s Words(STL:map)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42391248/article/details/81671114

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18645    Accepted Submission(s): 6605

Problem Description

A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.

Input

Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.

Output

Your output should contain all the hat’s words, one per line, in alphabetical order.

Sample Input

a
ahat
hat
hatword
hziee
word

Sample Output

ahat
hatword

string s1(s[i],a,k);  //s[i]从i=a开始之后的k个字符附给s1。

题意:给出几个单词组成字典,找出可以由字典里两个单词组成的单词。(一个单词可以由一个单词重复两次组成,例如aaaaaa由两个aaa组成)。

题解:对于每个单词依次拆解成两个单词,然后找拆开后的两个单词是否存在。

具体代码如下:

#include<iostream>
#include<algorithm>
#include<string>
#include<map>
using namespace std;
string str[50001];
int main()
{	
	map<string,int> mp;
	int n=0;
	while(cin>>str[n])
		mp[str[n++]]=1;
	int i,j;
	for(i=0;i<n;i++)
	{
		for(j=1;j<str[i].size()-1;j++)
		{
                        j=(j==0?1:j);//确保长度为2的字符串能进循环 
			string s1(str[i],0,j);
			string s2(str[i],j,str[i].size()-j);
//如果加上下面两行就好WA,说明单词可以重复使用
//			if(s1==s2)
//				continue;
			if(mp[s1]==1&&mp[s2]==1)
			{
				cout<<str[i]<<endl;
				break;
			}			
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42391248/article/details/81671114
今日推荐