study gomi

[소프티어/Softeer] lv2. 금고털이 (파이썬, C++) 본문

Practice/Other Sites...

[소프티어/Softeer] lv2. 금고털이 (파이썬, C++)

공부하곰 2024. 2. 1. 17:50
728x90
반응형

내 코드

- 이거 다섯 번 푼 듯...ㅋ.... 첨엔 문제 이해 못 했다(ㅜ?)

- grid 인가...? 옛날부터 탐욕 알고리즘은 나랑 안 맞았다.

- python 코드 ↓

더보기
import sys

input = sys.stdin.readline

w, n = map(int, input().rstrip().split())
metal_dict = []

for metal in range(1, n + 1):
    m, p = map(int, input().rstrip().split())
    metal_dict.append((m, p))

metal_dict.sort(key=lambda x: -x[1])
# sorted_metals = sorted(metal_dict.items(), key = lambda x: (-x[1]))

price = 0
for weight, value in metal_dict:
    if w - weight >= 0:
        w -= weight
        price += weight * value
    else:
        price += w * value
        break

print(price)

- 나는 tuple 을 사용했다. tuple 사용은 익숙하지 않다.

- dictionary가 편해서 첨에 dict로 이렇게 저렇게 했었는데 계속 틀렸습니다가 떴었다.

dict 사용했었을 때는 이렇게 정렬했었음.

- 간만에 c++을 사용해봤다. ↓

더보기
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int w, n;
    cin >> w >> n;

    vector<pair<int, int>> metalVec;

    for (int metal = 1; metal <= n; ++metal) {
        int m, p;
        cin >> m >> p;
        metalVec.emplace_back(m, p);
    }

    sort(metalVec.begin(), metalVec.end(), [](const auto& a, const auto& b) {
        return a.second > b.second;
    });

    int price = 0;

    for (const auto& metal : metalVec) {
        int weight = metal.first;
        int value = metal.second;

        if (w - weight >= 0) {
            w -= weight;
            price += weight * value;
        } else {
            price += w * value;
            break;
        }
    }

    cout << price << endl;

    return 0;
}

ios_base::sync_with_stdio(false);

cin.tie(NULL);
이 부분은 c++ 입출력 속도 향상을 위한 약간의 편법이다.

확실히 python 코드가 더 짧은데 아직은 나는 c++이 더 익숙하다.

 

 

채점 결과

 

문제 원본 : https://softeer.ai/practice/6288

 

문제 접근 참고 영상https://youtu.be/oAOT0fnBLsM?si=JGQjvX6PhXVRRomt

 

728x90
반응형

'Practice > Other Sites...' 카테고리의 다른 글

[소프티어/Softeer] lv2. 회의실 예약 (파이썬)  (0) 2024.02.01