알고리즘(PS)

백준[boj 1181번: 단어 정렬 ]

5353 2024. 2. 2. 03:30
반응형

 

백준 단어정렬

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

 

우선순위큐가 과연 string도 최소값을 기준으로 정렬해줄까 싶어 시도해 봤다. 우선 순위가 string의 길이 이므로 length 를 pair의 앞 부분에, 뒤에 string을 넣어 줬다.

priority_queue<pair<int, string>, vector<pair<int, string>>, greater<pair<int, string>> >pq;

 그후 큐가 비어있지 않고, 그 다음 큐와 단어가 같으면 출력하지 않고 pop해서 흘려보냈다.

항상 유의 할 것 !! 비어있지않은 것을 체크하지 않으면 컴파일 에러가 난다!

< 정답 코드 >

#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<string>
#include<sstream>
using namespace std;
//const int MAX = 1000000 + 5;
// 발생가능 예외 케이스 2,3번째 글짜 까지 같은 경우
// 발생가능 예외 케이스 
vector<int> str;
//priority_queue<pair<int,string>, vector<pair<int,string>, greater<int,string>>>pq;
priority_queue<pair<int, string>, vector<pair<int, string>>, greater<pair<int, string>> >pq;
int main() {
	int N;
	cin >> N;
	while (N--) {
		string str;
		cin >> str;
		int len = str.length();
		pq.emplace(len,str);


	}

	while (!pq.empty()) {
		int length = pq.top().first;
		string s = pq.top().second;
		pq.pop();

		while (!pq.empty() && s == pq.top().second) {
			pq.pop();
			//cout << "제거 : "  << pq.top().second << "\n";
		}
		//cout << "length : " << length << " , s : " << s << "\n";
		cout << s << "\n";

		
	}
	return 0;
}
반응형