티스토리 뷰

1181번: 단어 정렬
https://www.acmicpc.net/problem/1181
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int input = 0;
    cin >> input;
    
    vector<pair<int, string>> stringV;
    
    for(int i = 0; i < input; i++)
    {
        string inputString;
        cin >> inputString;
        stringV.push_back(make_pair(inputString.length(),inputString));
    }
    
    sort(stringV.begin(), stringV.end());
    
    for(int i = 0; i < input; i++)
    {
        if(stringV[i].second == stringV[i+1].second) continue;
        cout << stringV[i].second <<'\n';
    }
}
메모리 (KB)시간 (ms)코드 길이 (B)
505620640

이 문제에서 신경 썼던 점은 2가지이다.

첫 번째로는 입력한 문자열을 어떻게 저장할 것인가?

두 번째로는 문자열을 알파벳순을 어떻게 정렬할 것인가?

map, vector<string> name[51] 등등 여러 가지 방법을 시도했었는데, pair라는 좋은 문법을 알게 되었다.

🙋 더 알아보기

pair

#include <utility>

pair<type, type> name;
std::pair
std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a with two elements. If neither T1 nor T2 is a possibly cv-qualified class type with non-trivial destructor, or array thereof, the destructor of pair is trivial.
https://en.cppreference.com/w/cpp/utility/pair

2가지의 형식을 다룰 수 있는 pair라는 문법이 있다. 헤더에 utiliy를 추가해줘야 한다고 되어있는데, 오류인지 모르겠지만 작성하지 않아도 맞았다.

pair는 두 가지 형식을 구조체로 만들어 짝으로 값을 저장할 수 있다. 각 형식의 값을 가져올 수도 있다.

#include <iostream>
#include <utility>
#include <string>
using namespace std;

int main()
{
    pair<int, string> pairTest = {1, "first"};

    cout << "pairTest의 첫 번째 형식의 값 : " << pairTest.first << '\n' << "pairTest의 두 번째 형식의 값 : " << pairTest.second << '\n';

}

// 출력
// pairTest의 첫 번째 형식의 값 : 1
// pairTest의 두 번째 형식의 값 : first

name.first는 첫 번째 형식의 값을, name.second는 두 번째 형식의 값이다.

🤔 궁금해서 이 예시에서도 utility 헤더 추가 안 해봤는데 잘 작동된다. 그래도 앞으로는 추가해줘야 겠다.

그렇다면 이번에는 vector와 사용해보도록 하자.

#include <utility>
#include <vector>

vector<pair<type, type>> name;

작성 방법은 간단하다. pair를 만들었던 것처럼 짝을 형식 2가지를 넣어준 후pair<>로 묶어주면 된다.

형식 type ?

예전에 각 변수들이 가지고 있는 형식에 대해 헷갈렸던 적이 있다. 보통 초보단계에서는 변수를 만들 때 int a; double b; 정도로만 만들기에 해당 변수들이 어떤 형식인지 알기 쉬웠다.

vector<int> vectorInt; // int를 취하는 vector
vector<pair<int, float>> vectorPair; // pair<int, float>을 취하는 vector

단순히 생각하면 변수를 무언가를 담는 바구니라고 했을 때, 그 바구니 안에 들어갈 수 있는 내용물을 지정한다고 생각하니 쉬워졌다.

구조체나 클래스, 포인터 역시 이렇게 접근하니 쉬웠다. 이전에는 int처럼 한 가지 형식만 단독으로 들어간다고 인식해서 구조체 안에 여러 가지 형식이 있으면 어떻게 가져오는 건지 의문 투성이였다. 단순히 생각하면 구조체 자체를 담는 변수를 만든 것인데 말이다.

sort

sort(stringV.begin(), stringV.end());

문제에서 문자열의 개수가 같다면 알파벳으로 비교하여 나열해달라고 했다. 사실 sort 함수 한 번으로 모든게 해결될 줄 몰랐다.

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

int main()
{
    vector<pair<int, string>> test = 
		{
        {1, "abcde"},
        {1, "abcdf"},
        {1, "abccc"},
        {2, "abcde"},
        {3, "abcde"}
    };
    
    sort(test.begin(), test.end());
    
    for(int i = 0; i < 5; i++)
    {
        cout << test[i]. first << ' ' << test[i].second << '\n';
    }
}

// 출력
// 1 abccc
// 1 abcde
// 1 abcdf
// 2 abcde
// 3 abcde

여담으로 내림차순으로도 숫자는 물론, 알파벳까지 정렬되는 걸 확인할 수 있다.

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

int main()
{
    vector<pair<int, string>> test = 
		{
        {1, "abcde"},
        {1, "abcdf"},
        {1, "abccc"},
        {2, "abcde"},
        {3, "abcde"}
    };
    
    sort(test.begin(), test.end(), greater<pair<int, string>>());
    
    for(int i = 0; i < 5; i++)
    {
        cout << test[i]. first << ' ' << test[i].second << '\n';
    }
}

// 출력
// 3 abcde
// 2 abcde
// 1 abcdf
// 1 abcde
// 1 abccc

그렇다면 만일 숫자는 오름차순 그대로지만, 알파벳을 내림차순으로 나타내고 싶다면?

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

bool compare(pair<int, string> a, pair<int, string> b)
{
    if(a.first == b.first) return a.second > b.second;
    else return a.first < b.first;
}

int main()
{
    vector<pair<int, string>> test =
    {
        {1, "zzzzz"},
        {1, "bbbbb"},
        {2, "ccccc"},
        {2, "yyyyy"},
        {3, "eeeee"},
        {3, "xxxxx"}
    };
    
    sort(test.begin(), test.end(), compare);
    
    for(int i = 0; i < 6; i++)
    {
        cout << test[i]. first << ' ' << test[i].second << '\n';
    }
}

// 출력
// 1 zzzzz
// 1 bbbbb
// 2 yyyyy
// 2 ccccc
// 3 xxxxx
// 3 eeeee

compare 함수 제작하기

비교하는 함수를 직접 제작할 수 있다. 생각보다 어렵지 않았다. 바로 위 예시를 이용해서 compare 함수를 만들어보면 다음과 같다.

bool compare(pair<int, string> a, pair<int, string> b)
{
    if(a.first == b.first) return a.second > b.second;
    else return a.first < b.first;
}

위 코드를 해석해보면,

a.first와 b.first의 값이 같다면 a.second, b.second는 내림차순으로 정렬한다.

그게 아니라면 a.first, b.first는 오름차순으로 정렬한다.


Uploaded by N2T

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
링크
Total
Today
Yesterday