백준 알고리즘 1181번 : 단어 정렬

Zoo Da·2021년 8월 5일
0

백준 알고리즘

목록 보기
141/337
post-thumbnail

링크

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

문제

알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.

  1. 길이가 짧은 것부터
  2. 길이가 같으면 사전 순으로

입력

첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

출력

조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.

예제 입력 및 출력

풀이 코드(C++)

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<string>
#include<list>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<bitset>
#include<tuple>
#include<functional>
#include<utility>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<complex>
#include<cassert>
#define X first
#define Y second
#define pb push_back
#define MAX 20001
#define INF 1000000000
#define fastio ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
using ll = long long;
using ull = unsigned long long;
using dbl = double;
using ldb = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;

string dict[MAX];

bool cmp(const string &a,const string &b){
  if(a.length() == b.length()) return a < b;
  return a.length() < b.length();
}

int main(){
  fastio;
  int n;
  cin >> n;
  for(int i = 0; i < n; i++){
    cin >> dict[i];
  }
  sort(dict, dict+n,cmp);
  string temp;
  for(int i = 0; i < n; i++){
    if(dict[i] == temp) continue;
    cout << dict[i] << "\n";
    temp = dict[i];
  }
  return 0;
}

sol2) unique사용

#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define X first
#define Y second
#define pb push_back
#define fastio cin.tie(0)->sync_with_stdio(0)
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define sz(v) (int)(v).size()
#define all(v) v.begin(), v.end()
#define rall(v) (v).rbegin(), (v).rend()
#define compress(v) sort(all(v)), (v).erase(unique(all(v)), (v).end())
#define OOB(x, y) ((x) < 0 || (x) >= n || (y) < 0 || (y) >= m)
#define debug(x) cout << (#x) << ": " << (x) << '\n'
using namespace std;
using ll = long long;
using ull = unsigned long long;
using dbl = double;
using ldb = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;
using tii = tuple<int,int,int>;
template<typename T> using wector = vector<vector<T>>;

const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const ll LNF = 1e18 + 7;

int main(){
  fastio;
  int n; cin >> n;
  vector<string> dict(n);
  for(int i = 0; i < n; i++) cin >> dict[i];
  sort(all(dict),[](string& a,string& b) -> int{
    if(a.length() == b.length()) return a < b;
    return a.length() < b.length();
  });
  dict.erase(unique(all(dict)),dict.end());
  for(auto c : dict) cout << c << "\n";
	return 0;
}
profile
메모장 겸 블로그

0개의 댓글