[백준] 18870 C++

윤경·2021년 7월 17일
0

Baekjoon

목록 보기
52/64

문제

코드

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


bool cmp(const pair<int, int> &a, const pair<int, int> &b) {
  return a.second < b.second;
}

int main() {
  ios::sync_with_stdio(0);

  int N;
  cin >> N;


  vector<pair<int, int>> v;

  int n;
  for(int i=1; i<=N; i++) {
      cin >> n;
      v.push_back({n, i});
  }

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

  int j=0, tmp=v[0].first;
  v[0].first = 0;

  for(int i=1; i<N; i++) {
    if(v[i].first != tmp) { tmp = v[i].first; v[i].first = ++j; }
    else if(v[i].first == tmp) { v[i].first = j; }
  }

  sort(v.begin(), v.end(), cmp);

  for(int i=0; i<N; i++) {
    cout << v[i].first << ' ';
  }

  return 0;
}

📢

vector의 pair를 이용했다. pair의 first에는 숫자를, second에는 순서를 넣어 first를 기준으로 오름차순 sort 시켰고 tmp를 활용해 같은 숫자에는 같은 인덱스?를 넣어주고 다른 숫자라면 1씩 증가시키며 수를 넣어주었다.

그리고 second를 기준으로 다시 정렬시켜 출력 시키면 완료!

profile
개발 바보 이사 중

0개의 댓글