diff --git a/advent_of_code/d7/main.cpp b/advent_of_code/d7/main.cpp index 6995b7a..e45cd48 100644 --- a/advent_of_code/d7/main.cpp +++ b/advent_of_code/d7/main.cpp @@ -15,6 +15,17 @@ int fuel_cost(int n){ return result; } +int updated_fuel_cost(int n){ + int result = 0; + + for(auto &crab : crab_pos){ + int dif = abs(crab - n); + result += dif * (dif + 1) / 2; + } + + return result; +} + int main(){ ios::sync_with_stdio(0); cin.tie(0); @@ -38,6 +49,27 @@ int main(){ int target_coord = min(m2, m1); cout << fuel_cost(target_coord) << endl; + upper = crab_pos.back(); + lower = crab_pos.front(); + m1 = (upper + lower) / 2; + m2 = (upper + lower) / 2 + 1; + + while(upper - lower > 1){ + if(updated_fuel_cost(m1) < updated_fuel_cost(m2)){ + upper = m1; + } else{ + lower = m2; + } + + m1 = (upper + lower) / 2; + m2 = (upper + lower) / 2 + 1; + + // cout << m1 << ", fuel: " << updated_fuel_cost(m1) << " " << m2 << ", fuel: " << updated_fuel_cost(m2) << endl; + } + + target_coord = min(m1, m2); + cout << updated_fuel_cost(target_coord) << endl; + cout << flush; return 0;