Wednesday, May 13, 2015

UVa 10620 - A flea on a chessboard

// UVa 10620 - A flea on a chessboard

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <math.h>
#include <sstream>
#include <stdio.h>
using namespace std;

#define integer unsigned long long

integer gcd(integer a, integer b) {
	if (b == 0)
		return a;
	else
		return gcd(b, a % b);
}

integer lcm(integer a, integer b) {
	return a * b / gcd(a, b);
}

int main() {
	integer s, x, y, dx, dy;
	while (cin >> s >> x >> y >> dx >> dy && (s != 0 || x != 0 || y != 0 || dx != 0 || dy != 0)) {
		// don't know why up to lcm is not enough
		integer aa = 2 * lcm(s / gcd(s, dx), s / gcd(s, dy));

		integer sa;
		bool white = false;
		for (integer a = 0; a <= aa; a++) {
			integer xx = (x + a * dx);
			integer yy = (y + a * dy);
			if (xx % s && yy % s) {
				integer xxx = xx / s + 1;
				integer yyy = yy / s + 1;
				if ((xxx & 1) != (yyy & 1)) {
					white = true;
					sa = a;
					break;
				}
			}
		}
		if (white)
			printf("After %llu jumps the flea lands at (%.llu, %.llu).\n", sa, x + sa * dx, y + sa * dy);
		else
			printf("The flea cannot escape from black squares.\n");
	}
	return 0;
}

No comments:

Post a Comment