๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Goorm][์ •๋ ฌ] ๋‹จ์–ด์žฅ ๋งŒ๋“ค๊ธฐ

ibelieveinme 2023. 6. 8. 01:32
728x90
 

๊ตฌ๋ฆ„EDU - ๋ชจ๋‘๋ฅผ ์œ„ํ•œ ๋งž์ถคํ˜• IT๊ต์œก

๊ตฌ๋ฆ„EDU๋Š” ๋ชจ๋‘๋ฅผ ์œ„ํ•œ ๋งž์ถคํ˜• IT๊ต์œก ํ”Œ๋žซํผ์ž…๋‹ˆ๋‹ค. ๊ฐœ์ธ/ํ•™๊ต/๊ธฐ์—… ๋ฐ ๊ธฐ๊ด€ ๋ณ„ ์ตœ์ ํ™”๋œ IT๊ต์œก ์†”๋ฃจ์…˜์„ ๊ฒฝํ—˜ํ•ด๋ณด์„ธ์š”. ๊ธฐ์ดˆ๋ถ€ํ„ฐ ์‹ค๋ฌด ํ”„๋กœ๊ทธ๋ž˜๋ฐ ๊ต์œก, ์ „๊ตญ ์ดˆ์ค‘๊ณ /๋Œ€ํ•™๊ต ์˜จ๋ผ์ธ ๊ฐ•์˜, ๊ธฐ์—…/

edu.goorm.io

 

*ํ•ด๊ฒฐ๋ฒ•

์ฒ˜์Œ์—” ๋‹จ์–ด ๊ธธ์ด๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๋˜๋Š” ๊ฒƒ์„ ๋ชป๋ณด๊ณ  ๊ทธ๋ƒฅ sort ํ–ˆ๋‹ค๊ฐ€ ํ‹€๋ ธ๋‹ค.

๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•˜๋Š” ๊ฒƒ์€ ๋‹จ์–ด์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์„ ๋• ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๋กœ ์ •๋ ฌํ•˜๊ณ  ๋‹จ์–ด์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅผ ๋• ๋‹จ์–ด์˜ ๊ธธ์ด๋ณ„๋กœ ์ •๋ ฌํ•ด์•ผ ํ•˜๋ฏ€๋กœ Custom Sort ํ•จ์ˆ˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

 

*์•Œ์•„๋‘˜๊ฒƒ

1) Custom Sort ํ•จ์ˆ˜ ํ™œ์šฉ๋ฒ•

bool sortWord(string word1, string word2){
	//์‚ฌ์ด์ฆˆ๊ฐ€ ๋‹ค๋ฅด๋ฉด ๊ธด๊ฒŒ ๋’ค๋กœ
	if(word1.size() != word2.size()){
		return word1.size() < word2.size();
	}
	//์‚ฌ์ด์ฆˆ๊ฐ€ ๊ฐ™์œผ๋ฉด ํฐ ๊ฐ’์ด ๋’ค๋กœ
	return word1 < word2;
}

sort(words.begin(), words.end(), sortWord);

์ฐธ๊ฐ’์ธ๊ฒŒ ๋’ค๋กœ ๊ฐ€๋ฏ€๋กœ return bool ์‹œ ์œ„์™€ ๊ฐ™์ด ์ ์–ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

 

2) string ๊ธธ์ด๊ตฌํ•˜๋Š” ๋ฒ•

str.size();

3) string ํฌ๊ธฐ?๊ฐ’ ๋น„๊ต

str1 < str2

 

*์ฝ”๋“œ

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

bool sortWord(string word1, string word2){
	//์‚ฌ์ด์ฆˆ๊ฐ€ ๋‹ค๋ฅด๋ฉด ๊ธด๊ฒŒ ๋’ค๋กœ
	if(word1.size() != word2.size()){
		return word1.size() < word2.size();
	}
	//์‚ฌ์ด์ฆˆ๊ฐ€ ๊ฐ™์œผ๋ฉด ํฐ ๊ฐ’์ด ๋’ค๋กœ
	return word1 < word2;
}

int main() {
	int wordNum = 0, wordIndex = 0;
	vector<string> words(wordNum);
	string word;
	
	cin >> wordNum >> wordIndex;
	for(int i = 0; i<wordNum; i++){
		cin >> word;
		words.push_back(word);
	}
	
	sort(words.begin(), words.end(), sortWord);

	cout << words[wordIndex-1] << endl;
	return 0;
}

 

 

* vector pair์˜ second ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜๊ธฐ ์œ„ํ•œ custom sort ๋Š” ์•„๋ž˜ ๊ฒŒ์‹œ๊ธ€ ์ฐธ๊ณ 

 

[BOJ][C++] 1931 ํšŒ์˜์‹ค ๋ฐฐ์ • :: ๋ผ์ธ ์Šค์œ„ํ•‘

๊ตฌ๊ฐ„์ด ๋‚˜์˜ค๋ฉด ์ •๋ ฌ!์„ ๋– ์˜ฌ๋ฆฌ์ž. ์–ด๋Š์ •๋„์˜ ๋ณต์žก๋„๋ฅผ ๊ฐ์†Œ์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค. [๋ฌธ์ œ]https://www.acmicpc.net/problem/1931 ๊ฐ ํšŒ์˜์— ๋Œ€ํ•ด ์‹œ์ž‘์‹œ๊ฐ„๊ณผ ๋๋‚˜๋Š” ์‹œ๊ฐ„์ด ์ฃผ์–ด์ ธ ์žˆ์„ ๋•Œ,๊ฐ ํšŒ์˜๊ฐ€ ๊ฒน์น˜์ง€ ์•Š๊ฒŒ

i-believe-in-me.tistory.com

 

728x90