BOJ::16434 드래곤 앤 던전

[BOJ] : https://www.acmicpc.net/problem/16434

시사점

이해(10)

설계(11)

시간 복잡도

공간 복잡도

구현(29)

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
struct cell{
    ull maxHP;
    ull curHP;
    ull attk;
};
struct input{ ull t; ull a;ull h; };
int n;
vector<input> rooms;
bool simulate(cell w){
    for(int i = 0; i < rooms.size(); i++){
        // fight
        if(rooms[i].t == 1){
            cell m = {rooms[i].h, rooms[i].h, rooms[i].a};
            ull w_attkCnt = (m.curHP/w.attk);
            if((m.curHP%w.attk) > 0) w_attkCnt += 1;
            if( (w_attkCnt-1) * m.attk  >= w.curHP ) return false;
            w.curHP -= (w_attkCnt-1) * m.attk;
        }
        // heal
        else{
            w.attk += rooms[i].a;
            w.curHP = min(w.maxHP, w.curHP + rooms[i].h);
        }
    }
    return true;
}
ull binarySearch(cell& w){
    ull ret = numeric_limits<unsigned long long>::max();
    ull begin = 1, mid = 0, end = numeric_limits<unsigned long long>::max() / 10;
    while(begin <= end){
        mid = (begin + end) /2;
        if(mid == 1){
            cout << "HERE" << endl;
        }
        w.maxHP = w.curHP = mid;
        if(simulate(w)){
            ret = min(ret, mid);
            end = mid -1;
        }else{
            begin = mid+1;
        }
    }
    return ret;
}
int main(){
    freopen("input.txt", "r", stdin);
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cell w = {0, 0, 0};
    cin >> n >> w.attk;
    rooms = vector<input>(n, {0, 0, 0});
    for(int i = 0; i < n; i++)
        cin >> rooms[i].t >> rooms[i].a >> rooms[i].h;

    cout << binarySearch(w) << endl;
    return 0;
}

디버깅(x)

좋은 코드

#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
int main(){
    ios_base::sync_with_stdio(false);cin.tie(0);
    
    ll n,atk;cin>>n>>atk;
    ll curr=0, mx=0;
    while(n--){
        int t,a,h; cin>>t>>a>>h;
        if(t==1){
            ll damage=a*(ceil((double)h/atk)-1);
            if(damage>curr) mx+=damage-curr,curr=0;
            else curr-=damage;
        }else{
            atk+=a;
            curr+=h;
            if(curr>mx)curr=mx;
        }
    }
    cout<<mx+1;
}

최적화