PS/문자열 알고리즘[String]

백준 1764 듣보잡(c++)

SeungbeomKim 2022. 7. 4. 19:18
반응형

https://www.acmicpc.net/problem/1764

 

1764번: 듣보잡

첫째 줄에 듣도 못한 사람의 수 N, 보도 못한 사람의 수 M이 주어진다. 이어서 둘째 줄부터 N개의 줄에 걸쳐 듣도 못한 사람의 이름과, N+2째 줄부터 보도 못한 사람의 이름이 순서대로 주어진다.

www.acmicpc.net

<틀린 코드>

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

int main()
{
	int n,m;
	cin>>n>>m;
	string str1,str2;
	vector<string>s1;
	vector<string>s2;
	vector<string>result;
	vector<string>::iterator iter;
	for(int i=0;i<n;i++)
	{
		cin>>str1;
		s1.push_back(str1);
	}
	for(int i=0;i<m;i++)
	{
		cin>>str2;
		s2.push_back(str2);
	}
	int cnt=0;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(s1[i]==s2[j])
			{
				cnt++;
				result.push_back(s1[i]);	
			}	
		}	
	}
	sort(result.begin(),result.end());
	cout<<cnt<<'\n';
	for(auto iter = result.begin();iter!=result.end();iter++)
	{
		cout<<(*iter)<<'\n';
	}
}

테스트케이스에서 될 수 있는 n,m의 값이 각각 50만이기 때문에 이중 포문을 돌리면 시간 초과가 뜨게 된다.

그래서 할 수 있는 방법이 map 헤더를 이용하는 것이다.

<맞는 코드>

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;

int main()
{
	int n,m;
	cin>>n>>m;
	string str;
	map<string,int>mm;
	vector<string>v;
	vector<string>::iterator iter;
	for(int i=0;i<n+m;i++)
	{
		string str;
		cin>>str;
		mm[str]++;
		if(mm[str]>1) v.push_back(str);
	}
	
	sort(v.begin(),v.end());
	cout<<v.size()<<'\n';
	for(auto iter = v.begin();iter!=v.end();iter++)
	{
		cout<<(*iter)<<'\n';
	}
}

<풀이과정>

map헤더를 이용하여 mm에 있는 str의 key값이 1보다 크면(2개 이상)이면 벡터에 문자열을 push해준다. 

반응형

'PS > 문자열 알고리즘[String]' 카테고리의 다른 글

백준 1212 8진수 2진수(c++)  (0) 2022.07.06
백준 1373 2진수 8진수(c++)  (0) 2022.07.06
백준 14425 문자열 집합(c++)  (0) 2022.07.06
백준 5525 IOIOI(c++)  (0) 2022.07.05
백준 1357 뒤집힌 덧셈  (0) 2022.07.04