ALGORITHM

1181_단어정렬

서울소시민 2018. 5. 11. 20:53

1181_단어정렬

위 문제는 단어가 짧은 순서대로, 길이가 같다면 사전순으로 단어를 정렬하는 문제이다. 아울러 중복제거도 해주어야 한다. 여기서는 sort(start, end, compare)의 compare이 핵심이었다. 배열안의 원소를 정렬하는데, 조건에 맞게 정렬을 할수 있게 해주는 함수이다. 여기서는 cmp함수를 나타낸다. 다음은 parameter compare에 대한 설명이다.


comp

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.The function shall not modify any of its arguments.This can either be a function pointer or a function object.

출처 http://www.cplusplus.com/reference/algorithm/sort/



전체코드


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#define IOFAST() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;

string str[20001];

// true인 수가 앞에 온다.
bool cmp(string a, string b) {
   // 길이가 같을 때
   if(a.length() == b.length()){
       // more wait라고 가정할 때 more이 더 작은 값을 가지므로 true를 return한다.
       return a < b;
  }
   // no but이라고 할때 no가 더 적으므로 true를 return한다.
   return a.length() < b.length();
}

int main() {
   
   IOFAST()
   int T;
   cin >> T;
   
   for(int i=0;i<T;i++){
       cin >> str[i];
  }
   sort(str,str+T,cmp);
   
   for(int i=0;i<T;i++){
       if(i != 0){
           if(str[i] == str[i-1]) continue;
      }
       cout << str[i] << "\n";
  }
   
}

'ALGORITHM' 카테고리의 다른 글

14502_연구소  (0) 2018.06.12
Mutex와 Semaphore  (0) 2018.06.07
10989_수 정렬하기3  (0) 2018.05.11
1427_소트인사이드  (0) 2018.05.11
10974_모든순열  (0) 2018.04.21