Search is not available for this dataset
name
stringlengths 2
112
| description
stringlengths 29
13k
| source
int64 1
7
| difficulty
int64 0
25
| solution
stringlengths 7
983k
| language
stringclasses 4
values |
---|---|---|---|---|---|
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y, dx, dy, cnt, stp;
long long ans;
string s;
map<pair<int, int>, int> vis;
inline int abs(int x) { return x < 0 ? -x : x; }
int main() {
scanf("%d%d%d%d", &n, &m, &x, &y);
cin >> s, dx = s[0] == 'U' ? -1 : 1, dy = s[1] == 'L' ? -1 : 1;
if (x == 1 || x == n || y == 1 || y == m) vis[make_pair(x, y)] = 1, cnt++;
while (cnt != n + m - 2) {
stp++;
if (stp > 1000000) {
puts("-1");
return 0;
}
int ux = dx == 1 ? abs(n - x) : abs(x - 1),
uy = dy == 1 ? abs(m - y) : abs(y - 1);
ans += min(ux, uy), x += dx * min(ux, uy), y += dy * min(ux, uy);
dx = (x == 1 ? 1 : (x == n ? -1 : dx));
dy = (y == 1 ? 1 : (y == m ? -1 : dy));
if (vis.count(make_pair(x, y)) == 0) vis[make_pair(x, y)] = 1, cnt++;
}
printf("%lld\n", ans + 1);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const unsigned long int N = 100001, DIRECTIONS = 5, SIDE_VISITED_INDEX = 0;
unsigned long int n, m, d, x, y;
bool _up[N][DIRECTIONS], _down[N][DIRECTIONS], _left[N][DIRECTIONS],
_right[N][DIRECTIONS];
unsigned long int currentCellsCount, cellsCount;
signed long long int answer;
void init() {
string direction;
unsigned long int p;
cin >> n >> m;
cin >> y >> x >> direction;
if (direction == "DR") {
d = 1;
} else if (direction == "DL") {
d = 2;
} else if (direction == "UR") {
d = 3;
} else if (direction == "UL") {
d = 4;
}
cellsCount = 2 * (n / 2 + m / 2);
p = (x + y) % 2;
if (n % 2 == 1) {
if (p == 0) {
cellsCount++;
}
if (p != m % 2) {
cellsCount++;
}
}
if (m % 2 == 1) {
if (p == 0) {
cellsCount++;
}
if (p != n % 2) {
cellsCount++;
}
}
x--;
y--;
n--;
m--;
}
void solve() {
unsigned long int oldX, oldY;
oldX = 10000000;
oldY = 10000000;
answer = 1;
currentCellsCount = 0;
while (true) {
if (x == 0) {
if (_left[y][d] && (oldX != x || oldY != y)) {
answer = -1;
break;
}
if (!_left[y][SIDE_VISITED_INDEX]) {
_left[y][SIDE_VISITED_INDEX] = true;
currentCellsCount++;
}
_left[y][d] = true;
} else if (x == m) {
if (_right[y][d] && (oldX != x || oldY != y)) {
answer = -1;
break;
}
if (!_right[y][SIDE_VISITED_INDEX]) {
_right[y][SIDE_VISITED_INDEX] = true;
currentCellsCount++;
}
_right[y][d] = true;
}
if (y == 0) {
if (_up[x][d] && (oldX != x || oldY != y)) {
answer = -1;
break;
}
if (!_up[x][SIDE_VISITED_INDEX]) {
_up[x][SIDE_VISITED_INDEX] = true;
currentCellsCount++;
}
_up[x][d] = true;
} else if (y == n) {
if (_down[x][d] && (oldX != x || oldY != y)) {
answer = -1;
break;
}
if (!_down[x][SIDE_VISITED_INDEX]) {
_down[x][SIDE_VISITED_INDEX] = true;
currentCellsCount++;
}
_down[x][d] = true;
}
oldX = x;
oldY = y;
if (currentCellsCount == cellsCount) {
break;
}
if (d == 1) {
if (m - x < n - y) {
answer += m - x;
y += m - x;
x = m;
d = 2;
} else if (m - x > n - y) {
answer += n - y;
x += n - y;
y = n;
d = 3;
} else {
answer += m - x;
x = m;
y = n;
d = 4;
}
continue;
}
if (d == 2) {
if (x < n - y) {
answer += x;
y += x;
x = 0;
d = 1;
} else if (x > n - y) {
answer += n - y;
x -= n - y;
y = n;
d = 4;
} else {
answer += x;
x = 0;
y = n;
d = 3;
}
continue;
}
if (d == 3) {
if (m - x < y) {
answer += m - x;
y -= m - x;
x = m;
d = 4;
} else if (m - x > y) {
answer += y;
x += y;
y = 0;
d = 1;
} else {
answer += y;
x = m;
y = 0;
d = 2;
}
continue;
}
if (d == 4) {
if (x < y) {
answer += x;
y -= x;
x = 0;
d = 3;
} else if (x > y) {
answer += y;
x -= y;
y = 0;
d = 2;
} else {
answer += x;
x = 0;
y = 0;
d = 1;
}
continue;
}
}
}
void output() { cout << answer; }
int main() {
init();
solve();
output();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int Read() {
char c;
while (c = getchar(), (c != '-') && (c < '0' || c > '9'))
;
bool neg = (c == '-');
int ret = (neg ? 0 : c - 48);
while (c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + c - 48;
return neg ? -ret : ret;
}
map<pair<int, int>, int> t;
char s[5];
int N, M, dx, dy, x, y;
long long ans = 1;
int main() {
scanf("%d%d%d%d%s", &N, &M, &x, &y, s);
dx = (s[0] == 'U' ? -1 : 1), dy = (s[1] == 'L' ? -1 : 1);
for (int cb = 1; cb <= 2 * (N + M - 2); cb++) {
t[make_pair(x, y)] = 1;
if (t.size() == N + M - 2) return cout << ans << endl, 0.0;
dx = (x > 1 ? (x < N ? dx : -1) : 1), dy = (y > 1 ? (y < M ? dy : -1) : 1);
int d = min(dx > 0 ? N - x : x - 1, dy > 0 ? M - y : y - 1);
ans += d, x += d * dx, y += d * dy;
}
return puts("-1"), 0.0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int64_t n, m;
void upd(string& str, int64_t& x, int64_t& y) {
if (str[0] == 'D')
++x;
else
--x;
if (str[1] == 'R')
++y;
else
--y;
}
int64_t upd_xy(string& str, int64_t& x, int64_t& y) {
int64_t mx_x = 0, mx_y = 0;
if (str[0] == 'D')
mx_x = n - x;
else if (str[0] == 'U')
mx_x = x - 1;
if (str[1] == 'R')
mx_y = m - y;
else if (str[1] == 'L')
mx_y = y - 1;
int64_t diff = min(mx_x, mx_y);
if (str[0] == 'D')
x += diff;
else
x -= diff;
if (str[1] == 'R')
y += diff;
else
y -= diff;
return diff;
}
void upd_str(string& str, int64_t x, int64_t y, int64_t qx, int64_t qy) {
if ((qx < 1 || qx > n) && (qy < 1 || qy > m)) {
if (str[1] == 'L')
str[1] = 'R';
else if (str[1] == 'R')
str[1] = 'L';
if (str[0] == 'D')
str[0] = 'U';
else if (str[0] == 'U')
str[0] = 'D';
return;
}
if (y == 1 || y == m) {
if (str[1] == 'L')
str[1] = 'R';
else if (str[1] == 'R')
str[1] = 'L';
} else if (x == 1 || x == n) {
if (str[0] == 'D')
str[0] = 'U';
else if (str[0] == 'U')
str[0] = 'D';
}
}
int main(void) {
cin >> n >> m;
int64_t x, y;
cin >> x >> y;
string str;
cin >> str;
set<pair<int64_t, int64_t> > q;
q.insert({x, y});
int64_t ans = 1;
int64_t mx = (n * m / 2) - ((n - 2) * (m - 2) / 2);
for (int i = 0; i < 1000 * 1000; ++i) {
if (q.size() == mx) break;
int64_t qx = x, qy = y;
upd(str, qx, qy);
if (qx < 1 || qx > n || qy < 1 || qy > m) {
upd_str(str, x, y, qx, qy);
}
int64_t diff = upd_xy(str, x, y);
ans += diff;
q.insert({x, y});
}
if (q.size() == mx)
cout << ans << endl;
else
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int R, C;
void findNext(int &ii, int &jj, pair<int, int> &di, int &num) {
if (di.first < 0 && di.second < 0) {
num = min(ii - 1, jj - 1);
} else if (di.first < 0 && di.second > 0) {
num = min(ii - 1, C - jj);
} else if (di.first > 0 && di.second > 0) {
num = min(R - ii, C - jj);
} else {
num = min(R - ii, jj - 1);
}
ii = ii + num * di.first;
jj = jj + num * di.second;
if (ii <= 0)
ii += R;
else if (ii > R)
ii -= R;
if (jj <= 0)
jj += C;
else if (jj > C)
jj -= C;
if ((ii == 1 && jj == 1 && di.first == -1 && di.second == -1) ||
(ii == 1 && jj == C && di.first == -1 && di.second == 1) ||
(ii == R && jj == 1 && di.first == 1 && di.second == -1) ||
(ii == R && jj == C && di.first == 1 && di.second == 1)) {
di.first *= -1;
di.second *= -1;
} else if (ii == 1 || ii == R) {
di.first *= -1;
} else {
di.second *= -1;
}
}
int main() {
cin >> R >> C;
int si, sj;
pair<int, int> di;
string in;
cin >> si >> sj >> in;
if (in == "UL")
di = pair<int, int>(-1, -1);
else if (in == "UR")
di = pair<int, int>(-1, 1);
else if (in == "DR")
di = pair<int, int>(1, 1);
else
di = pair<int, int>(1, -1);
set<pair<int, int> > S;
for (int i = ((si + sj) % 2) + 1; i <= R; i += 2) {
S.insert(pair<int, int>(i, 1));
if (C % 2)
S.insert(pair<int, int>(i, C));
else if (i + 1 <= R)
S.insert(pair<int, int>(i + 1, C));
}
for (int i = ((si + sj) % 2) + 1; i <= C; i += 2) {
S.insert(pair<int, int>(1, i));
if (R % 2)
S.insert(pair<int, int>(R, i));
else if (i + 1 <= C)
S.insert(pair<int, int>(R, i + 1));
}
long long ans = 0;
if (S.find(pair<int, int>(si, sj)) != S.end()) {
ans++;
S.erase(pair<int, int>(si, sj));
}
int sz = S.size();
for (int i = 0; i < sz * 8; i++) {
if (S.empty()) {
cout << ans << endl;
return 0;
}
int num = 0;
findNext(si, sj, di, num);
ans += num;
S.erase(pair<int, int>(si, sj));
}
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import java.util.*;
import java.lang.Math;
import java.lang.Long;
import java.io.*;
import java.math.*;
import java.awt.*;
public class robot{
public static long mod = 1000000007;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int [] floor = new int[m];Arrays.fill(floor,0);
int [] ceil = new int[m];Arrays.fill(ceil,0);
int [] rwal = new int[n];Arrays.fill(rwal,0);
int [] lwal = new int[n];Arrays.fill(lwal,0);
int s = input.nextInt()-1;
int t = input.nextInt()-1;
long result= 0;
int mx = m+n;
if (((m%2)==1) && ((n%2)==1)){
if((s+t)%2==0)
mx+=2;
else
mx-=2;
}
String direction = input.next();
int size = 0;
long steps = 0;
for (long i=0;i<10*(n+m);i++){
if(s==0){
if(ceil[t]==0){
ceil[t] = 1;
size++;
}
direction = direction.replace('U','D');
}
if(s==n-1){
if(floor[t]==0){
floor[t] = 1;
size++;
}
direction = direction.replace('D','U');
}
if(t==0){
if(lwal[s]==0){
lwal[s] = 1;
size++;
}
direction = direction.replace('L','R');
}
if(t==m-1){
if(rwal[s]==0){
rwal[s] = 1;
size++;
}
direction = direction.replace('R','L');
}
if (size==mx && result==0)
result = steps;
if (direction.equals("DR")){
int r = Math.min(n-1-s,m-1-t);
s+= r;
t+= r;
steps +=r;
}
if(direction.equals("DL")){
int r= Math.min(n-1-s,t);
s+= r;
t-= r;
steps +=r;
}
if(direction.equals("UR")){
int r = Math.min(s,m-1-t);
s-= r;
t+= r;
steps +=r;
}
if(direction.equals("UL")){
int r = Math.min(s,t);
s-= r;
t-= r;
steps +=r;
}
}
if (size==mx){
System.out.println(result+1);
}
else
System.out.println(-1);
}
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAX = 100010;
int n, m, x, y;
int k;
bool top[MAX], bottom[MAX], lft[MAX], rgt[MAX];
const int dx[] = {1, 1, -1, -1};
const int dy[] = {1, -1, 1, -1};
int getCnt() {
bool res = x % 2 == y % 2;
int ret = 0;
for (int i = 0; i < (int)(m); i++) ret += (0 == i % 2) == res;
for (int i = 0; i < (int)(m); i++) ret += ((n - 1) % 2 == i % 2) == res;
for (int i = (int)(1); i < (int)(n - 1); i++) ret += (0 == i % 2) == res;
for (int i = (int)(1); i < (int)(n - 1); i++)
ret += ((m - 1) % 2 == i % 2) == res;
return ret;
}
long long solve() {
int cnt = getCnt();
long long ret = 0;
for (int _ = 0; _ < (int)(3000000); _++) {
if (x == 0) {
if (!top[y]) --cnt;
top[y] = true;
} else if (x == n - 1) {
if (!bottom[y]) --cnt;
bottom[y] = true;
} else if (y == 0) {
if (!lft[x]) --cnt;
lft[x] = true;
} else {
if (!rgt[x]) --cnt;
rgt[x] = true;
}
if (cnt == 0) break;
if (k == 0) {
if (x == n - 1 && y == m - 1)
k = 3;
else if (x == n - 1)
k = 2;
else if (y == m - 1)
k = 1;
} else if (k == 1) {
if (x == n - 1 && y == 0)
k = 2;
else if (x == n - 1)
k = 3;
else if (y == 0)
k = 0;
} else if (k == 2) {
if (x == 0 && y == m - 1)
k = 1;
else if (x == 0)
k = 0;
else if (y == m - 1)
k = 3;
} else {
if (x == 0 && y == 0)
k = 0;
else if (x == 0)
k = 1;
else if (y == 0)
k = 2;
}
int d;
if (k == 0)
d = min(n - 1 - x, m - 1 - y);
else if (k == 1)
d = min(n - 1 - x, y);
else if (k == 2)
d = min(x, m - 1 - y);
else
d = min(x, y);
x += d * dx[k];
y += d * dy[k];
ret += d;
}
if (cnt) return -1;
return ret;
}
int main() {
cin >> n >> m >> x >> y;
string dir;
cin >> dir;
if (dir[0] == 'U') k = 1;
k <<= 1;
if (dir[1] == 'L') k |= 1;
--x, --y;
long long ret = solve();
if (ret != -1) ++ret;
cout << ret << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int inf = 2000000000;
const int N = 101000;
int n, m, x, y, dx, dy, tot;
map<int, int> hs[N];
char dir[10];
bool vis[N * 4];
long long ret = 1;
void add(int px, int py) {
if ((px + py) % 2 == (x + y) % 2) hs[px][py] = tot++;
}
void ff() {
if (x == 1 && dx == -1) dx = 1;
if (x == n && dx == 1) dx = -1;
if (y == 1 && dy == -1) dy = 1;
if (y == m && dy == 1) dy = -1;
}
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d%s", &x, &y, dir);
if (dir[0] == 'D')
dx = 1;
else
dx = -1;
if (dir[1] == 'R')
dy = 1;
else
dy = -1;
for (int i = 1; i < m + 1; i++) add(1, i), add(n, i);
for (int i = 2; i < n; i++) add(i, 1), add(i, m);
ff();
for (int rd = 0; rd < 4 * (n + m); rd++) {
if (!vis[hs[x][y]]) --tot;
if (!tot) break;
vis[hs[x][y]] = 1;
int pv = min((dx == 1) ? n - x : x - 1, (dy == 1) ? m - y : y - 1);
ret += pv;
x += dx * pv;
y += dy * pv;
ff();
}
if (tot == 0)
printf("%I64d\n", ret);
else
puts("-1");
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
set<pair<int, int> > s1;
set<pair<pair<int, int>, int> > s2;
int main() {
int n, m, x, y;
string s;
cin >> n >> m >> x >> y >> s;
int num = 0;
if (x == 1) s[0] = 'D';
if (x == n) s[0] = 'U';
if (y == 1) s[1] = 'R';
if (y == m) s[1] = 'L';
if (s[0] == 'U') num += 2;
if (s[1] == 'L') num++;
long long val = (n * 1ll * m);
long long tot = val / 2 + (val & 1);
val = ((n - 2) * 1ll * (m - 2));
tot -= (val / 2 + (val & 1));
if ((x & 1) != (y & 1)) tot = n + n + m + m - 4 - tot;
bool f = true;
long long res = 1;
while (1) {
s1.insert(make_pair(x, y));
if (s1.size() == tot) break;
if (s2.find(make_pair(make_pair(x, y), num)) != s2.end()) {
f = false;
break;
}
s2.insert(make_pair(make_pair(x, y), num));
int dist = 1000000000;
if ((num >> 1) & 1)
dist = ((dist < x - 1) ? (dist) : (x - 1));
else
dist = ((dist < n - x) ? (dist) : (n - x));
if ((num)&1)
dist = ((dist < y - 1) ? (dist) : (y - 1));
else
dist = ((dist < m - y) ? (dist) : (m - y));
if ((num >> 1) & 1)
x -= dist;
else
x += dist;
if ((num)&1)
y -= dist;
else
y += dist;
res += dist;
if ((x == 1) || (x == n)) num ^= 2;
if ((y == 1) || (y == m)) num ^= 1;
}
if (f)
cout << res << endl;
else
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y, dir, dat[4][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
long long ans = 1;
char s[3];
map<int, map<int, map<int, bool> > > vis;
bool atedge() { return x == 1 || x == n || y == 1 || y == m; }
void func() {
int step = min(dir < 2 ? n - x : x - 1, dir & 1 ? y - 1 : m - y);
x += step * dat[dir][0], y += step * dat[dir][1];
ans += step;
if (x == 1 && y == 1)
dir = 0;
else if (x == 1 && y == m)
dir = 1;
else if (x == n && y == 1)
dir = 2;
else if (x == n && y == m)
dir = 3;
else if (x == 1)
dir -= 2;
else if (x == n)
dir += 2;
else if (y == 1)
dir -= 1;
else if (y == m)
dir += 1;
}
int main() {
scanf("%d%d%d%d%s", &n, &m, &x, &y, s);
if (s[0] != 'D') dir += 2;
if (s[1] != 'R') dir += 1;
int cnt = n + m - 2;
if (atedge()) --cnt, vis[x][y][dir] = 1;
while (cnt) {
func();
if (!vis[x].count(y)) {
vis[x][y][dir] = 1;
--cnt;
} else {
if (vis[x][y].count(dir)) return printf("-1\n"), 0;
vis[x][y][dir] = 1;
}
}
printf("%lld\n", ans);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
set<pair<int, int> > s;
int n, m, x, y, need;
int dir1, dir2;
long long ans;
int main() {
scanf("%d%d%d%d", &n, &m, &x, &y);
char c = getchar();
while (c != 'D' && c != 'U') c = getchar();
if (c == 'D')
dir1 = 1;
else
dir1 = -1;
while (c != 'R' && c != 'L') c = getchar();
if (c == 'R')
dir2 = 1;
else
dir2 = -1;
for (int i = 1; i <= (n + m) * 4; i++) {
s.insert(make_pair(x, y));
if (s.size() == (n + m - 2)) {
printf("%I64d", ans + 1);
return 0;
}
int dis1, dis2;
if (dir1 == 1)
dis1 = n - x;
else
dis1 = x - 1;
if (dir2 == 1)
dis2 = m - y;
else
dis2 = y - 1;
ans += min(dis1, dis2);
x += dir1 * min(dis1, dis2);
y += dir2 * min(dis1, dis2);
if (dis1 == dis2) {
dir1 = -dir1;
dir2 = -dir2;
} else if (dis1 < dis2)
dir1 = -dir1;
else
dir2 = -dir2;
}
puts("-1");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int N, M, X, Y, dx, dy;
map<pair<int, int>, int> F;
void doit() {
char s[3];
long long ans = 1;
scanf("%d%d%d%d%s", &N, &M, &X, &Y, s), dx = s[0] == 'U' ? -1 : 1,
dy = s[1] == 'L' ? -1 : 1;
for (int i = 1; i <= (N + M) * 2; i++) {
F[make_pair(X, Y)] = 1;
if (F.size() == N + M - 2) {
cout << ans << endl;
return;
}
int u = dx < 0 ? X - 1 : N - X, v = dy < 0 ? Y - 1 : M - Y, w = min(u, v);
X += dx * w, Y += dy * w, ans += w;
if (u == w) dx *= -1;
if (v == w) dy *= -1;
}
puts("-1");
}
int main() {
doit();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int INF = (int)1e9 + 7;
int main() {
int h, w;
cin >> h >> w;
int ci, cj;
cin >> ci >> cj, ci--, cj--;
string dir;
cin >> dir;
int di = dir[0] == 'D' ? 1 : -1;
int dj = dir[1] == 'R' ? 1 : -1;
int cnt = 0, pari = (ci + cj) & 1;
vector<vector<bool>> edge_h(2, vector<bool>(h));
for (int i = 0; i < h; i++) {
if (((0 + i) & 1) == pari) cnt += edge_h[0][i] = true;
if (((w - 1 + i) & 1) == pari) cnt += edge_h[1][i] = true;
}
vector<vector<bool>> edge_w(2, vector<bool>(w));
for (int j = 0; j < w; j++) {
if (((0 + j) & 1) == pari) cnt += edge_w[0][j] = true;
if (((h - 1 + j) & 1) == pari) cnt += edge_w[1][j] = true;
}
long long ans = 1;
for (int _ = 0; _ <= (h + w) * 2 * 2; _++) {
if (ci == 0 && edge_w[0][cj]) edge_w[0][cj] = false, cnt--;
if (ci == h - 1 && edge_w[1][cj]) edge_w[1][cj] = false, cnt--;
if (cj == 0 && edge_h[0][ci]) edge_h[0][ci] = false, cnt--;
if (cj == w - 1 && edge_h[1][ci]) edge_h[1][ci] = false, cnt--;
if (cnt == 0) return !(cout << ans << endl);
if (ci == 0) di = 1;
if (ci == h - 1) di = -1;
if (cj == 0) dj = 1;
if (cj == w - 1) dj = -1;
int mi = INF;
if (di > 0) mi = min(mi, h - 1 - ci);
if (di < 0) mi = min(mi, ci);
if (dj > 0) mi = min(mi, w - 1 - cj);
if (dj < 0) mi = min(mi, cj);
ans += mi;
ci += mi * di;
cj += mi * dj;
}
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int step[2] = {-1, 1}, mn = 101000;
int n, m, xs, ys, kx, ky, x, y, fx, fy, cnt;
long long ans;
string st;
set<int> T[mn];
void fix(int x, int y, int& fx, int& fy) {
if (x == 1)
fx = 1;
else if (x == n)
fx = 0;
if (y == 1)
fy = 1;
else if (y == m)
fy = 0;
}
int run(int& x, int& y, int& fx, int& fy) {
int l = n;
if (fx == 0)
l = min(l, x - 1);
else
l = min(l, n - x);
if (fy == 0)
l = min(l, y - 1);
else
l = min(l, m - y);
x += l * step[fx], y += l * step[fy];
fix(x, y, fx, fy);
return l;
}
int main() {
cin >> n >> m >> xs >> ys >> st;
kx = st[0] == 'D', ky = st[1] == 'R';
fix(xs, ys, kx, ky);
x = xs, y = ys, fx = kx, fy = ky;
ans = cnt = 1;
T[x].insert(y);
for (;;) {
ans += run(x, y, fx, fy);
if (!T[x].count(y)) {
++cnt;
T[x].insert(y);
}
if (cnt == n + m - 2) break;
if (x == xs && y == ys && fx == kx && fy == ky) break;
}
if (cnt == n + m - 2)
cout << ans << endl;
else
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
const int MOD = (int)1e9 + 7;
const int N = (int)1e5 + 7;
const double eps = 1e-6;
bool eq(const double &a, const double &b) { return fabs(a - b) < eps; }
bool ls(const double &a, const double &b) { return a + eps < b; }
bool le(const double &a, const double &b) { return eq(a, b) || ls(a, b); }
long long powmod(long long a, long long b) {
long long res = 1;
a %= MOD;
assert(b >= 0);
for (; b; b >>= 1) {
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
}
return res;
}
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
int n, m, x, y, dx, dy;
char dir[2];
set<pair<int, int> > S;
void Init() {}
int Solve() {
dx = dir[0] == 'U' ? -1 : 1;
dy = dir[1] == 'L' ? -1 : 1;
int remain = n + m - 2;
if (x == 1 || x == n || y == 1 || y == m) {
S.insert({x, y});
--remain;
}
long long ans = 1;
for (int i = (0); i < (4 * N); ++i) {
int step;
int tx = dx == 1 ? n - x : x - 1;
int ty = dy == 1 ? m - y : y - 1;
step = min(tx, ty);
ans += step;
x += step * dx;
y += step * dy;
if (S.find({x, y}) == S.end()) {
S.insert({x, y});
--remain;
if (!remain) return !printf("%I64d\n", ans);
}
if (x == 1 && dx == -1 || x == n && dx == 1) dx = -dx;
if (y == 1 && dy == -1 || y == m && dy == 1) dy = -dy;
}
return !puts("-1");
}
int main() {
while (~scanf("%d%d%d%d%s", &n, &m, &x, &y, dir)) {
Init();
Solve();
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, bool> fuck;
int n, m;
char s[5];
int x, y;
long long ans;
int dx, dy;
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d", &x, &y);
scanf("%s", s + 1);
if (s[1] == 'U')
dx = -1;
else
dx = 1;
if (s[2] == 'L')
dy = -1;
else
dy = 1;
int fis = 0;
int test = 1000000;
while (test--) {
pair<int, int> now = pair<int, int>(x, y);
if (!fuck[now]) {
fuck[now] = 1;
fis++;
}
if (fis == n + m - 2) {
cout << ans + 1;
return 0;
}
int xl, yl, l;
int ex, ey;
if (dx == -1)
xl = x - 1;
else
xl = n - x;
if (dy == -1)
yl = y - 1;
else
yl = m - y;
if (xl < yl) {
ex = -dx;
ey = dy;
l = xl;
} else {
if (xl > yl) {
ey = -dy;
ex = dx;
l = yl;
} else {
ex = -dx;
ey = -dy;
l = yl;
}
}
x += dx * l;
y += dy * l;
ans += 1ll * l;
dx = ex;
dy = ey;
}
printf("-1\n");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int cnt1, cnt2;
map<int, bool> M[100001];
int main() {
int n, m, x, y, d, dx, dy;
char dir[4];
scanf("%d%d%d%d", &n, &m, &x, &y);
scanf("%s", dir);
if (dir[0] == 'U')
dx = -1;
else
dx = 1;
if (dir[1] == 'R')
dy = 1;
else
dy = -1;
int cnt = m + n - 2, time = 0;
if (x == 1 || x == n || y == 1 || y == m) M[x][y] = 1, cnt--;
long long ans = 1;
while (time <= 1000100) {
time++;
int dis = 2e9;
if (dx == 1)
dis = min(dis, n - x);
else
dis = min(dis, x - 1);
if (dy == 1)
dis = min(dis, m - y);
else
dis = min(dis, y - 1);
ans += (long long)dis;
x += dx * dis;
y += dy * dis;
if (x == 1) dx = 1;
if (x == n) dx = -1;
if (y == 1) dy = 1;
if (y == m) dy = -1;
if (!M[x][y]) M[x][y] = 1, cnt--;
if (!cnt) {
cout << ans << endl;
return 0;
}
}
printf("-1\n");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int pd[101010][4];
char s[5];
int n, m, rem;
void paint(int x, int y, int tx, int ty) {
int f = ((tx) >> 31) + 2 * ((ty) >> 31);
int t;
int tt;
if (x == 1)
t = 0, tt = y;
else if (x == n)
t = 1, tt = y;
else if (y == 1)
t = 2, tt = x;
else
t = 3, tt = x;
if (rem && ((pd[tt][t] >> f) & 1)) {
printf("-1");
exit(0);
}
if (!pd[tt][t]) rem--;
pd[tt][t] |= 1 << f;
}
int main() {
int x, y;
scanf("%d%d%d%d%s", &n, &m, &x, &y, s);
int ty = (s[1] == 'R' ? 1 : -1), tx = (s[0] == 'D' ? 1 : -1);
long long ans = 0;
rem = m + n - 2;
if ((x == 1 && tx == -1) || (x == n && tx == 1)) tx *= -1;
if ((y == 1 && ty == -1) || (y == m && ty == 1)) ty *= -1;
paint(x, y, tx, ty);
while (rem) {
int mxd = 101010;
if (tx == 1)
mxd = min(mxd, n - x);
else
mxd = min(mxd, x - 1);
if (ty == 1)
mxd = min(mxd, m - y);
else
mxd = min(mxd, y - 1);
x += mxd * tx;
y += mxd * ty;
if ((x == 1 && tx == -1) || (x == n && tx == 1)) tx *= -1;
if ((y == 1 && ty == -1) || (y == m && ty == 1)) ty *= -1;
ans += mxd;
paint(x, y, tx, ty);
}
printf("%I64d", ans + 1);
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;
import java.math.*;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;
public class Main{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
AC solver = new AC();
solver.solve(in, out);
out.close();
}
}
class AC {
int n , m;
boolean judge(int x,int y) {
return 1<=x && x <= n && 1 <= y && y <= m;
}
int x , y , dx , dy;
long go()
{
int delta;
if(dx < 0) {
if(dy < 0) {
delta = Math.min(x-1, y-1);
} else {
delta = Math.min(m-y, x-1);
}
} else {
if(dy < 0) {
delta = Math.min(n-x, y-1);
} else {
delta = Math.min(n-x,m-y);
}
}
x += dx * delta;
y += dy * delta;
if(x+dx<1 || x+dx>n) dx *= -1;
if(y+dy<1 || y+dy>m) dy *= -1;
return (long)x*dx*1000000 + y*dy;
}
public void solve(InputReader in, PrintWriter out) {
int x0 , y0;
String cmd;
HashSet<Long> mp = new HashSet<Long>();
HashSet<Long> M = new HashSet<Long>();
n = in.nextInt();
m = in.nextInt();
x0 = in.nextInt(); y0 = in.nextInt();
cmd = in.next();
int tot = n + m - 2;
if(cmd.charAt(0)=='D') {
dx = 1;
} else dx = -1;
if(cmd.charAt(1)=='R') {
dy = 1;
} else dy = -1;
long ans = 1;
x = x0 ; y = y0;
if(x0==1 || x0==n || y0==1 || y0==m){
M.add((long)x0*1000000+y0);
tot --;
}
while(true) {
long tmp = go();
if(mp.contains(tmp)){
ans = -1;
break;
} else {
mp.add(tmp);
}
ans += Math.abs(x - x0);
//out.println(x+" "+y);
x0 = x ; y0 = y ;
long flag = (long)x0*1000000+y0;
if(!M.contains(flag)) {
// out.println(tot);
M.add(flag);
if(--tot == 0) break;
}
}
out.println(ans);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
if (!hasNext())
throw new RuntimeException();
return tokenizer.nextToken();
}
boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
return false;
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int mod = 1e9 + 7;
int n, m, a, b;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + c - '0';
c = getchar();
}
return x * f;
}
int dx, dy;
inline bool cor(int x, int y) {
if (x == 1 && y == 1) return 1;
if (x == 1 && y == m) return 1;
if (x == n && y == 1) return 1;
if (x == n && y == m) return 1;
return 0;
}
long long ans, sum;
map<long long, bool> vis, pd;
int main() {
n = read(), m = read();
a = read(), b = read();
string s;
cin >> s;
ans = 1ll * n * m - n - m + 2ll;
dx = (s[0] == 'D') ? 1 : -1;
dy = (s[1] == 'R') ? 1 : -1;
if ((n & 1) && (m & 1)) {
if (!((a + b) & 1) || ((n == m) && n > 3)) return puts("-1"), 0;
sum = 1;
int xx = a, yy = b;
while (1) {
int aa, bb;
if (dx == 1 && dy == 1) {
aa = n, bb = n + b - a;
if (bb > m) bb = m, aa = m + a - b;
} else if (dx == 1 && dy == -1) {
aa = n, bb = a + b - n;
if (bb < 1) bb = 1, aa = a + b - 1;
} else if (dx == -1 && dy == 1) {
aa = 1, bb = a + b - 1;
if (bb > m) bb = m, aa = a + b - m;
} else {
aa = 1, bb = 1 + b - a;
if (bb < 1) bb = 1, aa = 1 + a - b;
}
if (a ^ aa || b ^ bb) pd[1ll * a * maxn + b] = 1;
long long val = 1ll * aa * maxn + bb;
if (pd[val])
return printf("%lld\n", (2ll * sum >= 1ll * n * m - 1) ? sum : -1), 0;
pd[val] = 1;
sum += abs(a - aa);
a = aa, b = bb;
if (a == 1 || a == n) dx = -dx;
if (b == 1 || b == m) dy = -dy;
}
return 0;
}
while (!cor(a, b)) {
int aa, bb;
if (dx == 1 && dy == 1) {
aa = n, bb = n + b - a;
if (bb > m) bb = m, aa = m + a - b;
ans += (aa - a);
} else if (dx == 1 && dy == -1) {
aa = n, bb = a + b - n;
if (bb < 1) bb = 1, aa = a + b - 1;
ans += (aa - a);
} else if (dx == -1 && dy == 1) {
aa = 1, bb = a + b - 1;
if (bb > m) bb = m, aa = a + b - m;
ans += (a - aa);
} else {
aa = 1, bb = 1 + b - a;
if (bb < 1) bb = 1, aa = 1 + a - b;
ans += (a - aa);
}
a = aa, b = bb;
long long val = 1ll * a * maxn + b;
if (vis[val]) return puts("-1"), 0;
vis[val] = 1;
if (a == 1 || a == n) dx = -dx;
if (b == 1 || b == m) dy = -dy;
}
a = b = dx = dy = 1;
while (1) {
int aa, bb;
if (dx == 1 && dy == 1) {
aa = n, bb = n + b - a;
if (bb > m) bb = m, aa = m + a - b;
sum += (aa - a);
} else if (dx == 1 && dy == -1) {
aa = n, bb = a + b - n;
if (bb < 1) bb = 1, aa = a + b - 1;
sum += (aa - a);
} else if (dx == -1 && dy == 1) {
aa = 1, bb = a + b - 1;
if (bb > m) bb = m, aa = a + b - m;
sum += (a - aa);
} else {
aa = 1, bb = 1 + b - a;
if (bb < 1) bb = 1, aa = 1 + a - b;
sum += (a - aa);
}
a = aa, b = bb;
long long val = 1ll * a * maxn + b;
if (pd[val]) return puts("-1"), 0;
pd[val] = 1;
if (a == 1 || a == n) dx = -dx;
if (b == 1 || b == m) dy = -dy;
if (sum == 1ll * (n - 1) * (m - 1)) break;
}
printf("%lld\n", ans);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, uz, dz, lz, rz;
int u[100010], d[100010], l[100010], r[100010];
long long ans;
int paint(int x, int y) {
int f = 0;
if (x == 1) {
u[y]++;
if (u[y] == 1) uz--;
if (u[y] == 3) f = 1;
}
if (x == n) {
d[y]++;
if (d[y] == 1) dz--;
if (d[y] == 3) f = 1;
}
if (y == 1) {
l[x]++;
if (l[x] == 1) lz--;
if (l[x] == 3) f = 1;
}
if (y == m) {
r[x]++;
if (r[x] == 1) rz--;
if (r[x] == 3) f = 1;
}
return f;
}
void dfs(int x, int y, int w) {
int x1, y1, w1;
if (w == 0) {
if (x == y) {
x1 = y1 = 1, w1 = 3;
ans += x - 1;
}
if (x > y) {
x1 = x - (y - 1);
y1 = 1;
w1 = 1;
ans += y - 1;
}
if (x < y) {
y1 = y - (x - 1);
x1 = 1;
w1 = 2;
ans += x - 1;
}
}
if (w == 1) {
if (x == m - y + 1) {
x1 = 1;
y1 = m, w1 = 2;
ans += x - 1;
}
if (x > m - y + 1) {
x1 = x - (m - y);
y1 = m;
w1 = 0;
ans += m - y;
}
if (x < m - y + 1) {
y1 = y + (x - 1);
x1 = 1;
w1 = 3;
ans += x - 1;
}
}
if (w == 2) {
if (n - x + 1 == y) {
x1 = n;
y1 = 1;
w1 = 1;
ans += y - 1;
}
if (n - x + 1 > y) {
x1 = x + (y - 1);
y1 = 1;
w1 = 3;
ans += y - 1;
}
if (n - x + 1 < y) {
y1 = y - (n - x);
x1 = n;
w1 = 0;
ans += n - x;
}
}
if (w == 3) {
if (n - x == m - y) {
x1 = n;
y1 = m;
w1 = 0;
ans += n - x;
}
if (n - x > m - y) {
x1 = x + (m - y);
y1 = m;
w1 = 2;
ans += m - y;
}
if (n - x < m - y) {
y1 = y + (n - x);
x1 = n;
w1 = 1;
ans += n - x;
}
}
if (x1 != x || y1 != y)
if (paint(x1, y1) || (lz + rz + dz + uz == 0)) return;
dfs(x1, y1, w1);
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
int x, y, w = 0;
uz = dz = n / 2;
lz = rz = m / 2;
char s[20];
scanf("%d%d", &x, &y);
scanf("%s", s);
if (s[0] == 'D') w = 2;
if (s[1] == 'R') w++;
if (m & 1)
if ((x + y) & 1) {
if ((n & 1) == 0) dz++;
} else {
uz++;
if (n & 1) dz++;
}
if (n & 1)
if ((x + y) & 1) {
if ((m & 1) == 0) rz++;
} else {
lz++;
if (m & 1) rz++;
}
memset(u, 0, sizeof u);
memset(d, 0, sizeof d);
memset(l, 0, sizeof l);
memset(r, 0, sizeof r);
if (x == 1) u[y] = 1, uz--;
if (x == n) d[y] = 1, dz--;
if (y == 1) l[x] = 1, lz--;
if (y == m) r[x] = 1, rz--;
ans = 0;
dfs(x, y, w);
if (lz + rz + dz + uz > 0) ans = -2;
printf("%I64d\n", ans + 1);
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int lim = 1000000;
int n, m;
int x, y;
string dr;
int dx, dy;
set<pair<int, int> > was;
long long res;
void Calc(int &t1, int &t2) {
if (dx == 1) t1 = n - x;
if (dx == -1) t1 = x - 1;
if (dy == 1) t2 = m - y;
if (dy == -1) t2 = y - 1;
}
int main() {
cin >> n >> m;
cin >> x >> y >> dr;
if (dr == "DR") {
dx = 1;
dy = 1;
} else if (dr == "UL") {
dx = -1;
dy = -1;
} else if (dr == "UR") {
dx = -1;
dy = 1;
} else {
dx = 1;
dy = -1;
}
int cnt = lim;
res++;
while (cnt--) {
was.insert(pair<int, int>(x, y));
if (was.size() == n + m - 2) {
printf("%I64d\n", res);
return 0;
}
int t1, t2;
do {
Calc(t1, t2);
if (t1 == 0) dx = -dx;
if (t2 == 0) dy = -dy;
if (t1 && t2) break;
} while (true);
if (t1 <= t2) {
res += t1;
x += t1 * dx;
y += t1 * dy;
dx = -dx;
} else {
res += t2;
x += t2 * dx;
y += t2 * dy;
dy = -dy;
}
if (t1 == t2) dy = -dy;
}
printf("-1\n");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
int sx, sy;
string sd;
cin >> n >> m >> sx >> sy >> sd;
if (sx == 1)
sd[0] = 'D';
else if (sx == n)
sd[0] = 'U';
if (sy == 1)
sd[1] = 'R';
else if (sy == m)
sd[1] = 'L';
long long res = 1;
set<pair<int, int> > pS;
pS.insert(make_pair(sx, sy));
int x = sx, y = sy;
string d = sd;
do {
int s = min(d[0] == 'U' ? x - 1 : n - x, d[1] == 'L' ? y - 1 : m - y);
res += s;
x += d[0] == 'U' ? -s : s;
y += d[1] == 'L' ? -s : s;
if (x == 1)
d[0] = 'D';
else if (x == n)
d[0] = 'U';
if (y == 1)
d[1] = 'R';
else if (y == m)
d[1] = 'L';
pS.insert(make_pair(x, y));
if ((int)pS.size() == n + m - 2) {
cout << res << endl;
return 0;
}
} while (x != sx || y != sy || d != sd);
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
bool vis[400050];
int H, W;
int x, y, dx, dy;
void redirect() {
int tx = x + dx;
if (tx <= 0 || W < tx) dx = -dx;
int ty = y + dy;
if (ty <= 0 || H < ty) dy = -dy;
}
int main() {
istream& in = cin;
in >> H >> W;
in >> y >> x;
char tv, th;
in >> tv >> th;
dy = (tv == 'U' ? -1 : 1);
dx = (th == 'L' ? -1 : 1);
memset(vis, false, sizeof(vis));
long long count = 1;
while (x != 1 && x != W) {
redirect();
x += dx;
y += dy;
count++;
}
int endNum;
if (H % 2 && W % 2) {
if (y % 2) {
endNum = (H / 2 + 1) * 2;
} else {
endNum = (H / 2) * 2;
}
} else {
endNum = H;
}
for (int reachNum = 0;;) {
int chkId = y + (x == 1 ? 0 : H) + (dy == -1 ? 0 : H * 2);
int chkId2 = y + (x == 1 ? 0 : H) + (dy == 1 ? 0 : H * 2);
if (vis[chkId]) {
count = -1;
break;
}
vis[chkId] = true;
if (!vis[chkId2]) {
reachNum++;
}
if (reachNum == endNum) {
if (count < H * W / 2) count = H * W / 2;
break;
}
redirect();
int move = W - 1;
if (dy == 1 && y != 1) {
move += y - 1;
} else {
move += H - y + H - 1;
}
bool isDown = ((move - 1) / (H - 1)) % 2 == 0;
if (move >= H) {
move--;
move %= (H - 1);
y = isDown ? move + 2 : H - move - 1;
} else {
y = move + 1;
}
x = (x == 1 ? W : 1);
dy = isDown ? 1 : -1;
count += W - 1;
}
cout << count << endl;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
long long min(long long a, long long b) { return a < b ? a : b; }
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
long long e_gcd(long long a, long long b, long long &x, long long &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
long long ans = e_gcd(b, a % b, x, y);
long long temp = x;
x = y;
y = temp - a / b * y;
return ans;
}
long long n, m;
long long x, y;
char str[3];
bool judge(long long a, long long b) {
if ((a <= 1 || a >= n) || (b <= 1 || b >= m)) return 1;
return 0;
}
bool jd(long long a, long long b) {
if ((a <= 1 || a >= n) && (b <= 1 || b >= m)) return 1;
return 0;
}
long long pw(long long a, long long b, long long mod) {
long long s = 1;
while (b) {
if (b & 1) s = (s * a) % mod;
a = (a * a) % mod;
b = b / 2;
}
return s;
}
long long duo() {
int a, b;
if (str[0] == 'D')
a = n - x - 1;
else
a = x - 2;
if (str[1] == 'R')
b = m - y - 1;
else
b = y - 2;
return a > b ? b : a;
}
int main() {
scanf("%lld%lld", &n, &m);
scanf("%lld%lld", &x, &y);
scanf("%s", str);
if (n == 1 && m == 1) {
printf("%d\n", 0);
return 0;
}
if (n == 1 || m == 1) {
if (n <= 3 && m <= 3) {
printf("1\n");
return 0;
}
printf("%d\n", -1);
return 0;
}
long long u = gcd(n - 1, m - 1);
if (u > 2) {
printf("-1\n");
return 0;
}
if (x == 1 && y == 1 || x == n && y == m) {
if (str[0] == 'L' && str[1] == 'D' || str[0] == 'R' && str[1] == 'U') {
printf("-1\n");
return 0;
}
if (str[0] == 'R' && str[1] == 'D' || str[0] == 'L' && str[1] == 'U') {
printf("-1\n");
return 0;
}
}
if (u == 2) {
long long bian = n / 2 * 2 + m / 2 * 2;
long long sum = 1LL * n * m / 2 * 2 - bian;
if ((x + y) % 2 == 0) {
printf("-1\n");
return 0;
}
if (judge(x, y)) {
long long ff;
if (x == 1 || x == n) {
ff = n - 2;
if (str[1] == 'L') {
ff = min(ff, m - y - 1);
} else
ff = min(ff, y - 2);
}
if (y == 1 || y == m) {
ff = m - 2;
if (str[0] == 'U') {
ff = min(ff, n - x - 1);
} else
ff = min(ff, x - 2);
}
printf("%lld\n", sum - ff);
return 0;
}
printf("%lld\n", sum - duo());
return 0;
} else {
long long bian = n + m - 2;
long long sum = 1LL * n * m / 2 * 2 - bian;
if (jd(x, y)) {
printf("%lld\n", sum);
return 0;
}
long long xx, yy;
long long a, b;
if (str[0] == 'U')
a = n - x + 1;
else
a = x;
if (str[1] == 'L')
b = m - y + 1;
else
b = y;
long long f = b - a;
e_gcd(1 - n, m - 1, xx, yy);
long long uuu = xx * (n - 1) - yy * (m - 1);
if (uuu > 0 && f < 0) {
xx = xx * -1;
yy = yy * -1;
}
if (uuu < 0 && f > 0) {
xx = xx * -1;
yy = yy * -1;
}
if (f < 0) f = f * -1;
while (xx < 0 || yy < 0) {
xx = xx + m - 1;
yy = yy + n - 1;
}
xx = xx * f;
yy = yy * f;
long long ans = -2;
long long mx = xx % (m - 1);
long long yux = xx / (m - 1);
if (yy - yux * (n - 1) >= 0) {
ans = 2 * sum - (n - 1) * mx - a;
}
long long my = yy % (n - 1);
long long yuy = yy / (n - 1);
if (xx - yuy * (m - 1) >= 0) {
if (ans == -2)
ans = 2 * sum - (m - 1) * my - b;
else {
ans = min(ans, 2 * sum - (m - 1) * my - b);
}
}
printf("%lld\n", ans);
return 0;
}
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.math.*;
import java.util.*;
@SuppressWarnings("unused")
public class D {
private final static boolean autoflush = false;
private static final int MOD = (int) 1e9 + 7;
private static BigInteger BMOD = valueOf(MOD);
private static final double eps = 1e-9;
private static final int INF = (int) 1e9;
private static final Error NO = new Error("NO");
public D () {
N = sc.nextInt();
M = sc.nextInt();
int X = sc.nextInt();
int Y = sc.nextInt();
int [] T = dir(sc.next());
A = new int [N]; B = new int [N];
C = new int [M]; D = new int [M];
Z = 2 * (N/2 + M/2); int P = (X+Y) % 2;
if (N % 2 == 1 && P == 0) ++Z;
if (N % 2 == 1 && P == (1 + M) % 2) ++Z;
if (M % 2 == 1 && P == 0) ++Z;
if (M % 2 == 1 && P == (1 + N) % 2) ++Z;
long res = 1;
for (;;) {
if (mark(X, Y))
break;
res += next(X, Y, T);
X = W[0]; Y = W[1];
}
exit(res);
}
int N, M, Z, K = 0;
int [] A, B, C, D, W = new int [2];
int next(int X, int Y, int [] T) {
if (X == 1) T[0] = 1;
if (X == N) T[0] = -1;
if (Y == 1) T[1] = 1;
if (Y == M) T[1] = -1;
int t = INF, dx = T[0], dy = T[1];
if (dx == 1) t = min(t, N - X);
if (dx == -1) t = min(t, X - 1);
if (dy == 1) t = min(t, M - Y);
if (dy == -1) t = min(t, Y - 1);
X += t * dx; Y += t * dy;
W[0] = X; W[1] = Y;
return t;
}
void set(int [] T, int dx, int dy) {
T[0] = dx; T[1] = dy;
}
boolean mark(int X, int Y) {
boolean res = false;
if (Y == 1)
res = res || inc(A, X);
if (Y == M)
res = res || inc(B, X);
if (X == 1)
res = res || inc(C, Y);
if (X == N)
res = res || inc(D, Y);
return res;
}
boolean inc(int [] A, int X) {
if (A[X-1] == 0) ++K; ++A[X-1];
if (A[X-1] == 3)
exit(-1);
return K == Z;
}
int [] dir (String D) {
String [] S = { "UL", "UR", "DL", "DR" };
int [][] T = { { -1, -1 }, { -1, 1 }, { 1, -1 }, { 1, 1 }};
for (int i : rep(4))
if (D.equals(S[i]))
return T[i];
throw new Error();
}
////////////////////////////////////////////////////////////////////////////////////
private static int [] rep(int N) { return rep(0, N); }
private static int [] rep(int S, int T) { int [] res = new int [max(T-S, 0)]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [] req(int S, int T) { return rep(S, T+1); }
private static int [] sep(int N) { return sep(0, N); }
private static int [] sep(int S, int T) { int [] res = new int [max(T-S, 0)]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; }
private static int [] seq(int S, int T) { return sep(S, T+1); }
private static int [] ccw (int [] D) { return new int [] { -D[1], D[0] }; }
private static int [] cw (int [] D) { return new int [] { D[1], -D[0] }; }
private static <T> T ceiling(SortedSet<T> S, T x) { // Java 1.5 and below
SortedSet<T> T = S.tailSet(x);
return T.isEmpty() ? null : T.first();
}
private static <T> T floor(SortedSet<T> S, T x) { // Java 1.5 and below
if (S.contains(x))
return x;
else {
SortedSet<T> T = S.headSet(x);
return T.isEmpty() ? null : T.last();
}
}
private static int [] digits(long N, int B, int sz) {
int [] res = new int [sz];
for (int i : sep(sz))
if (N > 0) {
res[i] = (int)(N % B);
N /= B;
}
return res;
}
private static int digitSum(long N) {
int res = 0;
for (; N > 0; res += N % 10, N /= 10);
return res;
}
private static <T extends Comparable<T>> T max(T x, T y) { return x.compareTo(y) > 0 ? x : y; }
private static long mod(long x) { return mod(x, MOD); }
private static long mod(long x, long mod) { return ((x % mod) + mod) % mod; }
private static long modPow(long b, long e) { return valueOf(b).modPow(valueOf(e), BMOD).longValue(); }
private static long pow(long b, long e) { return round(Math.pow(b, e)); }
private static String reverse (String S) { return new StringBuilder(S).reverse().toString(); }
private static char [][] toCharArrays(String [] S) {
int N = S.length;
char [][] res = new char [N][];
for (int i : rep(N))
res[i] = S[i].toCharArray();
return res;
}
////////////////////////////////////////////////////////////////////////////////////
private final static MyScanner sc = new MyScanner();
private static class MyScanner {
private String next() {
newLine();
return line[index++];
}
private char nextChar() {
return next().charAt(0);
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
private String nextLine() {
line = null;
return readLine();
}
private String [] nextStrings() {
line = null;
return readLine().split(" ");
}
private char [] nextChars() {
return next ().toCharArray ();
}
private Integer [] nextInts() {
String [] L = nextStrings();
Integer [] res = new Integer [L.length];
for (int i : rep(L.length))
res[i] = Integer.parseInt(L[i]);
return res;
}
private Long [] nextLongs() {
String [] L = nextStrings();
Long [] res = new Long [L.length];
for (int i : rep(L.length))
res[i] = Long.parseLong(L[i]);
return res;
}
private Double [] nextDoubles() {
String [] L = nextStrings();
Double [] res = new Double [L.length];
for (int i : rep(L.length))
res[i] = Double.parseDouble(L[i]);
return res;
}
private String [] next (int N) {
String [] res = new String [N];
for (int i : rep(N))
res[i] = next();
return res;
}
private Integer [] nextInt (int N) {
Integer [] res = new Integer [N];
for (int i : rep(N))
res[i] = nextInt();
return res;
}
private Long [] nextLong (int N) {
Long [] res = new Long [N];
for (int i : rep(N))
res[i] = nextLong();
return res;
}
private Double [] nextDouble (int N) {
Double [] res = new Double [N];
for (int i : rep(N))
res[i] = nextDouble();
return res;
}
private String [][] nextStrings (int N) {
String [][] res = new String [N][];
for (int i : rep(N))
res[i] = nextStrings();
return res;
}
private Integer [][] nextInts (int N) {
Integer [][] res = new Integer [N][];
for (int i : rep(N))
res[i] = nextInts();
return res;
}
private Long [][] nextLongs (int N) {
Long [][] res = new Long [N][];
for (int i : rep(N))
res[i] = nextLongs();
return res;
}
private Double [][] nextDoubles (int N) {
Double [][] res = new Double [N][];
for (int i : rep(N))
res[i] = nextDoubles();
return res;
}
//////////////////////////////////////////////
private boolean eol() {
return index == line.length;
}
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () {
this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in)));
}
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = readLine().split(" ");
index = 0;
}
}
}
private static void print (Object o, Object... a) {
printDelim(" ", o, a);
}
private static void cprint (Object o, Object... a) {
printDelim("", o, a);
}
private static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, o, a));
}
private static void exit (Object o, Object... a) {
print(o, a);
exit();
}
private static void exit() {
pw.close();
System.out.flush();
System.err.println("------------------");
System.err.println("Time: " + ((millis() - t) / 1000.0));
System.exit(0);
}
private static void NO() {
throw new Error("NO!");
}
////////////////////////////////////////////////////////////////////////////////////
private static String build (String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
private static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = java.lang.reflect.Array.getLength(o);
for (int i : rep(L))
append(b, java.lang.reflect.Array.get(o, i), delim);
} else if (o instanceof Iterable<?>)
for (Object p : (Iterable<?>)o)
append(b, p, delim);
else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
private static void start() {
t = millis();
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out, autoflush);
private static long t;
private static long millis() {
return System.currentTimeMillis();
}
private static void statics() {
abs(0); valueOf(0); asList(new Object [0]); reverseOrder();
}
public static void main (String[] args) {
new D();
exit();
}
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | //package round178;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
int r = ni()-1, c = ni()-1;
char[] dir = ns(3);
int dr = dir[0] == 'D' ? 1 : -1;
int dc = dir[1] == 'R' ? 1 : -1;
if(gcd(n-1, m-1) == 1){
if((r == 0 || r == n-1) && (c == 0 || c == m-1)){
out.println((long)(n-1)*(m-1)+1);
}else{
out.println((long)(n-1)*(m-1) + fastsim(r, c, n, m, dr, dc));
}
}else{
if(gcd(n-1, m-1) == 2 && (r+c) % 2 == 1){
dr = -dr; dc = -dc;
out.println((long)(n-1)*(m-1)-fastsim2(r, c, n, m, dr, dc));
}else{
out.println(-1);
}
}
}
long fastsim(int r, int c, int n, int m, int dr, int dc)
{
long t = 1;
while(true){
int ntr = dr == 1 ? n-1-r : r;
int ntc = dc == 1 ? m-1-c : c;
if(ntr < ntc){
t += ntr;
r += ntr * dr;
c += ntr * dc;
dr = -dr;
}else{
t += ntc;
r += ntc * dr;
c += ntc * dc;
dc = -dc;
}
if((r == 0 || r == n-1) && (c == 0 || c == m-1)){
break;
}
}
return t;
}
int fastsim2(int r, int c, int n, int m, int dr, int dc)
{
int t = 0;
int or = r, oc = c;
while(true){
int ntr = dr == 1 ? n-1-r : r;
int ntc = dc == 1 ? m-1-c : c;
if(ntr < ntc){
t += ntr;
r += ntr * dr;
c += ntr * dc;
dr = -dr;
}else{
t += ntc;
r += ntc * dr;
c += ntc * dc;
dc = -dc;
}
if(r != or || c != oc)break;
}
return t-1;
}
public static int gcd(int a, int b) {
while (b > 0){
int c = a;
a = b;
b = c % b;
}
return a;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, int> M;
int main() {
int n, m, x, y;
char dir[5];
scanf("%d%d%d%d%s", &n, &m, &x, &y, dir);
int dx = (dir[0] == 'U' ? -1 : 1);
int dy = (dir[1] == 'L' ? -1 : 1);
int res = n + m - 2;
if (x == 1 || x == n || y == 1 || y == m) res--, M[make_pair(x, y)] = 1;
long long ans = 1;
for (int i = (0); i < (1000001); i++) {
int step = 2 * max(n, m);
step = min(dx == 1 ? n - x : x - 1, step);
step = min(dy == 1 ? m - y : y - 1, step);
ans += step;
x = x + step * dx;
y = y + step * dy;
if (x == 1 && dx == -1 || x == n && dx == 1) dx = -dx;
if (y == 1 && dy == -1 || y == m && dy == 1) dy = -dy;
if (!M[make_pair(x, y)]) res--, M[make_pair(x, y)] = 1;
if (!res) {
printf("%lld\n", ans);
return 0;
}
}
puts("-1");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
set<pair<int, int> > s;
int x, y;
int dirx, diry;
char dir[10];
int n, m;
int cnt = 0;
long long ans;
int c;
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d", &x, &y);
scanf("%s", dir);
if (dir[0] == 'U')
dirx = -1;
else
dirx = 1;
if (dir[1] == 'L')
diry = -1;
else
diry = 1;
cnt++, s.insert(make_pair(x, y));
ans = 1;
while (c <= 5 * (n + m)) {
if (x == 1 && dirx == -1) dirx = 1;
if (x == n && dirx == 1) dirx = -1;
if (y == 1 && diry == -1) diry = 1;
if (y == m && diry == 1) diry = -1;
int x0, y0;
if (dirx == -1)
x0 = x - 1;
else
x0 = n - x;
if (diry == -1)
y0 = y - 1;
else
y0 = m - y;
int q = min(x0, y0);
x += dirx * q;
y += diry * q;
ans += (long long)q;
if (!s.count(make_pair(x, y))) {
cnt++, s.insert(make_pair(x, y));
if (cnt == n + m - 2) {
printf("%I64d\n", ans);
return 0;
}
}
++c;
}
printf("-1\n");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
namespace orz {
const char *LL_SPECIFIER = "%I64d";
inline void read(int &x) { scanf("%d", &x); }
inline void read(char *x) { scanf("%s", x); }
template <typename T1, typename T2>
inline void read(T1 &x1, T2 &x2) {
read(x1);
read(x2);
}
template <typename T1, typename T2, typename T3>
inline void read(T1 &x1, T2 &x2, T3 &x3) {
read(x1);
read(x2);
read(x3);
}
template <typename T1, typename T2, typename T3, typename T4>
inline void read(T1 &x1, T2 &x2, T3 &x3, T4 &x4) {
read(x1);
read(x2);
read(x3);
read(x4);
}
inline void write(const int x) { printf("%d", x); }
inline void write(const long long x) { printf(LL_SPECIFIER, x); }
inline void write(const double x) { printf("%.15lf", x); }
template <typename T>
inline void writeln(T x) {
write(x);
putchar('\n');
}
template <typename T>
inline std::set<T> &operator<<(std::set<T> &S, const T a) {
S.insert(a);
return S;
}
} // namespace orz
using namespace orz;
std::set<std::pair<int, int> > vi;
int main() {
int n, m, cx, cy, dx, dy;
read(n, m, cx, cy);
{
char tmp[4];
read(tmp);
if (tmp[0] == 'D')
dx = 1;
else
dx = -1;
if (tmp[1] == 'R')
dy = 1;
else
dy = -1;
}
long long ans = 1;
vi.insert(std::pair<int, int>(cx, cy));
;
for (int rem = n + m - 3, cs = 0;; ++cs) {
if (cs >= 555555) {
writeln(-1);
return 0;
}
int cd = 23333333;
if (dx == 1) {
if (n - cx < cd) cd = n - cx;
} else {
if (cx - 1 < cd) cd = cx - 1;
}
if (dy == 1) {
if (m - cy < cd) cd = m - cy;
} else {
if (cy - 1 < cd) cd = cy - 1;
}
cx += dx * cd;
cy += dy * cd;
ans += (long long)cd;
if (cx == 1) dx = 1;
if (cx == n) dx = -1;
if (cy == 1) dy = 1;
if (cy == m) dy = -1;
if (!vi.count(std::pair<int, int>(cx, cy))) {
vi << std::pair<int, int>(cx, cy);
if (!(--rem)) {
writeln(ans);
return 0;
}
}
}
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
void solve();
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout << fixed;
cout.precision(12);
solve();
return 0;
}
template <typename T>
void prv(vector<T> v) {
for (int __ii = 0; __ii < ((int)v.size()); __ii++) {
if (__ii) cout << ' ';
cout << v[__ii];
}
cout << '\n';
}
template <typename T>
void prm(vector<vector<T>> v) {
for (int __ii = 0; __ii < ((int)v.size()); __ii++) {
for (int __jj = 0; __jj < v[__ii].size(); __jj++) {
if (__jj) cout << ' ';
cout << v[__ii][__jj];
}
cout << '\n';
}
}
template <typename T>
void sc(T& x) {
cin >> x;
}
template <typename Head, typename... Tail>
void sc(Head& head, Tail&... tail) {
cin >> head;
sc(tail...);
}
template <typename T>
void pr(const T& x) {
cout << x << '\n';
}
template <typename Head, typename... Tail>
void pr(const Head& head, const Tail&... tail) {
cout << head << ' ';
pr(tail...);
}
template <typename... T>
void err(const T&... cod) {
pr(cod...);
exit(0);
}
void solve() {
int n, m, y, x;
sc(n, m, y, x);
string s;
sc(s);
int dx = (s[1] == 'L' ? -1 : 1);
int dy = (s[0] == 'U' ? -1 : 1);
const int MAX_ITER = 1e6 + 10;
set<pair<int, int>> st;
long long ans = 1;
for (int i = 0; i < MAX_ITER; i++) {
st.emplace(y, x);
if (((int)st.size()) == n + m - 2) err(ans);
int u = (dy == -1 ? y - 1 : n - y);
int v = (dx == -1 ? x - 1 : m - x);
int w = min(u, v);
x += dx * w;
y += dy * w;
ans += w;
if (v == w) dx *= -1;
if (u == w) dy *= -1;
}
pr(-1);
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 200050;
const int M = 4 * N;
int n, m;
int FindMain(int x, int y) { return n - x + y; }
int FindSub(int x, int y) { return x + y - 1; }
int Get(int t, int x, int y) { return t == 0 ? FindMain(x, y) : FindSub(x, y); }
int Dist(int t, int x1, int y1, int x2, int y2) {
return max(abs(Get(t ^ 1, x1, y1) - Get(t ^ 1, x2, y2)) / 2,
abs(Get(t, x1, y1) - Get(t, x2, y2)) / 2);
}
int root_main, root_sub, tsz, ls[M], rs[M], sum[M];
void Inc(int &c, int ss, int se, int qs, int qe) {
if (qs > qe || qs > se || ss > qe) return;
if (!c) c = ++tsz;
if (qs <= ss && qe >= se) {
sum[c]++;
return;
}
int mid = ss + se >> 1;
Inc(ls[c], ss, mid, qs, qe);
Inc(rs[c], mid + 1, se, qs, qe);
}
int Get(int c, int ss, int se, int qi) {
if (ss == se) return sum[c];
int mid = ss + se >> 1;
if (qi <= mid)
return sum[c] + Get(ls[c], ss, mid, qi);
else
return sum[c] + Get(rs[c], mid + 1, se, qi);
}
int state[2][N], l[2][N], r[2][N], sz, was[2][N];
void UpdMain(int id, int s, int e) {
was[0][id]++;
if (s > e) swap(s, e);
if (!state[0][id]) {
Inc(root_main, 1, sz, s, e), l[0][id] = s, r[0][id] = e, state[0][id] = 1;
return;
}
if (l[0][id] <= s && r[0][id] >= e) return;
if (r[0][id] < e) Inc(root_main, 1, sz, r[0][id] + 1, e), r[0][id] = e;
if (l[0][id] > s) Inc(root_main, 1, sz, s, l[0][id] - 1), l[0][id] = s;
}
void UpdSub(int id, int s, int e) {
was[1][id]++;
if (s > e) swap(s, e);
if (!state[1][id]) {
Inc(root_sub, 1, sz, s, e), l[1][id] = s, r[1][id] = e, state[1][id] = 1;
return;
}
if (l[1][id] <= s && r[1][id] >= e) return;
if (r[1][id] < e) Inc(root_sub, 1, sz, r[1][id] + 1, e), r[1][id] = e;
if (l[1][id] > s) Inc(root_sub, 1, sz, s, l[1][id] - 1), l[1][id] = s;
}
vector<pair<int, int> > point[2][N];
map<int, map<int, int> > has[2];
int main() {
int x, y, i, j;
string dir;
scanf("%i %i", &n, &m);
scanf("%i %i", &x, &y);
cin >> dir;
sz = n + m - 1;
int cnt = 0, need = 0;
for (i = 1; i <= m; i++) {
if ((i + 1) % 2 == (x + y) % 2) need++;
if ((i + n) % 2 == (x + y) % 2) need++;
point[0][Get(0, 1, i)].push_back(make_pair(1, i));
point[0][Get(0, n, i)].push_back(make_pair(n, i));
point[1][Get(1, 1, i)].push_back(make_pair(1, i));
point[1][Get(1, n, i)].push_back(make_pair(n, i));
}
for (i = 2; i < n; i++) {
if ((i + 1) % 2 == (x + y) % 2) need++;
if ((i + m) % 2 == (x + y) % 2) need++;
point[0][Get(0, i, 1)].push_back(make_pair(i, 1));
point[0][Get(0, i, m)].push_back(make_pair(i, m));
point[1][Get(1, i, 1)].push_back(make_pair(i, 1));
point[1][Get(1, i, m)].push_back(make_pair(i, m));
}
for (i = 1; i <= sz; i++) sort(point[0][i].begin(), point[0][i].end());
for (i = 1; i <= sz; i++) sort(point[1][i].begin(), point[1][i].end());
int myx = x, myy = y, ms;
long long sol = 0;
if (x == 1 && y == 1) dir = "DR";
if (x == 1 && y == m) dir = "DL";
if (x == n && y == 1) dir = "UR";
if (x == n && y == m) dir = "UL";
if (dir == "DR") tie(myx, myy) = point[0][Get(0, x, y)][1], ms = 1;
if (dir == "UL") tie(myx, myy) = point[0][Get(0, x, y)][0], ms = 1;
if (dir == "UR") tie(myx, myy) = point[1][Get(1, x, y)][0], ms = 0;
if (dir == "DL") tie(myx, myy) = point[1][Get(1, x, y)][1], ms = 0;
if (make_pair(myx, myy) != make_pair(x, y) &&
(x == 1 || x == n || y == 1 || y == m))
cnt++, has[ms ^ 1][x][y]++;
if ((myx == 1 || myx == n) && (myy == 1 || myy == m)) ms ^= 1;
sol += Dist(ms ^ 1, x, y, myx, myy) + 1;
while (cnt < need) {
if (!has[ms][myx][myy] && !has[ms ^ 1][myx][myy]) cnt++;
if (cnt == need) break;
has[ms][myx][myy]++;
if (has[ms][myx][myy] > 2) return 0 * printf("-1\n");
sol += Dist(ms, point[ms][Get(ms, myx, myy)][0].first,
point[ms][Get(ms, myx, myy)][0].second,
point[ms][Get(ms, myx, myy)][1].first,
point[ms][Get(ms, myx, myy)][1].second);
if (make_pair(myx, myy) == point[ms][Get(ms, myx, myy)][0])
tie(myx, myy) = point[ms][Get(ms, myx, myy)][1];
else
tie(myx, myy) = point[ms][Get(ms, myx, myy)][0];
if ((myx == 1 || myx == n) && (myy == 1 || myy == m)) ms ^= 1;
ms ^= 1;
}
printf("%lld\n", sol);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
int n, m, x, y, dx, dy;
char dir[5];
map<pair<int, int>, bool> MP;
map<pair<pair<int, int>, int>, bool> GP;
long long ans = 1;
void fix() {
if (x == 1) dx = 1;
if (x == n) dx = -1;
if (y == 1) dy = 1;
if (y == m) dy = -1;
}
void shoot() {
int k = inf;
if (dx < 0)
k = min(k, x - 1);
else
k = min(k, n - x);
if (dy < 0)
k = min(k, y - 1);
else
k = min(k, m - y);
x += k * dx;
y += k * dy;
ans += k;
fix();
}
int main() {
scanf("%d %d", &n, &m);
scanf("%d %d %s", &x, &y, dir);
dx = dir[0] == 'U' ? -1 : 1;
dy = dir[1] == 'L' ? -1 : 1;
int need = 0;
need += (m + 1) / 2;
need += (m + (n & 1)) / 2;
need += (n + 1) / 2;
need += (n + (m & 1)) / 2;
need -= 1 + (n & 1) + (m & 1) + !(n + m & 1);
if (x + y & 1) need = 2 * (n + m - 2) - need;
for (fix();; shoot()) {
pair<int, int> cp = make_pair(x, y);
if (GP.find(make_pair(cp, dx + dy)) != GP.end())
break;
else
GP[make_pair(cp, dx + dy)] = 1;
if (MP.find(cp) == MP.end()) {
MP[cp] = 1;
if (--need == 0) {
cout << ans << endl;
return 0;
}
}
}
puts("-1");
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, bgx, bgy, fxx, fxy;
long long cnt, sum, tmp;
map<pair<int, int>, bool> vis;
char read() {
char c = getchar();
while (c != 'U' && c != 'D' && c != 'L' && c != 'R') {
c = getchar();
}
return c;
}
void go_to(int &x, int &y, int fx, int fy) {
if (fx == 1) {
if (fy == 1) {
int qwx = abs(n - x), qwy = abs(m - y);
int qw = min(qwx, qwy);
sum += qw;
x += qw;
y += qw;
} else {
int qwx = abs(n - x), qwy = abs(1 - y);
int qw = min(qwx, qwy);
sum += qw;
x += qw;
y -= qw;
}
} else {
if (fy == 1) {
int qwx = abs(1 - x), qwy = abs(m - y);
int qw = min(qwx, qwy);
sum += qw;
x -= qw;
y += qw;
} else {
int qwx = abs(1 - x), qwy = abs(1 - y);
int qw = min(qwx, qwy);
sum += qw;
x -= qw;
y -= qw;
}
}
}
void change_fx(int x, int y, int &fx, int &fy) {
if ((x == 1 && fx == -1) || (x == n && fx == 1)) {
fx = -fx;
}
if ((y == 1 && fy == -1) || (y == m && fy == 1)) {
fy = -fy;
}
}
int main() {
cin >> n >> m;
cin >> bgx >> bgy;
char c = read();
if (c == 'U') {
fxx = -1;
} else {
fxx = 1;
}
c = read();
if (c == 'L') {
fxy = -1;
} else {
fxy = 1;
}
int x = bgx, y = bgy;
if (x == 1 || x == n || y == 1 || y == m) {
cnt++;
vis[make_pair(x, y)] = 1;
change_fx(x, y, fxx, fxy);
}
while (cnt != n + m - 2) {
tmp++;
if (tmp >= 5e5) {
puts("-1");
return 0;
}
go_to(x, y, fxx, fxy);
if (!vis[make_pair(x, y)]) {
cnt++;
vis[make_pair(x, y)] = 1;
}
change_fx(x, y, fxx, fxy);
}
cout << sum + 1;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
void Get(int &T) {
char C;
bool F = 0;
for (; C = getchar(), C < '0' || C > '9';)
if (C == '-') F = 1;
for (T = C - '0'; C = getchar(), C >= '0' && C <= '9'; T = T * 10 + C - '0')
;
F && (T = -T);
}
int N, M;
int X, Y;
char Dir[5];
void Init() {
Get(N);
Get(M);
Get(X);
Get(Y);
gets(Dir + 1);
}
int A[1000005];
int B[1000005];
int C[1000005];
int E[1000005];
int Sum;
long long Ans;
void No() {
puts("-1");
exit(0);
}
void Delete() {
if (Y == 1) {
if (A[X] == 0) Sum--;
A[X]++;
if (A[X] > 5) No();
} else if (Y == M) {
if (B[X] == 0) Sum--;
B[X]++;
if (B[X] > 5) No();
} else if (X == 1) {
if (C[Y] == 0) Sum--;
C[Y]++;
if (C[Y] > 5) No();
} else if (X == N) {
if (E[Y] == 0) Sum--;
E[Y]++;
if (E[Y] > 5) No();
}
}
void Go() {
int DX, DY, D;
if (Dir[1] == 'U')
DX = X - 1;
else
DX = N - X;
if (Dir[2] == 'L')
DY = Y - 1;
else
DY = M - Y;
D = std::min(DX, DY);
Ans += D;
if (Dir[1] == 'U')
X -= D;
else
X += D;
if (Dir[2] == 'L')
Y -= D;
else
Y += D;
if (D == DX) Dir[1] ^= ('U' ^ 'D');
if (D == DY) Dir[2] ^= ('L' ^ 'R');
Delete();
if (Sum == 0) {
printf("%I64d\n", Ans);
exit(0);
}
}
void Work() {
Ans = 1;
for (int i = 1; i <= N; i++) {
if (((i ^ 1 ^ X ^ Y) & 1) == 0) {
Sum++;
}
if (((i ^ M ^ X ^ Y) & 1) == 0) {
Sum++;
}
}
for (int i = 2; i < M; i++) {
if (((i ^ 1 ^ X ^ Y) & 1) == 0) {
Sum++;
}
if (((i ^ N ^ X ^ Y) & 1) == 0) {
Sum++;
}
}
for (Delete();;) Go();
}
int main() {
Init();
Work();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y;
char ch[10];
bool vis[1000000];
int id(int x, int y) {
if (x == 1) return y;
if (y == m) return x + m - 1;
if (x == n) return m * 2 + n - y - 1;
if (y == 1) return m * 2 + n * 2 - 2 - x;
}
int stp(int x, int y, int dx, int dy) {
int ans = n + m;
if (dx > 0)
ans = min(ans, n - x);
else
ans = min(ans, x - 1);
if (dy > 0)
ans = min(ans, m - y);
else
ans = min(ans, y - 1);
return ans;
}
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d%s", &x, &y, ch);
int d1, d2;
if (ch[0] == 'D')
d1 = 1;
else
d1 = -1;
if (ch[1] == 'R')
d2 = 1;
else
d2 = -1;
int cnt = 0;
for (int i = 1; i <= n; i++)
cnt += (int)!(1 + i - x - y & 1) + (int)!(m + i - x - y & 1);
for (int i = 2; i < m; i++)
cnt += (int)!(1 + i - x - y & 1) + (int)!(n + i - x - y & 1);
long long ans = 1;
for (int c = 0;; c++) {
if (c > 500000) {
printf("-1\n");
return 0;
}
int u = id(x, y);
if (!vis[u]) {
cnt--;
vis[u] = 1;
}
if (cnt == 0) {
printf("%I64d\n", ans);
return 0;
}
int t = stp(x, y, d1, d2);
ans += t;
x += t * d1;
y += t * d2;
bool f = 0;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
if (!f && stp(x, y, i * 2 - 1, j * 2 - 1) &&
(d1 == i * 2 - 1 || d2 == j * 2 - 1)) {
d1 = i * 2 - 1;
d2 = j * 2 - 1;
f = 1;
}
if (!f) d1 = -d1, d2 = -d2;
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int sg[100050][4], n, m, Sx, Sy, Dir, st, ln[100050 * 4][4];
char b[3];
bool c[100050 * 4], d[100050 * 4][2];
long long cnt, ans;
inline int Sg(int x, int y) {
if (x == 1)
return sg[y][0];
else if (x == n)
return sg[y][1];
else if (y == 1)
return sg[x][2];
else
return sg[x][3];
}
inline void Line(int x, int y, int z, int o) {
int e = ln[x][0] ? 2 : 0;
ln[x][e] = Sg(y, z);
ln[x][e + 1] = o;
}
inline void DR(int x, int y, int z) {
int e = min(n - x, m - y), k = x + e, l = y + e;
Line(z, k, l, e);
}
inline void UR(int x, int y, int z) {
int e = min(x - 1, m - y), k = x - e, l = y + e;
Line(z, k, l, e);
}
inline void DL(int x, int y, int z) {
int e = min(n - x, y - 1), k = x + e, l = y - e;
Line(z, k, l, e);
}
inline void UL(int x, int y, int z) {
int e = min(x - 1, y - 1), k = x - e, l = y - e;
Line(z, k, l, e);
}
void Set_up() {
sg[1][0] = sg[1][2] = 1;
sg[1][1] = sg[n][2] = 2;
sg[m][0] = sg[1][3] = 3;
sg[m][1] = sg[n][3] = st = 4;
for (int i = 2; i < n; i++) sg[i][2] = ++st, sg[i][3] = ++st;
for (int i = 2; i < m; i++) sg[i][0] = ++st, sg[i][1] = ++st;
DR(1, 1, 1);
DL(1, m, 3);
UR(n, 1, 2);
UL(n, m, 4);
for (int i = 2; i < n; i++)
DR(i, 1, sg[i][2]), UR(i, 1, sg[i][2]), DL(i, m, sg[i][3]),
UL(i, m, sg[i][3]);
for (int i = 2; i < m; i++)
DR(1, i, sg[i][0]), DL(1, i, sg[i][0]), UR(n, i, sg[i][1]),
UL(n, i, sg[i][1]);
}
long long DFS(int x, int y) {
if (!c[x]) c[x] = true, cnt--;
if (!cnt) return 0;
for (int i = 0; i < 3 && ln[x][i]; i += 2)
if (ln[x][i] != y && !d[x][i / 2]) {
d[x][i / 2] = true;
return DFS(ln[x][i], x == st ? ln[x][2] : x) + ln[x][i + 1];
}
if (!ln[x][2] && !d[x][0]) {
d[x][0] = true;
return DFS(ln[x][0], x) + ln[x][1];
}
puts("-1");
exit(0);
}
void Solve() {
int k = 0;
st++;
bool flag = (Sx + Sy) & 1;
if (Sx == n && Sy == m) b[0] = 'U', b[1] = 'L';
if (Sx == 1 && Sy == m) b[0] = 'D', b[1] = 'L';
if (Sx == n && Sy == 1) b[0] = 'U', b[1] = 'R';
if (Sx == 1 && Sy == 1) b[0] = 'D', b[1] = 'R';
if (b[0] == 'D' && b[1] == 'R')
DR(Sx, Sy, st), UL(Sx, Sy, st);
else if (b[0] == 'D')
DL(Sx, Sy, st), UR(Sx, Sy, st);
else if (b[1] == 'R')
UR(Sx, Sy, st), DL(Sx, Sy, st);
else
UL(Sx, Sy, st), DR(Sx, Sy, st);
for (int i = 1; i <= m; i++)
cnt += flag == ((1 + i) & 1), cnt += flag == ((n + i) & 1);
for (int i = 2; i < n; i++)
cnt += flag == ((1 + i) & 1), cnt += flag == ((m + i) & 1);
cnt++;
if (Sx == 1 || Sy == 1 || Sx == n || Sy == m) cnt--, c[Sg(Sx, Sy)] = true;
ans = DFS(st, ln[st][2]);
printf("%I64d\n", ans + 1);
return;
}
int main() {
cin >> n >> m >> Sx >> Sy >> b;
Set_up();
Solve();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int mod = 1e9 + 7;
int n, m, a, b;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + c - '0';
c = getchar();
}
return x * f;
}
int dx, dy;
inline bool cor(int x, int y) {
if (x == 1 && y == 1) return 1;
if (x == 1 && y == m) return 1;
if (x == n && y == 1) return 1;
if (x == n && y == m) return 1;
return 0;
}
long long ans, sum;
map<long long, bool> vis, pd;
int main() {
n = read(), m = read();
a = read(), b = read();
string s;
cin >> s;
ans = 1ll * n * m - n - m + 2ll;
dx = (s[0] == 'D') ? 1 : -1;
dy = (s[1] == 'R') ? 1 : -1;
if ((n & 1) && (m & 1)) {
if (!((a + b) & 1) || ((n == m) && n > 3)) return puts("-1"), 0;
sum = 1;
int xx = a, yy = b;
while (1) {
int aa, bb;
if (dx == 1 && dy == 1) {
aa = n, bb = n + b - a;
if (bb > m) bb = m, aa = m + a - b;
} else if (dx == 1 && dy == -1) {
aa = n, bb = a + b - n;
if (bb < 1) bb = 1, aa = a + b - 1;
} else if (dx == -1 && dy == 1) {
aa = 1, bb = a + b - 1;
if (bb > m) bb = m, aa = a + b - m;
} else {
aa = 1, bb = 1 + b - a;
if (bb < 1) bb = 1, aa = 1 + a - b;
}
if (a ^ aa || b ^ bb) pd[1ll * a * maxn + b] = 1;
long long val = 1ll * aa * maxn + bb;
if (pd[val])
return printf("%lld\n", (2ll * sum >= 1ll * n * m - 1) ? sum : -1), 0;
pd[val] = 1;
sum += abs(a - aa);
a = aa, b = bb;
if (a == 1 || a == n) dx = -dx;
if (b == 1 || b == m) dy = -dy;
}
return 0;
}
while (!cor(a, b)) {
int aa, bb;
if (dx == 1 && dy == 1) {
aa = n, bb = n + b - a;
if (bb > m) bb = m, aa = m + a - b;
ans += (aa - a);
} else if (dx == 1 && dy == -1) {
aa = n, bb = a + b - n;
if (bb < 1) bb = 1, aa = a + b - 1;
ans += (aa - a);
} else if (dx == -1 && dy == 1) {
aa = 1, bb = a + b - 1;
if (bb > m) bb = m, aa = a + b - m;
ans += (a - aa);
} else {
aa = 1, bb = 1 + b - a;
if (bb < 1) bb = 1, aa = 1 + a - b;
ans += (a - aa);
}
a = aa, b = bb;
long long val = 1ll * a * maxn + b;
if (vis[val]) return puts("-1"), 0;
vis[val] = 1;
if (a == 1 || a == n) dx = -dx;
if (b == 1 || b == m) dy = -dy;
}
a = b = dx = dy = 1;
while (1) {
int aa, bb;
if (dx == 1 && dy == 1) {
aa = n, bb = n + b - a;
if (bb > m) bb = m, aa = m + a - b;
sum += (aa - a);
} else if (dx == 1 && dy == -1) {
aa = n, bb = a + b - n;
if (bb < 1) bb = 1, aa = a + b - 1;
sum += (aa - a);
} else if (dx == -1 && dy == 1) {
aa = 1, bb = a + b - 1;
if (bb > m) bb = m, aa = a + b - m;
sum += (a - aa);
} else {
aa = 1, bb = 1 + b - a;
if (bb < 1) bb = 1, aa = 1 + a - b;
sum += (a - aa);
}
a = aa, b = bb;
long long val = 1ll * a * maxn + b;
if (pd[val]) return puts("-1"), 0;
pd[val] = 1;
if (a == 1 || a == n) dx = -dx;
if (b == 1 || b == m) dy = -dy;
if (sum == 1ll * (n - 1) * (m - 1)) break;
}
printf("%lld\n", ans);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int N, M, X, Y, dx, dy;
map<pair<int, int>, int> F;
void doit() {
char s[3];
long long ans = 1;
scanf("%d%d%d%d%s", &N, &M, &X, &Y, s), dx = s[0] == 'U' ? -1 : 1,
dy = s[1] == 'L' ? -1 : 1;
for (int i = 1; i <= (N + M) * 2; i++) {
F[make_pair(X, Y)] = 1;
if (F.size() == N + M - 2) {
cout << ans << endl;
return;
}
int u = dx < 0 ? X - 1 : N - X, v = dy < 0 ? Y - 1 : M - Y, w = min(u, v);
X += dx * w, Y += dy * w, ans += w;
if (u == w) dx *= -1;
if (v == w) dy *= -1;
}
puts("-1");
}
int main() {
doit();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MAXA = 100010;
int N, M;
int ox, oy, dx, dy;
int Go() {
int t = min((dx == 1) ? (N - ox) : (ox - 1), (dy == 1) ? (M - oy) : (oy - 1));
ox += dx * t;
oy += dy * t;
return t;
}
int Vu[MAXA], Vd[MAXA], Vl[MAXA], Vr[MAXA], Task;
void TaskInitialize() {
int i, c = (ox + oy) & 1;
Task = 0;
for (i = 1; i <= M; i++) {
Vu[i] = 0;
if ((1 + i) % 2 == c) Task++;
Vd[i] = 0;
if ((N + i) % 2 == c) Task++;
}
for (i = 1; i <= N; i++) {
Vl[i] = 0;
if ((1 + i) % 2 == c) Task++;
Vr[i] = 0;
if ((M + i) % 2 == c) Task++;
}
}
void Process(int &x) {
if (x == 3) {
printf("-1\n");
exit(0);
}
if (x == 0) Task--;
x++;
}
void IAmHere() {
if (ox == 1) Process(Vu[oy]);
if (ox == N) Process(Vd[oy]);
if (oy == 1) Process(Vl[ox]);
if (oy == M) Process(Vr[ox]);
}
void Reflect() {
if (ox == 1) dx = 1;
if (ox == N) dx = -1;
if (oy == 1) dy = 1;
if (oy == M) dy = -1;
}
int main() {
scanf("%d%d%d%d", &N, &M, &ox, &oy);
char ch[3];
scanf("%s", ch);
dx = (ch[0] == 'U') ? -1 : 1;
dy = (ch[1] == 'L') ? -1 : 1;
TaskInitialize();
long long ans = 1;
IAmHere();
while (Task) {
ans += Go();
IAmHere();
Reflect();
}
cout << ans << endl;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5111;
const long long base = 10000000;
const int mod = 1000000007;
template <typename T>
T ABS(T n) {
return n > 0 ? n : -n;
}
long long convert(long long x, long long y, long long dx, long long dy) {
return (x << 22) | (y << 2) | (dx << 1) | (dy);
}
set<long long> h1, h2;
long long n, m;
long long code(long long x, long long y, long long dx, long long dy) {
long long tx, ty;
long long a, b;
if (dx) {
tx = n - x;
if (dy) {
ty = m - y;
if (tx > ty)
a = x + ty, b = m, dy ^= 1;
else if (tx < ty)
a = n, b = y + tx, dx ^= 1;
else
a = n, b = m, dx ^= 1, dy ^= 1;
} else {
ty = y - 1;
if (tx > ty)
a = x + ty, b = 1, dy ^= 1;
else if (tx < ty)
a = n, b = y - tx, dx ^= 1;
else
a = n, b = 1, dx ^= 1, dy ^= 1;
}
} else {
tx = x - 1;
if (dy) {
ty = m - y;
if (tx > ty)
a = x - ty, b = m, dy ^= 1;
else if (tx < ty)
a = 1, b = y + tx, dx ^= 1;
else
a = 1, b = m, dx ^= 1, dy ^= 1;
} else {
ty = y - 1;
if (tx > ty)
a = x - ty, b = 1, dy ^= 1;
else if (tx < ty)
a = 1, b = y - tx, dx ^= 1;
else
a = 1, b = 1, dx ^= 1, dy ^ 1;
}
}
long long res = 0;
res = (a << 22) | (b << 2) | (dx << 1) | dy;
return res;
}
long long mask = (1 << 20) - 1;
long long code(long long x, long long y) { return (x << 20) | y; }
void decode(long long n, long long &x, long long &y, long long &dx,
long long &dy) {
x = (n >> 22) & mask;
y = (n >> 2) & mask;
dx = (n >> 1) & 1;
dy = n & 1;
}
int main() {
ios::sync_with_stdio(false);
long long x, y, dx, dy;
string s;
cin >> n >> m;
decode(code(3, 1, 0, 1), x, y, dx, dy);
cin >> x >> y;
cin >> s;
dx = s[0] == 'D';
dy = s[1] == 'R';
if (x == 1 || x == n || y == 1 || y == m)
h1.insert(code(x, y)), h2.insert(convert(x, y, dx, dy));
long long t;
int cnt = 0;
long long ans = 0;
long long tx, ty;
while (true) {
tx = x, ty = y;
t = code(x, y, dx, dy);
if (h2.count(t)) {
break;
}
decode(t, x, y, dx, dy);
h2.insert(t);
h1.insert(code(x, y));
ans += ABS(x - tx);
if (h1.size() == m + n - 2) break;
}
if (h1.size() == n + m - 2)
cout << ans + 1 << endl;
else
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, bool> mp;
char s[5];
int main() {
int n, m, x, y;
scanf("%d%d%d%d", &n, &m, &x, &y);
scanf("%s", s + 1);
int dx, dy;
if (s[1] == 'U')
dx = -1;
else
dx = 1;
if (s[2] == 'L')
dy = -1;
else
dy = 1;
int cnt = 0, time = 4e5 + 5;
long long ans = 0;
while (time--) {
pair<int, int> now = pair<int, int>(x, y);
if (mp.count(now) == 0) {
mp[now] = 1;
cnt++;
}
if (cnt == n + m - 2) {
printf("%lld", ans + 1);
return 0;
}
int xl, yl, l;
int ex, ey;
if (dx == -1)
xl = x - 1;
else if (dx != -1)
xl = n - x;
if (dy == -1)
yl = y - 1;
else if (dy != -1)
yl = m - y;
if (xl < yl) {
ex = -dx;
ey = dy;
l = xl;
} else if (xl > yl) {
ey = -dy;
ex = dx;
l = yl;
} else {
ex = -dx;
ey = -dy;
l = yl;
}
x += dx * l;
y += dy * l;
ans += 1ll * l;
dx = ex;
dy = ey;
}
printf("-1\n");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
int n, m, x, y;
string kier;
cin >> n >> m >> x >> y >> kier;
int dx, dy;
if (kier[0] == 'U')
dx = -1;
else
dx = 1;
if (kier[1] == 'L')
dy = -1;
else
dy = 1;
set<pair<int, int> > S;
S.insert(make_pair(x, y));
int il_kr = n + m - 2;
long long odp = 1;
bool ost = false;
for (int i = 0; i < 2 * (n + m); ++i) {
if (dx == -1 && dy == -1) {
int l = y - 1, g = x - 1;
x -= min(l, g);
y -= min(l, g);
odp += min(l, g);
if (x == 1 && y == 1) {
dx = 1;
dy = 1;
} else {
if (x == 1)
dx = 1;
else
dy = 1;
}
} else {
if (dx == -1 && dy == 1) {
int p = m - y, g = x - 1;
x -= min(p, g);
y += min(p, g);
odp += min(p, g);
if (x == 1 && y == m) {
dx = 1;
dy = -1;
} else {
if (x == 1)
dx = 1;
else
dy = -1;
}
} else {
if (dx == 1 && dy == 1) {
int p = m - y, d = n - x;
x += min(p, d);
y += min(p, d);
odp += min(p, d);
if (x == n && y == m) {
dx = -1;
dy = -1;
} else {
if (x == n)
dx = -1;
else
dy = -1;
}
} else {
if (dx == 1 && dy == -1) {
int l = y - 1, d = n - x;
x += min(l, d);
y -= min(l, d);
odp += min(l, d);
if (x == n && y == 1) {
dx = -1;
dy = 1;
} else {
if (x == n)
dx = -1;
else
dy = 1;
}
}
}
}
}
S.insert(make_pair(x, y));
if (S.size() == il_kr) {
cout << odp;
return 0;
}
}
cout << "-1";
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.StringTokenizer;
public class D {
private static final int UL = 0;
private static final int UR = 1;
private static final int DL = 2;
private static final int DR = 3;
private static class Result {
public boolean inCorner;
public long cellsPassed;
public int steps;
public int x;
public int y;
public int dir;
public Result(boolean inCorner, long cellsPassed, int steps, int x, int y, int dir) {
this.inCorner = inCorner;
this.cellsPassed = cellsPassed;
this.steps = steps;
this.x = x;
this.y = y;
this.dir = dir;
}
}
private Result go(int n, int m, int x0, int y0, int dir0, int stepsNeeded) {
long res = 0;
int x = x0;
int y = y0;
int dir = dir0;
int steps = 0;
do {
steps++;
if (dir == UR) {
int dx = x - 1;
int dy = m - y;
int d = Math.min(dx, dy);
x -= d;
y += d;
res += d;
if (dy < dx) {
dir = UL;
} else if (dx < dy) {
dir = DR;
}
} else if (dir == UL) {
int dx = x - 1;
int dy = y - 1;
int d = Math.min(dx, dy);
x -= d;
y -= d;
res += d;
if (dx < dy) {
dir = DL;
} else if (dy < dx) {
dir = UR;
}
} else if (dir == DL) {
int dx = n - x;
int dy = y - 1;
int d = Math.min(dx, dy);
x += d;
y -= d;
res += d;
if (dx < dy) {
dir = UL;
} else if (dy < dx) {
dir = DR;
}
} else if (dir == DR) {
int dx = n - x;
int dy = m - y;
int d = Math.min(dx, dy);
x += d;
y += d;
res += d;
if (dx < dy) {
dir = UR;
} else if (dy < dx) {
dir = DL;
}
}
} while (steps < stepsNeeded
&& !isCorner(x, y, n, m)
&& (x != x0 || y != y0 || dir != dir0));
if (isCorner(x, y, n, m)) {
return new Result(true, res, steps, x, y, dir);
} else {
return new Result(false, res, steps, x, y, dir);
}
}
private boolean isCorner(int x, int y, int n, int m) {
return (x == 1 && y == 1 || x == 1 && y == m ||
x == n && y == 1 || x == n && y == m);
}
private int reverseDirection(int dir) {
if (dir == UL) {
return DR;
} else if (dir == UR) {
return DL;
} else if (dir == DL) {
return UR;
} else if (dir == DR) {
return UL;
} else {
throw new RuntimeException();
}
}
private void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int x = nextInt();
int y = nextInt();
String s = nextToken();
int dir = getDirection(s);
dir = updateDirction(n, m, x, y, dir);
int stepsNeeded = (n + n + m + m - 4) / 2 - 1;
Result r1 = go(n, m, x, y, dir, stepsNeeded);
if (r1.inCorner) {
r1.cellsPassed++;
if (isCorner(x, y, n, m)) {
if (r1.steps == stepsNeeded) {
println(r1.cellsPassed);
} else {
println("-1");
}
} else {
Result r2 = go(n, m, r1.x, r1.y, reverseDirection(r1.dir), stepsNeeded);
if (r2.steps == stepsNeeded) {
println(r1.cellsPassed + r2.cellsPassed);
} else {
println("-1");
}
}
} else {
if (r1.steps == stepsNeeded) {
println(r1.cellsPassed + 1);
} else {
println("-1");
}
}
}
private int getDirection(String s) {
int dir = 0;
if ("UL".equals(s)) {
dir = UL;
} else if ("UR".equals(s)) {
dir = UR;
} else if ("DL".equals(s)) {
dir = DL;
} else {
dir = DR;
}
return dir;
}
private int updateDirction(int n, int m, int x, int y, int dir) {
if (x == 1 && y == 1) {
dir = DR;
} else if (x == 1 && y == m) {
dir = DL;
} else if (x == n && y == 1) {
dir = UR;
} else if (x == n && y == m) {
dir = UL;
} else if (x == 1) {
if (dir == UR) {
dir = DR;
} else if (dir == UL) {
dir = DL;
}
} else if (x == n) {
if (dir == DR) {
dir = UR;
} else if (dir == DL) {
dir = UL;
}
} else if (y == 1) {
if (dir == UL) {
dir = UR;
} else if (dir == DL) {
dir = DR;
}
} else if (y == m) {
if (dir == UR) {
dir = UL;
} else if (dir == DR) {
dir = DL;
}
}
return dir;
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
private double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private void print(Object o) {
writer.print(o);
}
private void println(Object o) {
writer.println(o);
}
private void printf(String format, Object... o) {
writer.printf(format, o);
}
public static void main(String[] args) {
long time = System.currentTimeMillis();
Locale.setDefault(Locale.US);
new D().run();
System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
private void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(13);
}
}
} | JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;
import java.math.*;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;
public class Main{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
AC solver = new AC();
solver.solve(in, out);
out.close();
}
}
class AC {
class Node extends Object{
int x,y,dx,dy;
Node() {}
Node(int x,int y,int dx,int dy)
{
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
}
@Override public boolean equals (Object cmp) {
if(cmp instanceof Node) {
Node tmp = (Node) cmp;
return tmp.x == x && tmp.y == y && tmp.dx==dx && tmp.dy == dy ;
}
return false;
}
@Override public int hashCode() {
return x*dx * 100000+ y*dy;
}
}
class pair extends Object{
int x,y;
pair() {}
pair(int x,int y)
{
this.x = x;
this.y = y;
}
@Override public boolean equals (Object cmp) {
if(cmp instanceof pair) {
pair tmp = (pair) cmp;
return tmp.x == x && tmp.y == y;
}
return false;
}
@Override public int hashCode () {
return x*100000+y;
}
}
int n , m;
boolean judge(int x,int y) {
return 1<=x && x <= n && 1 <= y && y <= m;
}
Node go(int x,int y,int dx,int dy) {
int delta;
if(dx < 0) {
if(dy < 0) {
delta = Math.min(x-1, y-1);
} else {
delta = Math.min(m-y, x-1);
}
} else {
if(dy < 0) {
delta = Math.min(n-x, y-1);
} else {
delta = Math.min(n-x,m-y);
}
}
x += dx * delta;
y += dy * delta;
if(x+dx<1 || x+dx>n) dx *= -1;
if(y+dy<1 || y+dy>m) dy *= -1;
return new Node(x,y,dx,dy);
}
public void solve(InputReader in, PrintWriter out) {
int x0 , y0;
String cmd;
HashMap<Node,Integer> mp = new HashMap<Node,Integer>();
HashMap<pair,Integer> M = new HashMap<pair,Integer>();
n = in.nextInt();
m = in.nextInt();
x0 = in.nextInt(); y0 = in.nextInt();
cmd = in.next();
int tot = n + m - 2;
int dx , dy;
if(cmd.charAt(0)=='D') {
dx = 1;
} else dx = -1;
if(cmd.charAt(1)=='R') {
dy = 1;
} else dy = -1;
long ans = 1;
pair A = new pair(1,2);
pair B = new pair(1,2);
if(x0==1 || x0==n || y0==1 || y0==m){
M.put(new pair(x0, y0) , 1 );
tot --;
}
while(true) {
Node tmp = go(x0,y0,dx,dy);
ans += Math.abs( tmp.x - x0);
x0 = tmp.x ; y0 = tmp.y ;
dx = tmp.dx ; dy = tmp.dy;
pair t = new pair(x0,y0);
Integer flag = M.get(t);
if(flag == null) {
M.put(t, 1);
if(--tot == 0) break;
}
if(mp.get(tmp)!=null){
ans = -1;
break;
} else {
mp.put(tmp, 1);
}
}
out.println(ans);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
if (!hasNext())
throw new RuntimeException();
return tokenizer.nextToken();
}
boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
return false;
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y, tot, a, b, f[4][10000000], dx, dy;
char ch[5];
long long ans;
int solve(int x, int y) {
if (x == 1)
a = 0, b = y;
else if (x == n)
a = 1, b = y;
else if (y == 1)
a = 2, b = x;
else if (y == m)
a = 3, b = x;
if (!f[a][b]) f[a][b] = 1, ++tot;
if (x == 1) dx = 1;
if (x == n) dx = -1;
if (y == 1) dy = 1;
if (y == m) dy = -1;
}
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d", &x, &y);
scanf("%s", &ch);
ch[0] == 'D' ? dx = 1 : dx = -1;
ch[1] == 'R' ? dy = 1 : dy = -1;
int t;
ans = 1;
for (int i = 1; i <= 2 * (n + m - 2); i++) {
solve(x, y);
if (tot >= n + m - 2) {
printf("%I64d", ans);
return 0;
}
t = min(dy > 0 ? m - y : y - 1, dx > 0 ? n - x : x - 1);
ans += t;
x += dx * t;
y += dy * t;
}
puts("-1");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int top[100010], bottom[100010], le[100010], ri[100010];
int dx[4] = {1, 1, -1, -1};
int dy[4] = {1, -1, -1, 1};
int correctit(int y, int x, int n, int m, int d) {
switch (d) {
case 0:
if (y == n - 1) return (x == m - 1) ? 2 : 1;
if (x == m - 1) return 3;
break;
case 1:
if (!y) return (x == m - 1) ? 3 : 0;
if (x == m - 1) return 2;
break;
case 2:
if (!y) return !x ? 0 : 3;
if (!x) return 1;
break;
case 3:
if (y == n - 1) return !x ? 1 : 2;
if (!x) return 0;
break;
}
return d;
}
int main() {
int n, i, m, y, x, j, d;
char buf[16];
scanf("%d %d", &n, &m);
scanf("%d %d %s", &y, &x, buf);
y--;
x--;
string dir(buf);
if (dir == "UL")
d = 2;
else if (dir == "UR")
d = 1;
else if (dir == "DL")
d = 3;
else
d = 0;
int mustbe = (m + 1) / 2 + (n - (m & 1)) / 2 + (m - ((n + m) % 2 == 0)) / 2 +
(n - 2) / 2;
long long total = 0;
int xo = x;
int yo = y;
while (true) {
d = correctit(y, x, n, m, d);
if (!y) {
if (!top[x]) {
mustbe--;
if (!mustbe) break;
}
if (top[x] & (1 << d)) break;
top[x] |= 1 << d;
} else if (y == n - 1) {
if (!bottom[x]) {
mustbe--;
if (!mustbe) break;
}
if (bottom[x] & (1 << d)) break;
bottom[x] |= 1 << d;
} else if (!x) {
if (!le[y]) {
mustbe--;
if (!mustbe) break;
}
if (le[y] & (1 << d)) break;
le[y] |= 1 << d;
} else {
if (!ri[y]) {
mustbe--;
if (!mustbe) break;
}
if (ri[y] & (1 << d)) break;
ri[y] |= 1 << d;
}
int k = 1000000;
if (-x / dx[d] > 0) k = -x / dx[d];
if ((m - 1 - x) / dx[d] > 0) k = min(k, (m - 1 - x) / dx[d]);
if (-y / dy[d] > 0) k = min(k, -y / dy[d]);
if ((n - 1 - y) / dy[d] > 0) k = min(k, (n - 1 - y) / dy[d]);
x += k * dx[d];
y += k * dy[d];
total += k;
}
total += (xo != x || yo != y);
printf("%I64d", !mustbe ? total : -1LL);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
const int INF = 0x3f3f3f3f;
map<int, int> mp[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int x, y, n, m, dx, dy;
string s;
cin >> n >> m >> x >> y;
cin >> s;
if (s[0] == 'U')
dx = -1;
else
dx = 1;
if (s[1] == 'L')
dy = -1;
else
dy = 1;
int tot = n + m - 2;
int cnt = 0;
long long ans = 1;
if (x == 1 || x == n || y == 1 || y == m) {
tot--;
mp[x][y] = 1;
}
while (true) {
cnt++;
if (cnt >= 5e5) return 0 * puts("-1");
int dis = INF;
if (dx == 1)
dis = min(dis, n - x);
else
dis = min(dis, x - 1);
if (dy == 1)
dis = min(dis, m - y);
else
dis = min(dis, y - 1);
ans += dis;
x += dx * dis;
y += dy * dis;
if (x == 1)
dx = 1;
else if (x == n)
dx = -1;
if (y == 1)
dy = 1;
else if (y == m)
dy = -1;
if (!mp[x][y]) {
tot--;
mp[x][y] = 1;
}
if (!tot) {
cout << ans << endl;
return 0;
}
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, total, dx = 1, dy = 1;
set<pair<int, int> > vis;
void save(int x, int y) {
if (!vis.count(pair<int, int>(x, y))) {
vis.insert(pair<int, int>(x, y));
total++;
}
if (x == 1) dx = 1;
if (x == n) dx = -1;
if (y == 1) dy = 1;
if (y == m) dy = -1;
}
int main() {
int t, i, x, y;
string s;
long long ans = 1;
cin >> n >> m;
cin >> x >> y >> s;
if (s[0] == 'U') dx = -1;
if (s[1] == 'L') dy = -1;
save(x, y);
for (i = 0; i < 2 * (n + m); i++) {
t = min(dx == 1 ? n - x : x - 1, dy == 1 ? m - y : y - 1);
ans += t;
x += t * dx;
y += t * dy;
save(x, y);
if (total == m + n - 2) {
cout << ans << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int MX = 100005;
int n, m, x, y, fx, fy, k;
int arr[MX], aba[MX], izq[MX], der[MX];
long long res;
string s;
void no() {
cout << -1 << '\n';
exit(0);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m >> x >> y >> s;
if (s[0] == 'U')
fx = -1;
else
fx = 1;
if (s[1] == 'L')
fy = -1;
else
fy = 1;
if (m % 2 == 0)
k += n;
else
k += 2 * ((n + 1 - (x + y) % 2) / 2);
if (n % 2 == 0)
k += m;
else
k += 2 * ((m + 1 - (x + y) % 2) / 2);
while (k) {
if (x == 1) {
if (!arr[y]) k--;
arr[y]++;
if (arr[y] == 3) no();
fx = 1;
}
if (x == n) {
if (!aba[y]) k--;
aba[y]++;
if (aba[y] == 3) no();
fx = -1;
}
if (y == 1) {
if (!izq[x]) k--;
izq[x]++;
if (izq[x] == 3) no();
fy = 1;
}
if (y == m) {
if (!der[x]) k--;
der[x]++;
if (der[x] == 3) no();
fy = -1;
}
if (!k) break;
int d;
if (fx == -1)
d = x - 1;
else
d = n - x;
if (fy == -1)
d = min(d, y - 1);
else
d = min(d, m - y);
res += d;
x += fx * d;
y += fy * d;
}
cout << 1 + res << '\n';
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import static java.lang.Math.*;
public class D {
private final static boolean autoflush = false;
private static final int INF = (int) 1e9;
private int N, M, Z, K = 0;
private int [] A, B, C, D, W, T;
private long res;
public D () {
N = sc.nextInt();
M = sc.nextInt();
int X = sc.nextInt();
int Y = sc.nextInt();
char [] dir = sc.nextChars();
int dx = dir[0] == 'D' ? 1 : -1;
int dy = dir[1] == 'R' ? 1 : -1;
W = new int [] { X, Y };
T = new int [] { dx, dy };
A = new int [N]; B = new int [N];
C = new int [M]; D = new int [M];
Z = 2 * (N/2 + M/2); int P = (X+Y) % 2;
if (N % 2 == 1 && P == 0) ++Z;
if (N % 2 == 1 && P == (1 + M) % 2) ++Z;
if (M % 2 == 1 && P == 0) ++Z;
if (M % 2 == 1 && P == (1 + N) % 2) ++Z;
res = 1;
for (;;) {
mark();
res += next();
}
}
private int next() {
int X = W[0], Y = W[1];
int dx = T[0], dy = T[1];
if (X == 1) dx = 1;
if (X == N) dx = -1;
if (Y == 1) dy = 1;
if (Y == M) dy = -1;
int t = INF;
if (dx == 1) t = min(t, N - X);
if (dx == -1) t = min(t, X - 1);
if (dy == 1) t = min(t, M - Y);
if (dy == -1) t = min(t, Y - 1);
X += t * dx; Y += t * dy;
W[0] = X; W[1] = Y;
T[0] = dx; T[1] = dy;
return t;
}
private void mark() {
int X = W[0], Y = W[1];
if (Y == 1) inc(A, X);
if (Y == M) inc(B, X);
if (X == 1) inc(C, Y);
if (X == N) inc(D, Y);
}
private void inc(int [] A, int X) {
--X; if (A[X] == 0) ++K; ++A[X];
if (A[X] == 3)
exit(-1);
if (K == Z)
exit(res);
}
////////////////////////////////////////////////////////////////////////////////////
private static int [] rep(int N) { return rep(0, N); }
private static int [] rep(int S, int T) { int [] res = new int [max(T-S, 0)]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static <T extends Comparable<T>> T max(T x, T y) { return x.compareTo(y) > 0 ? x : y; }
////////////////////////////////////////////////////////////////////////////////////
private final static MyScanner sc = new MyScanner();
private static class MyScanner {
private String next() {
newLine();
return line[index++];
}
private int nextInt() {
return Integer.parseInt(next());
}
private char [] nextChars() {
return next ().toCharArray ();
}
//////////////////////////////////////////////
private boolean eol() {
return index == line.length;
}
private String readLine() {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () {
this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in)));
}
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine() {
if (line == null || eol()) {
line = readLine().split(" ");
index = 0;
}
}
}
private static void print (Object o, Object... a) {
printDelim(" ", o, a);
}
private static void printDelim (String delim, Object o, Object... a) {
pw.println(build(delim, o, a));
}
private static void exit (Object o, Object... a) {
print(o, a);
exit();
}
private static void exit() {
pw.close();
System.out.flush();
System.err.println("------------------");
System.err.println("Time: " + ((millis() - t) / 1000.0));
System.exit(0);
}
////////////////////////////////////////////////////////////////////////////////////
private static String build (String delim, Object o, Object... a) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : a)
append(b, p, delim);
return b.toString().trim();
}
private static void append(StringBuilder b, Object o, String delim) {
if (o.getClass().isArray()) {
int L = java.lang.reflect.Array.getLength(o);
for (int i : rep(L))
append(b, java.lang.reflect.Array.get(o, i), delim);
} else if (o instanceof Iterable<?>)
for (Object p : (Iterable<?>)o)
append(b, p, delim);
else
b.append(delim).append(o);
}
////////////////////////////////////////////////////////////////////////////////////
private static void start() {
t = millis();
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out, autoflush);
private static long t;
private static long millis() {
return System.currentTimeMillis();
}
public static void main (String[] args) {
new D();
exit();
}
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int r, c, sr, sc;
map<pair<int, int>, int> M;
string dir;
int x[] = {0, 0, 1, -1};
int y[] = {1, -1, 0, 0};
void visit() {
long long res = 1;
int tp = 2 * (r + c - 1) - 2, evenp = ceil(r / 2.0) + ceil(c / 2.0) - 1;
int cp = tp / 2;
int cr = sr, cc = sc, nr = sr, nc = sc;
tp = 0;
bool rep = false;
while (1) {
cr = nr;
cc = nc;
if (M[make_pair(cr, cc)] == 0) ++tp;
if (!rep) M[make_pair(cr, cc)]++;
if (M[make_pair(cr, cc)] >= 3) break;
if (tp == cp) break;
rep = false;
if (dir == "DR") {
nr = cr + c - cc;
nc = c;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += c - cc;
dir = "DL";
if (nr == r && nc == c) dir = "UL";
if (nr == cr && nc == cc) rep = true;
continue;
}
nr = r;
nc = cc + r - cr;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += r - cr;
dir = "UR";
if (nr == r && nc == c) dir = "UL";
if (nr == cr && nc == cc) rep = true;
continue;
}
}
if (dir == "UR") {
nr = cr - c + cc;
nc = c;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += c - cc;
dir = "UL";
if (nr == 1 && nc == c) dir = "DL";
if (nr == cr && nc == cc) rep = true;
continue;
}
nr = 1;
nc = cc + cr - 1;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += cr - 1;
dir = "DR";
if (nr == 1 && nc == c) dir = "DL";
if (nr == cr && nc == cc) rep = true;
continue;
}
}
if (dir == "DL") {
nr = cr + cc - 1;
nc = 1;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += cc - 1;
dir = "DR";
if (nr == r && nc == 1) dir = "UR";
if (nr == cr && nc == cc) rep = true;
continue;
}
nr = r;
nc = cc - r + cr;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += r - cr;
dir = "UL";
if (nr == r && nc == 1) dir = "UR";
if (nr == cr && nc == cc) rep = true;
continue;
}
}
if (dir == "UL") {
nr = cr - cc + 1;
nc = 1;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += cc - 1;
dir = "UR";
if (nr == 1 && nc == 1) dir = "DR";
if (nr == cr && nc == cc) rep = true;
continue;
}
nr = 1;
nc = cc - cr + 1;
if (nr > 0 && nr <= r && nc > 0 && nc <= c) {
res += cr - 1;
dir = "DL";
if (nr == 1 && nc == 1) dir = "DR";
if (nr == cr && nc == cc) rep = true;
continue;
}
}
}
if (tp == cp)
cout << res << endl;
else
cout << -1 << endl;
}
int main() {
cin >> r >> c;
cin >> sr >> sc >> dir;
visit();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
long long a, b, x, y, s, dx, dy, e[4][100005], n, m, zz = 0, qsb, wl;
void as(int c, int y) {
if (x == 1) {
n = 0;
m = y;
}
if (x == a) {
n = 1;
m = y;
}
if (y == 1) {
n = 2;
m = x;
}
if (y == b) {
n = 3;
m = x;
}
if (!e[n][m]) {
e[n][m] = 1;
zz++;
}
if (x == 1) {
dy = 1;
}
if (x == a) {
dy = -1;
}
if (y == 1) {
dx = 1;
}
if (y == b) {
dx = -1;
}
}
int main() {
ios::sync_with_stdio(false);
while (cin >> a >> b) {
s = 1;
string z;
zz = 0;
cin >> x >> y >> z;
wl = 0;
memset(e, 0, sizeof(e));
z[0] == 'D' ? dy = 1 : dy = -1;
z[1] == 'R' ? dx = 1 : dx = -1;
for (int i = 0; i < (a + b - 2) * 2; i++) {
as(x, y);
if (zz >= (a + b - 2)) {
wl++;
break;
}
qsb = min(dy > 0 ? a - x : x - 1, dx > 0 ? b - y : y - 1);
s += qsb;
x += dy * qsb;
y += dx * qsb;
}
if (wl) {
cout << s << endl;
} else {
cout << -1 << endl;
}
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, dx, dy, x, y;
char S[10];
map<int, int> A[100010];
int main() {
scanf("%d%d%d%d", &n, &m, &x, &y), cin >> S;
dx = (S[0] == 'U') ? -1 : 1;
dy = (S[1] == 'L') ? -1 : 1;
int tot = n + m - 2, T = 0;
if (x == 1 || x == n || y == 1 || y == m) A[x][y] = 1, (--(tot));
long long Ans = 1;
while (1) {
(++(T));
if (T >= 2333333) return puts("-1"), 0;
int Dis = 2147483647;
Dis = (dx == 1) ? min(Dis, n - x) : min(Dis, x - 1);
Dis = (dy == 1) ? min(Dis, m - y) : min(Dis, y - 1);
x += dx * Dis, y += dy * Dis, Ans += Dis;
if (x == 1)
dx = 1;
else if (x == n)
dx = -1;
if (y == 1)
dy = 1;
else if (y == m)
dy = -1;
if (!A[x][y]) (--(tot)), A[x][y] = 1;
if (!tot) return cout << Ans, 0;
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int d[][2] = {{1, -1}, {1, 1}, {-1, -1}, {-1, 1}};
const char* ds[] = {"DL", "DR", "UL", "UR"};
int gdi(const char* s) {
int i = -1;
while (++i < 4) {
if (!strcmp(s, ds[i])) return i;
}
}
bool sv[4] = {false};
int fdi(const int dr, const int dc) {
int i = -1;
while (++i < 4 && !(dr == d[i][0] && dc == d[i][1]))
;
return i;
}
void pr1(map<pair<int, int>, bool>& mp) {
map<pair<int, int>, bool>::iterator it = mp.begin();
while (it != mp.end()) {
printf("%d, %d\n", it->first.first, it->first.second);
++it;
}
printf("------------\n");
}
int main() {
int n, m, xs, ys, di;
char drs[3];
scanf("%d%d%d%d%s", &n, &m, &xs, &ys, drs);
const int n1 = n - 1, m1 = m - 1;
--xs, --ys;
const int xy = ((xs + ys) & 1);
di = gdi(drs);
int dr = d[di][0], dc = d[di][1], cr = xs, cc = ys;
if (n == m && n > 2) {
if ((((!xs && !ys) || (xs == n1 && ys == n1)) && dr * dc > 0) ||
(((!xs && ys == m1) || (xs == n1 && !ys)) && dr * dc < 0)) {
printf("-1\n");
return 0;
}
}
map<pair<int, int>, bool> mp;
int i = -1;
while (++i < n) {
pair<int, int> p1(i, 0), p2(i, m1);
if (((p1.first + p1.second) & 1) == xy) mp[p1] = false;
if (((p2.first + p2.second) & 1) == xy) mp[p2] = false;
}
i = -1;
while (++i < m) {
pair<int, int> p1(0, i), p2(n1, i);
if (((p1.first + p1.second) & 1) == xy) mp[p1] = false;
if (((p2.first + p2.second) & 1) == xy) mp[p2] = false;
}
int nm = mp.size();
long long pn = 1;
pair<int, int> pc(xs, ys);
map<pair<int, int>, bool>::iterator it = mp.find(pc);
if (it != mp.end()) {
it->second = true;
--nm;
}
while (nm) {
int d1, d2;
if (dr < 0) {
d1 = cr;
if (dc > 0) {
d2 = m1 - cc;
} else {
d2 = cc;
}
} else {
d1 = n1 - cr;
if (dc > 0) {
d2 = m1 - cc;
} else {
d2 = cc;
}
}
if (d1 > d2) {
d1 = d2;
cr += d1 * dr;
cc += d1 * dc;
dc = -dc;
} else if (d1 < d2) {
cr += d1 * dr;
cc += d1 * dc;
dr = -dr;
} else {
cr += d1 * dr;
cc += d2 * dc;
dr = -dr;
dc = -dc;
}
pn += d1;
pc.first = cr, pc.second = cc;
it = mp.find(pc);
if (it != mp.end() && !it->second) {
--nm;
it->second = true;
}
if (nm && cr == xs && cc == ys) {
int j = fdi(dr, dc);
if (sv[j]) {
printf("-1\n");
return 0;
} else {
sv[j] = true;
}
}
}
printf("%I64d\n", pn);
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int n, m;
set<pair<pair<int, int>, int> > S;
set<pair<int, int> > SS;
string c;
int main() {
int i, j;
int x, y;
cin >> n >> m >> x >> y >> c;
int dir;
if (c == "DR")
dir = 2;
else if (c == "UR")
dir = 3;
else if (c == "DL")
dir = 4;
else
dir = 1;
int tot = 1;
int sum = (m + 1) / 2 + (m + (n & 1)) / 2 + (n + 1) / 2 + (n + (m & 1)) / 2 -
1 - (m & 1) - (n & 1) - ((n & 1) == (m & 1));
long long ans = 1;
S.insert(make_pair(make_pair(x, y), dir));
SS.insert(make_pair(x, y));
bool flag = 0;
while (1) {
if (dir == 1) {
int cnt = min(x - 1, y - 1);
ans += cnt;
y -= cnt;
x -= cnt;
if (x == 1 && y == 1)
dir = 2;
else if (x == 1)
dir = 4;
else if (y == 1)
dir = 3;
} else if (dir == 2) {
int cnt = min(m - y, n - x);
ans += cnt;
x += cnt;
y += cnt;
if (x == n && y == m)
dir = 1;
else if (x == n)
dir = 3;
else if (y == m)
dir = 4;
} else if (dir == 3) {
int cnt = min(x - 1, m - y);
ans += cnt;
x -= cnt;
y += cnt;
if (x == 1 && y == m)
dir = 4;
else if (x == 1)
dir = 2;
else if (y == m)
dir = 1;
} else {
int cnt = min(n - x, y - 1);
ans += cnt;
x += cnt;
y -= cnt;
if (x == n && y == 1)
dir = 3;
else if (x == n)
dir = 1;
else if (y == 1)
dir = 2;
}
pair<int, int> pp = make_pair(x, y);
if (!SS.count(pp)) {
SS.insert(pp);
tot++;
}
if (tot == sum) break;
if (S.count(make_pair(pp, dir))) {
flag = 1;
break;
}
S.insert(make_pair(pp, dir));
}
if (flag)
puts("-1");
else
cout << ans << endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y;
char ch[4];
int dx, dy;
map<pair<int, int>, bool> Map;
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d", &x, &y);
scanf("%s", ch);
if (ch[0] == 'D')
dx = 1;
else
dx = -1;
if (ch[1] == 'R')
dy = 1;
else
dy = -1;
long long ans = 1;
for (int i = 1; i <= 2 * (n + m); i++) {
Map[make_pair(x, y)] = 1;
if (Map.size() == n + m - 2) {
cout << ans << endl;
return 0;
}
int delx, dely;
if (dx == -1)
delx = x - 1;
else
delx = n - x;
if (dy == -1)
dely = y - 1;
else
dely = m - y;
int mw = min(delx, dely);
x += mw * dx;
y += mw * dy;
if (delx == mw) dx = -dx;
if (dely == mw) dy = -dy;
ans += mw;
}
printf("-1\n");
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y;
map<pair<int, int>, int> p;
void solve() {
long long ans = 1;
cin >> n >> m >> x >> y;
string s;
cin >> s;
int dx = s[0] == 'U' ? -1 : 1;
int dy = s[1] == 'L' ? -1 : 1;
for (int i = 1; i <= (n + m) * 2; ++i) {
p[make_pair(x, y)] = 1;
if (p.size() == n + m - 2) {
cout << ans << endl;
exit(0);
}
int u = dx < 0 ? x - 1 : n - x;
int v = dy < 0 ? y - 1 : m - y;
int w = min(u, v);
x += dx * w;
y += dy * w;
ans += w;
if (u == w) {
dx *= -1;
}
if (v == w) {
dy *= -1;
}
}
puts("-1");
}
int main(int argc, char const *argv[]) {
solve();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int INF = 1075555555;
map<int, int> A[100010];
int n, m, now, dx, dy, x, y;
char ch[10];
void work(void) {
scanf("%d%d", &n, &m);
scanf("%d%d", &x, &y);
scanf("%s", ch + 1);
if (ch[1] == 'U')
dx = -1;
else
dx = 1;
if (ch[2] == 'L')
dy = -1;
else
dy = 1;
int rem = n + m - 2;
if (x == 1 || x == n || y == 1 || y == m) {
A[x][y] = 1;
rem--;
}
int timer = 0;
long long ans = 1;
while (true) {
timer++;
if (timer >= 500000) {
cout << -1 << endl;
return;
}
int dis = INF;
if (dx == 1)
dis = min(dis, n - x);
else
dis = min(dis, x - 1);
if (dy == 1)
dis = min(dis, m - y);
else
dis = min(dis, y - 1);
x += dx * dis, y += dy * dis;
ans += dis;
if (x == 1)
dx = 1;
else if (x == n)
dx = -1;
if (y == 1)
dy = 1;
else if (y == m)
dy = -1;
if (A[x][y] == 0) {
rem--;
A[x][y] = 1;
}
if (!rem) {
cout << ans << endl;
return;
}
}
}
int main() {
work();
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class PanterRobot {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
static int N,M;
static HashSet<State> visited;
static class State{
int x,y,dir;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
State other = (State) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public State(int xx, int yy, int dirr){
x = xx;
y = yy;
dir = dirr;
}
public String toString(){
return String.format("(%d, %d, %d)", x, y, dir);
}
}
static int getCode(String ins){
if (ins.equals("UL"))
return 3;
if (ins.equals("UR"))
return 2;
if (ins.equals("DL"))
return 1;
if (ins.equals("DR"))
return 0;
return (0 / 0);
}
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc = new Scanner();
N = sc.nextInt();
M = sc.nextInt();
int amount = N + M - 2;
long ans = 0;
boolean finished = false;
int a = sc.nextInt();
int b = sc.nextInt();
int c = getCode(sc.next());
State current = new State(a, b, c);
HashSet<State> visited = new HashSet<State>();
if (N == M && M == 3){
if (a == 1 && b == 1){
System.out.println("-1");
return;
}
if (a == 3 && b == 1){
System.out.println("-1");
return;
}
if (a == 1 && b == 3){
System.out.println("-1");
return;
}
if (a == 3 && b == 3){
System.out.println("-1");
return;
}
}
if(N == M && M > 3){
System.out.println("-1");
return;
}
int trans = 0;
boolean termino = false;
while(true){
visited.add(current);
if (visited.size() == amount) {
finished = true;
break;
}
int nx = 0,ny = 0,ndir = 0;
if (current.dir == 0){
int dy = M - current.y;
int dx = N - current.x;
if ( dy < dx){
nx = current.x + dy;
ny = M;
ndir = getCode("DL");
}
else if (dy > dx){
nx = N;
ny = current.y + dx;
ndir = getCode("UR");
}
else{
//iguales
nx = N;
ny = M;
ndir = getCode("UL");
}
ans += Math.min(dx, dy);
}
else if (current.dir == 1){
int dy = current.y - 1;
int dx = N - current.x;
if ( dy < dx){
nx = current.x + dy;
ny = 1;
ndir = getCode("DR");
}
else if (dy > dx){
nx = N;
ny = current.y - dx;
ndir = getCode("UL");
}
else{
//iguales
nx = N;
ny = 1;
ndir = getCode("UR");
}
ans += Math.min(dx, dy);
}
else if (current.dir == 2){
int dy = M - current.y;
int dx = current.x - 1;
if ( dy < dx){
nx = current.x - dy;
ny = M;
ndir = getCode("UL");
}
else if (dy > dx){
nx = 1;
ny = current.y + dx;
ndir = getCode("DR");
}
else{
//iguales
nx = 1;
ny = M;
ndir = getCode("DL");
}
ans += Math.min(dx, dy);
}
else if (current.dir == 3){
int dy = current.y - 1;
int dx = current.x - 1;
if ( dy < dx){
nx = current.x - dy;
ny = 1;
ndir = getCode("UR");
}
else if (dy > dx){
nx = 1;
ny = current.y - dx;
ndir = getCode("DL");
}
else{
//iguales
nx = 1;
ny = 1;
ndir = getCode("DR");
}
ans += Math.min(dx, dy);
}
else
System.out.println(0 / 0);
current = new State(nx, ny, ndir);
//System.out.println(ans);
//System.out.println(current);
trans++;
if (trans > (2 * (amount + 0L)+ 1000)){
termino = true;
System.out.println("-1");
break;
}
}
if (!termino){
if (finished)
System.out.println(ans + 1);
else
System.out.println("-1");
}
}
}
| JAVA |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | __author__ = 'sergio'
def sg(p):
if p == 0:
return -1
else:
return 1
def minim(w,h):
if w < h:
return (w,0)
else:
return (h,1)
def find_path(x, y, down, right):
global size_n
global size_m
if down == 1:
h = size_n - x
else:
h = x - 1
if right == 1:
w = size_m - y
else:
w = y - 1
minimum = minim(w,h)
p = minimum[0]
ansX = x + p * sg(down)
ansY = y + p * sg(right)
if ansX == 1:
down = 1
if ansY == 1:
right = 1
if ansX == size_n:
down = 0
if ansY == size_m:
right = 0
return (ansX, ansY, down, right)
def total_black_bound_cells(n, m):
return n + m - 2
def moves_count(x, y, xn, yn):
return abs(x - xn)
def get_direction(direction):
if direction == 'UL':
return 0, 0
elif direction == 'UR':
return 0, 1
elif direction == 'DL':
return 1, 0
elif direction == 'DR':
return 1, 1
def turn_inside(n, m, xs, ys, down, right):
if xs == 1:
down = 1
if ys == 1:
right = 1
if xs == n:
down = 0
if ys == m:
right = 0
return (down, right)
size_n = 0
size_m = 0
if __name__ == '__main__':
n, m = [int(x) for x in raw_input().strip().split(' ')]
xs, ys, direction = raw_input().strip().split(' ')
xs = int(xs)
ys = int(ys)
size_n = n
size_m = m
down, right = get_direction(direction)
down, right = turn_inside(n, m, xs, ys, down, right)
# print n, m, xs, ys, down, right
# make visited_points with bound cells
visited_points = {}
total_to_check = total_black_bound_cells(n, m) # calculate
# print 'total_to_check', total_to_check
visited_points[(xs, ys)] = 1
total_to_check -= 1
x = xs
y = ys
dye = 1
while (total_to_check > 0):
xn, yn, down, right = find_path(x, y, down, right)
dye += moves_count(x, y, xn, yn)
# print 'moves_count', moves_count(x, y, xn, yn)
x = xn
y = yn
if (x, y) not in visited_points:
visited_points[(x, y)] = 1
total_to_check -= 1
elif visited_points[(x,y)] == 1:
visited_points[(x,y)] += 1
else:
print -1
exit()
print dye | PYTHON |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const long long MAX_N = 100005;
long long n, m;
long long H(long long x) {
if (x >= 0)
return 1;
else
return 0;
}
bool legal(long long nx, long long ny, long long dx, long long dy) {
if (nx == 1 && ny == 1 && dx == -1 && dy == -1) return false;
if (nx == 1 && ny == m && dx == -1 && dy == 1) return false;
if (nx == n && ny == 1 && dx == 1 && dy == -1) return false;
if (nx == n && ny == m && dx == 1 && dy == 1) return false;
return true;
}
map<long long, long long> vis[2][2][MAX_N];
map<long long, long long> used[MAX_N];
signed main() {
long long nx, ny, dx, dy;
cin >> n >> m;
cin >> nx >> ny;
string s;
cin >> s;
if (s[0] == 'U')
dx = -1;
else
dx = 1;
if (s[1] == 'L')
dy = -1;
else
dy = 1;
long long ans = 1;
long long cnt = 0;
while (true) {
if (!used[nx][ny]) cnt++;
used[nx][ny] = true;
if (cnt == n + m - 2) {
cout << ans << endl;
return 0;
}
if (nx == 1) dx = 1;
if (ny == 1) dy = 1;
if (nx == n) dx = -1;
if (ny == m) dy = -1;
if (vis[H(dx)][H(dy)][nx][ny]) {
cout << -1 << endl;
return 0;
}
vis[H(dx)][H(dy)][nx][ny] = true;
if (dx == 1 && dy == 1) {
long long d1 = n - nx;
long long d2 = m - ny;
long long d = min(d1, d2);
nx += d;
ny += d;
ans += d;
}
if (dx == 1 && dy == -1) {
long long d1 = n - nx;
long long d2 = ny - 1;
long long d = min(d1, d2);
nx += d;
ny -= d;
ans += d;
}
if (dx == -1 && dy == 1) {
long long d1 = nx - 1;
long long d2 = m - ny;
long long d = min(d1, d2);
nx -= d;
ny += d;
ans += d;
}
if (dx == -1 && dy == -1) {
long long d1 = nx - 1;
long long d2 = ny - 1;
long long d = min(d1, d2);
nx -= d;
ny -= d;
ans += d;
}
}
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
struct Point {
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
Point &operator+=(const Point &o) {
x += o.x;
y += o.y;
return *this;
}
};
Point operator+(Point a, const Point &b) { return a += b; }
Point operator*(Point a, int k) { return Point(a.x * k, a.y * k); }
bool operator<(const Point &a, const Point &b) {
if (a.x == b.x) {
return a.y < b.y;
}
return a.x < b.x;
}
Point DELTA[4] = {Point(1, 1), Point(-1, 1), Point(-1, -1), Point(1, -1)};
const int LIMIT = 1000000;
int n, m, d;
Point p;
char buffer[3];
std::set<Point> set;
int main() {
scanf("%d%d%d%d%s", &n, &m, &p.x, &p.y, buffer);
for (int i = 1; i <= n; ++i) {
int d = i == 1 || i == n ? 1 : m - 1;
for (int j = 1; j <= m; j += d) {
if ((i + j & 1) == (p.x + p.y & 1)) {
set.insert(Point(i, j));
}
}
}
d = 0;
if (buffer[0] == 'U') {
d ^= 1;
}
if (buffer[1] == 'L') {
d ^= 3;
}
set.erase(p);
long long answer = 1;
for (int _ = 0; _ < LIMIT && !set.empty(); ++_) {
int low = 0;
int high = std::max(n, m);
while (low < high) {
int middle = low + high + 1 >> 1;
Point q = p + DELTA[d] * middle;
if (1 <= q.x && q.x <= n && 1 <= q.y && q.y <= m) {
low = middle;
} else {
high = middle - 1;
}
}
if (low == 0) {
if (p.x + DELTA[d].x > n || p.x + DELTA[d].x < 1) {
d ^= 1;
}
if (p.y + DELTA[d].y > m || p.y + DELTA[d].y < 1) {
d ^= 3;
}
} else {
answer += low;
p += DELTA[d] * low;
set.erase(p);
}
}
std::cout << (set.empty() ? answer : -1) << std::endl;
return 0;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, int> M;
map<pair<int, int>, int> MM;
int n, m;
inline int jud(int x, int y) {
if (x < 1 || x > n) return 0;
if (y < 1 || y > m) return 0;
return 1;
}
int main() {
int i, j, k;
long long ans = 0;
int x, y;
cin >> n >> m;
cin >> x >> y;
int dx, dy;
char s[10];
cin >> s;
if (s[0] == 'D')
dx = 1;
else
dx = -1;
if (s[1] == 'R')
dy = 1;
else
dy = -1;
int ca = 2 * (n + m) - 4;
ca /= 2;
do {
int ct = 0;
if (!jud(x + dx, y)) dx *= -1;
if (!jud(x, y + dy)) dy *= -1;
if (M.count(make_pair(x * dx, y * dy))) {
puts("-1");
return 0;
}
if (MM.count(make_pair(x, y)) == 0) {
MM[make_pair(x, y)] = 1;
ca--;
}
if (ca == 0) break;
M[make_pair(x * dx, y * dy)] = 1;
int l = 1, r = 100000, mid;
while (l < r) {
mid = (l + r + 1) / 2;
if (!jud(x + dx * mid, y + dy * mid))
r = mid - 1;
else
l = mid;
}
x += dx * l, y += dy * l;
ans += l;
} while (ca);
cout << ans + 1 << endl;
}
| CPP |
294_D. Shaass and Painter Robot | Shaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of n·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.
Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.
The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.
Let's consider an examples depicted below.
<image>
If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.
Input
The first line of the input contains two integers n and m, (2 ≤ n, m ≤ 105). The second line contains two integers xs and ys (1 ≤ xs ≤ n, 1 ≤ ys ≤ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).
Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.
It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).
Output
Print the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
3 4
1 1 DR
Output
7
Input
3 4
3 3 DR
Output
11
Input
3 3
1 1 DR
Output
-1
Input
3 3
1 2 DL
Output
4 | 2 | 10 | #include <bits/stdc++.h>
using namespace std;
const int inf = ~0U >> 1;
const long long INF = ~0ULL >> 1;
template <class T>
inline void read(T &n) {
char c;
for (c = getchar(); !(c >= '0' && c <= '9'); c = getchar())
;
n = c - '0';
for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - '0';
}
int Pow(int base, int n, int mo) {
if (n == 0) return 1;
if (n == 1) return base % mo;
int tmp = Pow(base, n >> 1, mo);
tmp = (long long)tmp * tmp % mo;
if (n & 1) tmp = (long long)tmp * base % mo;
return tmp;
}
int n, m, sx, sy;
char Dir[3];
long long s, ans = 1;
int dir, curx, cury;
set<int> s1, s2, s3, s4;
void add(int x, int y) {
if (x == 1) s1.insert(y);
if (x == n) s2.insert(y);
if (y == 1) s3.insert(x);
if (y == m) s4.insert(x);
if (s1.size() + s2.size() + s3.size() + s4.size() == s) {
printf("%lld\n", ans);
exit(0);
}
}
int main() {
scanf("%d%d", &n, &m);
scanf("%d%d%s", &sx, &sy, Dir);
if (Dir[0] == 'U' && Dir[1] == 'L')
dir = 0;
else if (Dir[0] == 'U')
dir = 1;
else if (Dir[1] == 'L')
dir = 2;
else
dir = 3;
for (int i = (1); i <= (m); ++i) {
if ((1 + i) % 2 == (sx + sy) % 2) s++;
if ((n + i) % 2 == (sx + sy) % 2) s++;
}
for (int i = (1); i <= (n); ++i) {
if ((1 + i) % 2 == (sx + sy) % 2) s++;
if ((m + i) % 2 == (sx + sy) % 2) s++;
}
curx = sx, cury = sy;
add(curx, cury);
for (int _ = (1); _ <= (1000000); ++_) {
if (dir == 0) {
int step = min(curx - 1, cury - 1);
curx -= step;
cury -= step;
ans += step;
add(curx, cury);
if (curx == 1 && cury == 1)
dir = 3;
else if (cury == 1)
dir = 1;
else if (curx == 1)
dir = 2;
} else if (dir == 1) {
int step = min(curx - 1, m - cury);
curx -= step;
cury += step;
ans += step;
add(curx, cury);
if (curx == 1 && cury == m)
dir = 2;
else if (cury == m)
dir = 0;
else if (curx == 1)
dir = 3;
} else if (dir == 2) {
int step = min(n - curx, cury - 1);
curx += step;
cury -= step;
ans += step;
add(curx, cury);
if (curx == n && cury == 1)
dir = 1;
else if (curx == n)
dir = 0;
else if (cury == 1)
dir = 3;
} else if (dir == 3) {
int step = min(n - curx, m - cury);
curx += step;
cury += step;
ans += step;
add(curx, cury);
if (curx == n && cury == m)
dir = 0;
else if (curx == n)
dir = 1;
else if (cury == m)
dir = 2;
}
}
puts("-1");
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | from functools import reduce
from operator import *
from math import *
from sys import *
from string import *
from collections import *
setrecursionlimit(10**7)
dX= [-1, 1, 0, 0,-1, 1,-1, 1]
dY= [ 0, 0,-1, 1, 1,-1,-1, 1]
RI=lambda: list(map(int,input().split()))
RS=lambda: input().rstrip().split()
#################################################
s=RS()[0]
h,m=[],[]
i=s.find("heavy")
while i!=-1:
h.append(i)
i=s.find("heavy",i+1)
j=s.find("metal")
while j!=-1:
m.append(j)
j=s.find("metal",j+1)
i,j=0,0
ans=0
while i<len(h):
while j<len(m) and m[j]<h[i]:
j+=1
if j<len(m):
ans+=(len(m)-j)
i+=1
print(ans)
| PYTHON3 |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | def r(): return map(int, raw_input().split())
def main():
s = raw_input()
s = s.replace("heavy", "|").replace("metal", "^")
ls = len(s)
total = 0
cur = 0
for i in xrange(ls):
si = s[ls-i-1]
if si == "^":
cur += 1
elif si == "|":
total += cur
print total
main() | PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import time,math,bisect,sys
from sys import stdin,stdout
from collections import deque
from fractions import Fraction
from collections import Counter
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IO(): # to take string input
return stdin.readline()
def IP(): # to take tuple as input
return map(int,stdin.readline().split())
def L(): # to take list as input
return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
if a==0:
return b
elif b==0:
return a
if a>b:
return gcd(a%b,b)
else:
return gcd(a,b%a)
def readTree(): # to read tree
v=int(input())
adj=[set() for i in range(v+1)]
for i in range(v-1):
u1,u2=In()
adj[u1].add(u2)
adj[u2].add(u1)
return adj,v
def bfs(adj,v): # a schema of bfs
visited=[False]*(v+1)
q=deque()
while q:
pass
def sieve():
li=[True]*1000001
li[0],li[1]=False,False
for i in range(2,len(li),1):
if li[i]==True:
for j in range(i*i,len(li),i):
li[j]=False
prime=[]
for i in range(1000001):
if li[i]==True:
prime.append(i)
return prime
def setBit(n):
count=0
while n!=0:
n=n&(n-1)
count+=1
return count
#####################################################################################
def solve():
s=input()
h=0
c=0
n=len(s)
for i in range(n-4):
if s[i:i+5]=='heavy':
h+=1
elif s[i:i+5]=='metal':
c=c+h
print(c)
solve() | PYTHON3 |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
const long long inf = 0x3f3f3f3f3f3f3f3f;
const long long maxn = 2e6 + 7;
using namespace std;
string h = "heavy", m = "metal";
string s;
long long pre[maxn], pree[maxn];
void solve() {
int flag = 1, pl = 0, cnt = 0;
while (~pl) {
if (pl == 0) pl = -1;
pl = s.find(h, pl + 1);
if (~pl) pre[pl++]++;
}
pl = 0;
while (~pl) {
if (pl == 0) pl = -1;
pl = s.find(m, pl + 1);
if (~pl) pree[pl++]++;
}
for (int i = 1; i <= s.size(); i++)
pree[i] += pree[i - 1], pre[i] += pre[i - 1];
long long sum = 0, n = s.size() - 1;
for (int i = 0; i < s.size(); i++) {
if (pre[i] - pre[i - 1] == 1) {
sum += (pree[n] - pree[i]);
}
}
cout << sum << "\n";
}
int main() {
cin >> s;
solve();
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 |
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Igor
*/
public class B318 {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
long res = 0;
long heavy = 0;
if (s.length() > 4) {
for (int i = 4 ; i < s.length() ; i++) {
if (s.charAt(i - 4) == 'h') {
if (s.charAt(i - 3) == 'e') {
if (s.charAt(i - 2) == 'a') {
if (s.charAt(i - 1) == 'v') {
if (s.charAt(i) == 'y') {
heavy++;
}
}
}
}
} else if (s.charAt(i - 4) == 'm') {
if (s.charAt(i - 3) == 'e') {
if (s.charAt(i - 2) == 't') {
if (s.charAt(i - 1) == 'a') {
if (s.charAt(i) == 'l') {
res += heavy;
}
}
}
}
}
}
}
System.out.println(res);
}
}
| JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
string cad, he = "heavy", me = "metal";
cin >> cad;
vector<int> ph, pm;
int ps = 0;
while ((ps = cad.find(he, ps)) != string::npos) ph.push_back(ps), ps++;
ps = 0;
while ((ps = cad.find(me, ps)) != string::npos) pm.push_back(ps), ps++;
long long cnt = 0;
for (int i = (0), _n = (ph.size()); i < _n; i++) {
int pos = upper_bound(pm.begin(), pm.end(), ph[i]) - pm.begin();
int num = pm.size() - pos;
cnt += num;
}
cout << cnt << endl;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
;
cin.tie(NULL);
;
string s, s1, s2, s3;
cin >> s;
s1 = "heavy";
s2 = "metal";
int n, i;
long long an = 0, h1 = 0, h2 = 0;
n = s.length();
for (i = 0; i < n - 4; i++) {
s3 = s.substr(i, 5);
if (s3 == s1) h1++;
if (s3 == s2) {
an += h1;
}
}
cout << an;
cout << "\n";
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import sys
import re
if __name__ == "__main__":
line = sys.stdin.readline().strip().replace("metal", '1').replace("heavy", '0')
line = re.sub(r'[a-z]+', '', line)
line = ''.join(reversed(line))
amount = 0
count = 0
for i in range(0, len(line)):
if line[i] == '1':
count += 1
else:
amount += count
print amount
| PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String s = myScanner.next();
s = s.replaceAll("heavy", "1");
s = s.replaceAll("metal", "2");
s = s.replaceAll("[a-z]", "");
int metal[] = new int[s.length()], tmp = 0;
for (int i = s.length() - 1; i >= 0; i--)
if (s.charAt(i) == '2') {
metal[i] = tmp + 1;
tmp++;
} else
metal[i] = tmp;
long res = 0;
for (int i = 0; i < metal.length; i++)
if (s.charAt(i) == '1') {
res += metal[i];
}
System.out.println(res);
}
}
| JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
long long l, i, h = 0, m = 0;
cin >> s;
l = s.size();
for (i = 0; i < l - 4; i++) {
if (s[i] == 'h' && s[i + 1] == 'e' && s[i + 2] == 'a' && s[i + 3] == 'v' &&
s[i + 4] == 'y')
++h;
if (s[i] == 'm' && s[i + 1] == 'e' && s[i + 2] == 't' && s[i + 3] == 'a' &&
s[i + 4] == 'l')
m += h;
}
cout << m << endl;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 |
import java.util.Scanner;
/**
*
* @author takhi
*/
public class string_318B {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String n=sc.next();
n=n.toLowerCase();
long count=0;
long ans=0;
for(int i=0;i+4<n.length();i++){
if(n.substring(i,i+5).equals("heavy")){
count++;
}else if(n.substring(i,i+5).equals("metal")){
ans=ans+count;
}
}
System.out.println(ans);
}
} | JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
string s;
long long nr[11000000], k;
int main() {
cin >> s;
for (int j = s.size(); j >= 0; j--) {
nr[j] = nr[j + 1];
if (s[j] == 'm' && s[j + 1] == 'e' && s[j + 2] == 't' && s[j + 3] == 'a' &&
s[j + 4] == 'l')
nr[j]++;
if (s[j] == 'h' && s[j + 1] == 'e' && s[j + 2] == 'a' && s[j + 3] == 'v' &&
s[j + 4] == 'y')
k = k + nr[j];
}
cout << k << "\n";
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.StringTokenizer;
/* ------------ Theorems and Lemmas ------------ */
// Fermat's Little Theorem
// (1) ((a ** p) - a) % p = 0; if 'p' is prime
// (2) Further, if 'a % p != 0', then ((a ** (p - 1)) - 1) % p = 0
/* -------------- End of theorems -------------- */
public class Solution {
// Digit DP
private static int digit;
private static int times;
private static StringBuilder number;
private static int[][][] digitDP;
// End
public static void main(String[] args) {
FastReader reader = new FastReader();
String s = reader.nextLine();
reader.close();
int[] a = new int[s.length()];
Arrays.fill(a, 2);
for (int i = 0; i <= a.length - 5; ++i) {
a[i] = s.substring(i, i + 5).equals("heavy") ? 0 : a[i];
a[i] = s.substring(i, i + 5).equals("metal") ? 1 : a[i];
}
long ans = 0;
long cnt = 0;
for (int i = 0; i <= a.length - 5; ++i) {
if (a[i] == 0)
++cnt;
else if (a[i] == 1)
ans += cnt;
}
System.out.println(ans);
}
// Digit DP
public static int ddp(int n) {
number = new StringBuilder(String.valueOf(n));
digitDP = new int[12][12][2];
for (int[][] a : digitDP)
for (int[] b : a)
Arrays.fill(b, -1);
return call(0, 0, 0);
}
// Digit DP
public static int call(int pos, int cnt, int f) {
if (cnt > times)
return 0;
if (pos == number.length())
return cnt == times ? 1 : 0;
if (digitDP[pos][cnt][f] != -1)
return digitDP[pos][cnt][f];
int res = 0;
int lmt = f == 0 ? number.charAt(pos) - '0' : 9;
for (int dgt = 0; dgt <= lmt; ++dgt)
if ((dgt == digit ? 1 + cnt : cnt) <= times)
res += call(1 + pos, dgt == digit ? 1 + cnt : cnt, f == 0 && dgt < lmt ? 1 : f);
digitDP[pos][cnt][f] = res;
return res;
}
// Binary Exponentiation
public static long binpow(long a, long n, long mod) {
// Iterative approach
a %= mod;
long result = 1l;
while (n > 0l) {
if ((n & 1l) != 0l)
result = result * a % mod;
a = a * a % mod;
n >>= 1l;
}
return result;
// Recursive approach
/*
* if (n == 0l) return 1l; long res = binpow(a, n / 2, mod); if ((n & 1l) != 0l)
* return ((res % mod) * (res % mod) * (a % mod)) % mod; else return ((res %
* mod) * (res % mod)) % mod;
*/
}
// GCD
public static long gcd(long a, long b) {
while (b > 0) {
a %= b;
long t = a;
a = b;
b = t;
}
return a;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine().trim());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
StringBuilder str = new StringBuilder("");
try {
str.append(br.readLine().trim());
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
int[] readArray(int size) {
int[] ar = new int[size];
for (int i = 0; i < size; ++i)
ar[i] = nextInt();
return ar;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | def lower_bound(arr, l, r, key):
res = -1
while l <= r:
mid = (l + r)/2
if arr[mid] <= key:
l = mid + 1
else:
res = mid
r = mid - 1
return res
line = raw_input()
heavy = []
metal = []
i = 0
while i < len(line):
if line[i:i+5] == "heavy":
heavy.append(i)
elif line[i:i+5] == "metal":
metal.append(i)
i += 1
count = 0
for i_heavy in heavy:
i_metal = lower_bound(metal, 0, len(metal)-1, i_heavy)
if i_metal == -1:
break
count += len(metal) - i_metal
print count | PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class B {
public static void main(String [] args){
Scanner in = new Scanner(System.in);
StringBuffer s = new StringBuffer(in.next());
int i = 0 ;
Queue<Integer> h = new LinkedList<>();
Queue<Integer> m = new LinkedList<>();
int l = s.length();
while(i<l){
try{
if(s.charAt(i)=='h' && s.charAt(i+1)=='e' && s.charAt(i+2)=='a' && s.charAt(i+3)=='v' && s.charAt(i+4)=='y' ){
h.add(i);
i+=4;
}
}
catch (Exception e) {
}
try{
if(s.charAt(i)=='m' && s.charAt(i+1)=='e' && s.charAt(i+2)=='t' && s.charAt(i+3)=='a' && s.charAt(i+4)=='l' ){
m.add(i);
i+=4;
}
}
catch (Exception e) {
}
i++;
}
long ans = 0;
for( int j : h){
while(!m.isEmpty() && m.peek() < j){
m.poll();
}
ans += m.size();
}
System.out.println(ans);
}
}
| JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
string a;
unsigned long long int count = 0, output = 0;
cin >> a;
for (int i = 0; i < a.size(); i++) {
if (a[i] == 'h' && a[i + 1] == 'e' && a[i + 2] == 'a' && a[i + 3] == 'v' &&
a[i + 4] == 'y')
count++;
if (a[i] == 'm' && a[i + 1] == 'e' && a[i + 2] == 't' && a[i + 3] == 'a' &&
a[i + 4] == 'l') {
output += count;
}
}
cout << output << endl;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | s = input()
a = 0
su = 0
for i in range(len(s)):
if s[i : i + 5] == 'heavy':
a += 1
elif s[i : i + 5] == 'metal':
su += a
print(su)
| PYTHON3 |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
long long Count(string str) {
long long cnt = 0;
long long res = 0;
for (int i = 0; i < str.size(); i++) {
if (str.substr(i, 5) == "heavy") cnt++;
if (str.substr(i, 5) == "metal") res += cnt;
}
return res;
}
int main() {
string str;
cin >> str;
long long ans = Count(str);
cout << ans << endl;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #!/usr/bin/python
s = raw_input()
a = "heavy"
b = "metal"
n = len(s)
i = 0
w = []
while True:
if i>=n and i>=n: break
if s[i:i+len(a)]==a:
w.append(True)
i = i + 1
elif s[i:i+len(b)]==b:
w.append(False)
i = i + 1
else:
i = i + 1
s = 0
ans = 0
for e in w:
if e: s = s + 1
else: ans = ans + s
print ans
| PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int n, k;
char a[2000009];
const char he[] = {'h', 'e', 'a', 'v', 'y', '\n'};
inline bool checkh(int x) {
int c;
for (c = 0; c + x < n && c < 5; c++) {
if (a[x + c] != he[c]) return 0;
}
if (c == 5) return 1;
return 0;
}
const char met[] = {'m', 'e', 't', 'a', 'l', '\n'};
inline bool checkm(int x) {
int c;
for (c = 0; c + x < n && c < 5; c++) {
if (a[x + c] != met[c]) return 0;
}
if (c == 5) return 1;
return 0;
}
int main() {
int t, i, j, l, x = 0, y = 0;
bool di = 0;
long long count = 0;
scanf("%s", &a);
n = strlen(a);
for (i = 0; i < n;) {
if (checkh(i)) {
x++;
i += 5;
} else if (checkm(i)) {
count += (long long)x;
i += 5;
} else
i++;
}
cout << count;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
char a[1000001];
int main() {
long long sum = 0, aux = 0, i;
cin >> a;
for (i = 0; a[i] != '\0'; i++) {
if (a[i] == 'h' && a[i + 1] == 'e' && a[i + 2] == 'a' && a[i + 3] == 'v' &&
a[i + 4] == 'y') {
aux++;
}
if (a[i] == 'm' && a[i + 1] == 'e' && a[i + 2] == 't' & a[i + 3] == 'a' &&
a[i + 4] == 'l') {
sum += aux;
}
}
cout << sum;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
const int L = 1e6;
char t[L + 1];
bool f[L], g[L];
int sumg[L + 1];
int main() {
scanf(" %s", t);
int len = strlen(t);
for (int i = 0; i < len; i++) {
if (strncmp("heavy", t + i, 5) == 0) f[i] = true;
}
for (int i = 0; i < len; i++) {
if (strncmp("metal", t + i, 5) == 0) g[i] = true;
}
for (int i = len - 1; i >= 0; i--) {
sumg[i] = sumg[i + 1];
if (g[i]) sumg[i]++;
}
long long ret = 0;
for (int i = 0; i < len; i++) {
if (f[i]) ret += sumg[i];
}
cout << ret << endl;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
string a;
cin >> a;
long long ans = 0, h = 0, i, j, k;
for (i = 0; i < a.size(); i++) {
if (a[i] == 'h' && a[i + 1] == 'e' && a[i + 2] == 'a' && a[i + 3] == 'v' &&
a[i + 4] == 'y')
h++, i += 4;
else if (a[i] == 'm' && a[i + 1] == 'e' && a[i + 2] == 't' &&
a[i + 3] == 'a' && a[i + 4] == 'l')
ans += h, i += 4;
}
printf("%lld\n", ans);
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import os
s = raw_input()
heavy = []
i = s.find('heavy')
while i != -1:
heavy.append(i)
i = s.find('heavy',i+1)
metal = []
i = s.find('metal')
while i != -1:
metal.append(i)
i = s.find('metal',i+1)
#def getMetalAfter(num):
#for i in range(len(metal)):
#if num < metal[i]:
#return len(metal) - i
#return 0
count = 0
heavy.reverse()
i = len(metal) - 1
for x in heavy:
while i>= 0 and x < metal[i]:
i -= 1
count += len(metal) - i - 1
print count
| PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
char a[1000100];
scanf("%s", a);
int len = strlen(a) - 4;
long long ans = 0, h = 0, i, j, k;
for (i = 0; i < len; i++) {
if (a[i] == 'h' && a[i + 1] == 'e' && a[i + 2] == 'a' && a[i + 3] == 'v' &&
a[i + 4] == 'y')
h++;
else if (a[i] == 'm' && a[i + 1] == 'e' && a[i + 2] == 't' &&
a[i + 3] == 'a' && a[i + 4] == 'l')
ans += h;
}
printf("%lld\n", ans);
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
long long ans = 0;
int cnt = 0;
for (int i = 0; i < s.size(); i++) {
string sub = s.substr(i, 5);
if (sub == "heavy") {
cnt++;
i += 4;
} else if (sub == "metal") {
ans += cnt;
}
}
cout << ans << endl;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
string st;
int main() {
cin >> st;
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int i, j;
long long int h = 0, m = 0, ans = 0;
for (i = 0; i < (int)(st.length() - 4); i++) {
if (st.substr(i, 5) == "heavy") {
h++;
} else if (st.substr(i, 5) == "metal") {
ans += h;
}
}
printf("%lld", ans);
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] adsa) throws Exception {
BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
PrintWriter out = new PrintWriter( new BufferedOutputStream(System.out) );
String str = br.readLine();
int [] a = getIndexes(str, "heavy");
int [] b = getIndexes(str, "metal");
long count = 0;
int j = 0, i = 0;
while ( i < a.length && j < b.length ) {
if ( a[i] < b[j] ) {
count += b.length - j;
i++;
} else {
j++;
}
}
out.println(count);
out.flush();
}
static int [] getIndexes(String str, String key) {
ArrayList<Integer> list = new ArrayList<Integer>();
int i = - 1;
while (true) {
i = str.indexOf(key, i + 1);
if ( i < 0 ) break;
list.add(i);
}
int res [] = new int [ list.size() ];
i = 0;
for (Integer val : list) {
res[i++] = val;
}
return res;
}
}
| JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
vector<int> heavy;
vector<int> metal;
int i, j, k;
long long int count = 0;
for (i = 0; i < s.size(); i++) {
if (s.substr(i, 5) == "heavy")
heavy.push_back(i + 4);
else if (s.substr(i, 5) == "metal")
metal.push_back(i);
}
sort(heavy.begin(), heavy.end());
sort(metal.begin(), metal.end());
for (i = 0; i < metal.size(); i++) {
k = upper_bound(heavy.begin(), heavy.end(), metal[i]) - heavy.begin();
count += k;
}
cout << count;
return 0;
}
| CPP |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | s=raw_input()
a=list()
m = 0
for i in range(0,len(s)-4):
if s[i:(i+5)]=="heavy": a.append(0)
if s[i:(i+5)]=="metal":
a.append(1)
m = m+1
ans=0
for i in range(0,len(a)):
if a[i] == 0: ans = ans + m
else: m = m-1
print ans
| PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class BB {
static StringTokenizer st;
static BufferedReader in;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
String s = next();
long ans = 0;
int cnt = 0;
for (int i = 0; i <= s.length()-5; i++) {
if (s.substring(i, i+5).equals("heavy"))
cnt++;
else if (s.substring(i, i+5).equals("metal"))
ans += cnt;
}
System.out.println(ans);
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| JAVA |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | l = input().split('metal')
ans = cur = 0
for str in l:
cur += str.count('heavy')
ans += cur
print(ans - cur) | PYTHON3 |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | s = raw_input().strip()
H,M = [[i for i in xrange(len(s)) if s[i:i+5]==S] for S in ['heavy','metal']]
h,m = len(H),len(M)
i,j = 0,0
ans = 0
while i<h and j<m:
if M[j] < H[i]:
j += 1
else:
ans += m-j
i += 1
print ans | PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import sys
import bisect
line = sys.stdin.readline().strip()
heavy = []
metal = []
last = -1
while True:
nxt = line.find("heavy", last + 1)
if nxt == -1:
break
heavy.append(nxt)
last = nxt
last = -1
while True:
nxt = line.find("metal", last + 1)
if nxt == -1:
break
metal.append(nxt)
last = nxt
ans = 0
for h in heavy:
m = bisect.bisect_left(metal, h)
ans += len(metal) - m
print ans
| PYTHON |
318_B. Strings of Power | Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.
Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.
For simplicity, let us assume that Volodya's text can be represented as a single string.
Input
Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.
Output
Print exactly one number — the number of powerful substrings of the given string.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
heavymetalisheavymetal
Output
3
Input
heavymetalismetal
Output
2
Input
trueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyou
Output
3
Note
In the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.
In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal". | 2 | 8 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
###############################################################################
s=input()
n=len(s)
if n<10:
print(0)
else:
i=0
c1,c2=0,0
l1=[0]*n
l2=[0]*n
while i<=n-5:
if s[i]=='h':
if s[i+1:i+5]=='eavy':
c1+=1
l1[i]=c1
if s[n-5-i]=='m':
if s[n-4-i:n-i]=='etal':
c2+=1
l2[n-5-i]=c2
i+=1
ans=0
for i in range(n-5):
if i==0:
if l1[i]==1:
ans+=l2[1]
else:
if l1[i]-l1[i-1]>0:
ans+=l2[i]
print(ans)
| PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.