[프로그래머스] 2024 Kakao Winter Internship - 가장 많이 받은 선물

부리또의 댄스·2025년 4월 23일
0

프로그래머스

목록 보기
3/3
post-thumbnail

풀이

풀이과정

레벨 1이라서 문제에서 제시하는 대로만 따라가면 간단하게 풀 수 있었다.

특이사항은 unordered_map을 선언해 key로 친구의 이름을 사용하여, value로 index 번호를 조회할 수 있는 map을 만들어주었다. 이것은 arr를 세팅할 때 gifts 배열 안의 친구 이름으로 index를 지정해 값을 세팅하는데 사용된다.

나머지는 주석을 통해 쉽게 이해할 수 있다.

최종코드


int solution(vector<string> friends, vector<string> gifts) {
   //1. 일단 문제처럼 표로 재정리
   int n = friends.size();
   //이름 배열 전처리
   unordered_map<string, int> names;
   for(int i=0; i<n; ++i)
      names[friends[i]] = i;

   vector<vector<int>> arr(n, vector<int>(n, 0));
   for(string gift: gifts){
      istringstream ss(gift);
      vector<string> temp(2);
      ss >> temp[0] >> temp[1];
      arr[names[temp[0]]][names[temp[1]]] += 1;
   }
   //2. 선물지수 계산
   vector<int> scores(n);
   for(int i=0; i<n; ++i){
      //(행-열)
      int row = 0; int column = 0;
      for(int j=0; j<n; ++j){
         row += arr[i][j];
         column += arr[j][i];
      }
      scores[i] = row - column;
   }
   //3. 선물받기 계산
   int max = 0;
   for(int i=0; i<n; ++i){
      int cnt = 0;
      //서로의 선물 주고받기부터 비교
      for(int j=0; j<n; ++j){
         if(i==j) continue;
         int give = arr[i][j]; int get = arr[j][i];
         if(give > get)
            cnt++;
         else if(give == get) //같거나 주고 받은 이력이 없을 때
            if(scores[i] > scores[j]) cnt++;
      }
      if(max < cnt)
         max = cnt;
   }
   return max;
}
profile
환영합니다!

1개의 댓글

comment-user-thumbnail
2025년 5월 10일

꾸준한 업로드 멋져요!

답글 달기