개발 공부/알고리즘

HackerRank , C++, Hotel Prices

그냥하는티스토리 2022. 11. 3. 10:30
728x90

문제 자체는 쉽지만,

클래스를 어떻게 활용 할지 고민했던 문제,

특히 virtual을 안쓰면 부모 클래스의 함수가 그대로 호출 되는걸 처음 알게 됨.

 

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


class HotelRoom{
private:
    int bedRooms;
    int bathRooms;
    
public:
    HotelRoom(int bed, int bath ) : bedRooms(bed), bathRooms(bath){
        
    }
    virtual int calculate(){
        return 50* bedRooms + 100 * bathRooms;
    }    
};

class HotelApartment : public HotelRoom{
public:
    HotelApartment(int bed, int bath) : HotelRoom(bed,bath){
        
    }

    int calculate(){

        return HotelRoom::calculate() + 100;
    }    
};


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    
    int N;
    cin >> N;
    int total = 0;
    
    vector<HotelRoom*> vect;
    for(unsigned int i = 0 ; i < N; i++)
    {
        string type;
        int bedRooms, bathRooms;
        cin >> type >> bedRooms >> bathRooms;
        if(type == "standard"){
            vect.push_back(new HotelRoom(bedRooms, bathRooms));
        }
        else {
            vect.push_back(new HotelApartment(bedRooms, bathRooms));
        }
    }
    
    for( auto room : vect)
    {
        total += room->calculate();
    }
    
    cout << total << endl;
    
    for( auto room : vect)
    {
        delete room;
    }
    
    return 0;
}
728x90