day15: finish part 2 c++

master
Clyne 2 years ago
parent b6e660ac61
commit e54a0068c9

@ -7,49 +7,58 @@ struct Sensor
{ {
long x, y, power; long x, y, power;
Sensor(long xx, long yy, long pp): Sensor(long xx, long yy, long pp = 0):
x(xx), y(yy), power(pp) {} x(xx), y(yy), power(pp) {}
}; };
std::vector<Sensor> sensors;
bool isDistressBeacon(const Sensor& c)
{
if (c.x < 0 || c.x > 4000000 || c.y < 0 || c.y > 4000000)
return false;
bool found = true;
uint64_t freq = 0;
for (auto& s : sensors) {
auto dist = std::abs(c.x - s.x) + std::abs(c.y - s.y);
if (dist <= s.power) {
found = false;
break;
}
}
return found;
}
int main() int main()
{ {
std::vector<Sensor> sensors;
long px, py, bx, by; long px, py, bx, by;
do {
std::string line; std::string line;
std::getline(std::cin, line); std::getline(std::cin, line);
if (std::cin.eof()) for (; !std::cin.eof(); std::getline(std::cin, line)) {
break;
auto a = sscanf(line.c_str(), auto a = sscanf(line.c_str(),
"Sensor at x=%ld, y=%ld: closest beacon is at x=%ld, y=%ld", "Sensor at x=%ld, y=%ld: closest beacon is at x=%ld, y=%ld",
&px, &py, &bx, &by); &px, &py, &bx, &by);
long power = std::abs(px - bx) + std::abs(py - by); long power = std::abs(px - bx) + std::abs(py - by);
sensors.emplace_back(px, py, power); sensors.emplace_back(px, py, power);
} while (1); }
std::cout << "# of sensors: " << sensors.size() << std::endl;
for (long y = 0; y <= 4000000; ++y) {
std::cout << "\r \r" << y;
fflush(stdout);
for (long x = 0; x <= 4000000; ++x) {
bool h = false;
for (auto& s : sensors) { for (auto& s : sensors) {
auto dist = std::abs(x - s.x) + std::abs(y - s.y); for (long q = 0; q <= (s.power + 1) * 2; ++q) {
if (dist <= s.power) { auto x = s.x + q - s.power - 1;
long spr = (dist - std::abs(s.y - y)); auto y = s.y + q;
x += spr - std::abs(s.x - x); if (isDistressBeacon(Sensor(x, y))) {
h = true; std::cout << x * 4000000 + y << std::endl;
break; return 0;
}
} }
if (!h) { y -= q * 2;
std::cout << std::endl << x << ", " << y << std::endl; if (isDistressBeacon(Sensor(x, y))) {
std::cout << x * 4000000 + y << std::endl;
return 0; return 0;
} }
} }

Loading…
Cancel
Save