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
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
import sys def prime(n): v = int(n**0.5)+1 l = [True for i in range(n+1)] l[0]=False l[1]=False for i in range(2,v): if l[i]: for j in range(i,n+1,i): if j%i == 0 and j!=i and l[j]: l[j] = False return l def c_prime(n): if d.get(n,False): return d[n] elif table[n]: d[n] = n return d[n] else: if n == 0 or n == 1: d[n] = 2 return d[n] else: c = 1 while True: if table[n+c]: d[n] = n+c return d[n] c+=1 table = prime(110000) d = {} # print(table) n,m = [int(i) for i in input().split()] s = sys.maxsize matrix = [] for i in range(n): temp = [int(j) for j in input().split()] matrix.append(temp) s = min(s,sum([abs(j-c_prime(j)) for j in temp])) for i in range(m): temp = [j[i] for j in matrix] s = min(s,sum([abs(j-c_prime(j)) for j in temp])) print(s)
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; int prime[maxn]; int nextPrime(int n) { int i; for (i = n; i <= maxn; i++) { if (prime[i] == 0) return i - n; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); memset(prime, 0, sizeof(prime)); int i, j, n, m; for (i = 2; i * i <= maxn; i++) { if (prime[i] == 0) { for (j = i * i; j <= maxn; j += i) prime[j] = 1; } } prime[0] = 1; prime[1] = 1; cin >> n >> m; int a[n][m], b[n][m]; for (i = 0; i < n; i++) for (j = 0; j < m; j++) cin >> a[i][j]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { b[i][j] = nextPrime(a[i][j]); } } long long mi = LONG_MAX, temp = 0; for (i = 0; i < n; i++) { temp = 0; for (j = 0; j < m; j++) temp = temp + b[i][j]; mi = min(mi, temp); } for (i = 0; i < m; i++) { temp = 0; for (j = 0; j < n; j++) temp = temp + b[j][i]; mi = min(mi, temp); } cout << mi << endl; }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> using namespace std; bool a[200005]; int n = 200000; void seieve() { a[0] = a[1] = true; for (int i = 4; i <= n; i += 2) { a[i] = true; } int x = sqrt(n); for (int i = 3; i <= x; i += 2) { if (!a[i]) { for (int j = i * i; j <= n; j += 2 * i) { a[j] = true; } } } } int ma[505][505]; vector<int> v; int g(int val) { if (!a[val]) return val; int x = *(upper_bound(v.begin(), v.end(), val)); return x; } int main() { seieve(); for (int i = 2; i <= n; i++) { if (!a[i]) { v.push_back(i); } } int ni, m; cin >> ni >> m; for (int i = 0; i < ni; i++) { for (int j = 0; j < m; j++) { cin >> ma[i][j]; ma[i][j] = g(ma[i][j]) - ma[i][j]; if (ma[i][j] < 0) { cout << "Hello"; } } } int64_t mi = INT_MAX; for (int i = 0; i < ni; i++) { int64_t s = 0; for (int j = 0; j < m; j++) { s += ma[i][j]; } mi = min(mi, s); } for (int i = 0; i < m; i++) { int64_t s = 0; for (int j = 0; j < ni; j++) { s += ma[j][i]; } mi = min(mi, s); } cout << mi; return 0; }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
from math import * sz = 100010 ind = [] prime = [] for x in range(sz): ind.append(False) def seive(): for x in range(3,sz,2): for y in range(x*x,sz,(2*x)): ind[y] = True prime.append(2) for x in range(3,sz,2): if(not(ind[x])): prime.append(x) def lb(): k = 0 for x in range(100001): if prime[k]<x: k+=1 ind[x] = prime[k] seive() lb() b = input() b = b.split() ans = [] for x in range(int(b[0])): c = input() c = c.split() for y in c: cnt = ind[int(y)]-int(y) ans.append(cnt) l = 100000000000 i = 0 for x in range(int(b[0])): cnt = 0 for y in range(int(b[1])): cnt += ans[i] i+=1 l = min(l,cnt) j = 0 for x in range(int(b[1])): cnt = 0 i = j for y in range(int(b[0])): cnt += ans[i] i+=int(b[1]) l = min(l,cnt) j+=1 print(l)
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
from sys import stdin,stdout input=stdin.readline import math,bisect #from itertools import permutations #from collections import Counter prime=[1]*102001 prime[1]=0 prime[0]=0 for i in range(2,102001): j=i if prime[i]==1: while(j+i<102001): j+=i prime[j]=0 #print(prime) l=[] n,m=map(int,input().split()) for i in range(n): t=list(map(int,input().split())) l.append(t) ans=5000000000 for i in range(n): tot=0 for j in range(m): ele=l[i][j] for k in range(ele,102001): if prime[k]==1: tot+=k-ele break ans=min(ans,tot) for j in range(m): tot=0 for i in range(n): ele=l[i][j] for k in range(ele,102001): if prime[k]==1: tot+=k-ele break ans=min(ans,tot) print(ans)
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
from sys import stdin input = stdin.readline def get_primes(n): primes = [] numbers = [x for x in range(1, n + 1)] checked = [False]*n for i in range(1, n): if checked[i]: continue divisor = numbers[i] primes.append(divisor) for j in range(i + divisor, n, divisor): checked[j] = True return primes primes = get_primes(100_005) costs = [0] i = 0 j = 0 for i in range(1, 100_001): while primes[j] < i: j += 1 costs.append(primes[j] - i) n, m = [int(x) for x in input().split()] a = [[int(x) for x in input().split()] for _ in range(n)] ans = float("inf") for r in range(n): current = 0 for c in range(m): current += costs[a[r][c]] ans = min(ans, current) for c in range(m): current = 0 for r in range(n): current += costs[a[r][c]] ans = min(ans, current) print(ans)
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
size = 10**6 n = size primos = [1]*(n+1) for i in range(2,n+1): if primos[i]==1: for j in range(i*i,n+1,i): primos[j]=0 primos[1] = 0 n,m = map(int, input().split()) ar = [] for i in range(n): ar.append(list(map(int, input().split()))) res = size lstPrimos = [0]*size lstPrimo = size-1 while (not primos[lstPrimo]): lstPrimo-=1 for i in range(lstPrimo,0,-1): if (primos[i]): lstPrimo = i lstPrimos[i] = lstPrimo for i in range(0,n): qtd = 0 for j in range(0,m): k = ar[i][j] qtd += lstPrimos[k] - k res = min(res,qtd) for j in range(0,m): qtd = 0 for i in range(0,n): k = ar[i][j] qtd += lstPrimos[k] - k res = min(res,qtd) print(res)
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
# -*- coding: utf-8 -*- import math def remove_zeros(listNum): listNumAux = [] for num in listNum: if num != 0: listNumAux.append(num) return listNumAux def sieve_of_eratosthenes(): limNumbers = 100004 limTest = math.ceil(math.sqrt(limNumbers)) listNum = list(range(2, limNumbers)) i = 0 for i in range(0, limTest): if listNum[i] != 0: for j in range((listNum[i]**2)-2, limNumbers-2, listNum[i]): listNum[j] = 0 listNum = remove_zeros(listNum) return listNum def bs(A, esquerda, direita, item): if direita < esquerda or len(A) == 2: if A[esquerda] > item: return A[esquerda] else: return A[direita] meio = (esquerda + direita) // 2 if A[meio] == item: return A[meio] elif A[meio] > item: return bs(A, esquerda, meio - 1, item) else: return bs(A, meio + 1, direita, item) def main(): n, m = input().split(' ') n = int(n) m = int(m) primeNumbers = sieve_of_eratosthenes() sumCols = [0 for x in range(m)] minLine = 1000000 for i in range(n): line = input().split(' ') sumLine = 0 for j in range(m): num = int(line[j]) dist = bs(primeNumbers,0, len(primeNumbers), num) - num sumLine += dist sumCols[j] += dist if minLine > sumLine: minLine = sumLine minCol = 1000000 for sumCol in sumCols: if minCol > sumCol: minCol = sumCol if minCol < minLine: print(minCol) else: print(minLine) main()
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> using namespace std; const int MAXN = 505; const int MAXM = 1e6 + 5; int n, m, val[MAXN][MAXN]; int tot, prime[MAXM]; bool is_prime[MAXM]; void sieves() { memset(is_prime, true, sizeof(is_prime)); tot = 0; for (int i = 2; i <= 1e6; i++) { if (is_prime[i]) prime[tot++] = i; for (int j = 0; j < tot && prime[j] * i <= 1e6; j++) { is_prime[prime[j] * i] = false; if (i % prime[j] == 0) break; } } } int get(int x) { if (x == 1) return 1; if (is_prime[x]) return 0; int l = 0, r = tot, mid; while (l <= r) { int mid = l + r >> 1; if (prime[mid] > x) r = mid - 1; else l = mid + 1; } return abs(x - prime[l]); } int main() { sieves(); scanf("%d%d", &n, &m); int x; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf("%d", &x); val[i][j] = get(x); } } long long ans = 1e18; for (int i = 1; i <= n; i++) { long long tmp = 0; for (int j = 1; j <= m; j++) { tmp += val[i][j]; } ans = min(ans, tmp); } for (int j = 1; j <= m; j++) { long long tmp = 0; for (int i = 1; i <= n; i++) { tmp += val[i][j]; } ans = min(ans, tmp); } printf("%lld\n", ans); }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
crivo = [True for i in xrange(1000000)] crivo[0] = crivo[1] = False for i in xrange(2, 1000000): if not crivo[i]: continue for j in range(i * i, 1000000, i): crivo[j] = False n, m = map(int, raw_input().split()) data = [] for i in xrange(n): data.append(map(int, raw_input().split())) count = [0 for i in xrange(200000)] count[100000] = 3 for i in xrange(99999, -1, -1): if crivo[i]: count[i] = 0 else: count[i] = 1 + count[i+1] res = 100000 for i in xrange(n): sum = 0 for j in xrange(m): sum += count[data[i][j]] res = min(res, sum) for i in xrange(m): sum = 0 for j in xrange(n): sum += count[data[j][i]] res = min(res, sum) print res
PYTHON
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
M=110000 p=[0,0]+[1]*M for i in range(2,M): if p[i]: for j in range(i*i,M,i):p[j]=0; u=M for i in reversed(range(M)): if p[i]:u=i p[i]=u-i R=lambda:map(int,raw_input().split()) n,m=R() a=[R() for _ in range(n)] t=10**10 for v in a: t=min(t,sum(map(lambda x:p[x],v))) for v in zip(*a): t=min(t,sum(map(lambda x:p[x],v))) print t
PYTHON
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static ArrayList<Integer> primess; static void seive () { primess = new ArrayList<>(); int n = (int)1e6 + 1; boolean primes [] = new boolean[n+1]; Arrays.fill(primes, true); primes[0]=primes[1]=false; for(int i =0 ; i*i<=n; i++) if(primes[i]) { for(int j =2 ;i*j <=n ; j++) primes [i*j]=false; } for (int i = 0 ; i < n ; ++i) if (primes[i]) primess.add(i); } static int bs (int num ) { int lo = 0; int hi = primess.size() - 1; int best = (int)1e6 + 1; for (int i = 0 ; i < 30 ; ++i) { int mid = lo + ((hi - lo) >> 1); int curNum = primess.get(Math.max(0, mid)); if (curNum == num) { return 0 ; } else if (curNum < num) { lo = mid + 1; } else { best = Math.min(best, curNum - num); hi = mid - 1; } } return best; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); PrintWriter out = new PrintWriter(System.out); seive(); int n = sc.nextInt(); int m = sc.nextInt(); int mat [][] = new int[n][m]; for (int i = 0 ; i < n ; ++i) for (int j = 0 ; j < m ; ++j) mat[i][j] = bs(sc.nextInt()); long best = (long)1e12; ; for (int i = 0 ; i < n ; ++i) { long cnt = 0 ; for (int j = 0 ; j < m ; ++j) cnt += mat[i][j]; best = Math.min(best, cnt); } for (int j = 0 ; j < m ; ++ j) { long cnt = 0; for (int i = 0 ; i < n ; ++i) cnt += mat[i][j]; best = Math.min(best, cnt); } out.print(best); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static PrintWriter out; static StringTokenizer st; static boolean[] genPrimes() { int N = 100010; boolean[] isPrime = new boolean[N]; Arrays.fill(isPrime, true); isPrime[1] = false; for (int i = 2; i * i < N; i++) if (isPrime[i]) for (int j = i * i; j < N; j += i) isPrime[j] = false; return isPrime; } static int getWeight(int n, boolean[] prime) { int cnt = 0; for (int i = n; !prime[i]; i++) { cnt++; } return cnt; } static void solve() throws Exception { int n = nextInt(); int m = nextInt(); int[][] a = new int[n][m]; int[][] w = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextInt(); } } boolean[] prime = genPrimes(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { w[i][j] = getWeight(a[i][j], prime); } } int min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum += w[i][j]; } min = Math.min(min, sum); } for (int i = 0; i < m; i++) { int sum = 0; for (int j = 0; j < n; j++) { sum += w[j][i]; } min = Math.min(min, sum); } System.out.println(min); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public static void main(String[] args) { try { File file = new File(".in"); InputStream input = System.in; OutputStream output = System.out; if (file.canRead()) { input = new FileInputStream(file); output = new FileOutputStream(".out"); } br = new BufferedReader(new InputStreamReader(input)); out = new PrintWriter(new PrintStream(output)); solve(); out.close(); br.close(); } catch (Throwable t) { t.printStackTrace(); } } }
JAVA
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> using namespace std; int a[1000][1000]; int c[100000 + 10]; int r[1000000 + 10]; bool t[1000000 + 10]; int pr[100000 + 10]; int main() { int n, m; cin >> n >> m; for (int i = 2; i <= 100000 + 10; i++) { bool k = true; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { k = false; } } if (k == true) { t[i] = 1; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int pnt = a[i][j]; int pnt2 = a[i][j]; while (t[pnt2] != 1) { pnt2++; r[i]++; c[j]++; } } } int min = 1000 * 1000 * 1000 + 1; for (int i = 1; i <= n; i++) { if (r[i] < min) { min = r[i]; } } for (int i = 1; i <= m; i++) { if (c[i] < min) { min = c[i]; } } cout << min; }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
//package ladderB; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class primeMatrix { static ArrayList<Integer> primes; static boolean [] prime; static void gen() { prime = new boolean[(int)1e6]; primes = new ArrayList<Integer>(); Arrays.fill(prime, true); for (int i = 2; i <=1000; i++) { if(prime[i]) for (int j = i*i; j < prime.length; j+=i) { prime[j] = false; } } for (int i = 2; i < prime.length; i++) { if(prime[i]) primes.add(i); } } static int bs(int cur) { int low = 0; int high = primes.size()-1; int diff = (int)1e9; while(low<=high) { int mid = (low + high)/2; int prime = primes.get(mid); if(prime==cur) return 0; else if(prime<cur) { low = mid +1; }else { diff = Math.min(diff, prime-cur); high = mid-1; } } return diff; } public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int [][] matrix = new int[n][m]; int [][] ans = new int[n][m]; gen(); for (int i = 0; i < matrix.length; i++) { st = new StringTokenizer(in.readLine()); for (int j = 0; j < matrix[i].length; j++) { matrix[i][j] = Integer.parseInt(st.nextToken()); ans[i][j]= bs(matrix[i][j]); } } int min = (int)1e9; for (int i = 0; i < ans.length; i++) { int cur = 0; for (int j = 0; j < ans[i].length; j++) { // System.out.print(ans[i][j]+" "); cur+=ans[i][j]; } // System.out.println(); min = Math.min(cur, min); } for (int i = 0; i < ans[0].length; i++) { int cur = 0; for (int j = 0; j < ans.length; j++) { cur+=ans[j][i]; } min = Math.min(cur, min); } System.out.println(min); } }
JAVA
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
n, m = map(int, raw_input().split()) g = [[] for i in xrange(n)] for i in xrange(n): g[i] = map(int, raw_input().split()) prime = [True for i in xrange(110000)] prime[0] = 0 prime[1] = 0 for i in xrange(4, 110000, 2): prime[i] = False p = [2] for i in xrange(3, 110000, 2): if prime[i]: p.append(i) for j in xrange(i + i, 110000, i): prime[j] = False l = len(p) ne = range(100100) t= 999999 for i in xrange(100100-1, 0, -1): if not prime[i]: ne[i] = t else: t = i ne[i] = t #print prime[4] #print 'ac' for i in xrange(n): for j in xrange(m): #print prime[g[i][j]] if prime[g[i][j]]: g[i][j] = 0 else: g[i][j] = ne[g[i][j]] - g[i][j] #print g #print 'wa' ans = 9999999 for i in xrange(n): temp = sum(g[i]) if temp < ans: ans = temp if ans: for j in xrange(m): temp = 0 for i in xrange(n): temp += g[i][j] if temp > ans: break if temp < ans: ans = temp print ans
PYTHON
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> using namespace std; int z[501], y[501]; vector<int> v; int main() { v.clear(); bool check; int m, n, i, j, x, ans = INT_MAX; for (i = 2; i < 100500; i++) { check = 1; for (j = 2; j * j <= i; j++) { if (i % j == 0) { check = 0; break; } } if (check) v.push_back(i); } cin >> n >> m; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { cin >> x; z[i] += *lower_bound(v.begin(), v.end(), x) - x; y[j] += *lower_bound(v.begin(), v.end(), x) - x; } } for (i = 0; i < n; i++) ans = min(ans, z[i]); for (i = 0; i < m; i++) ans = min(ans, y[i]); cout << ans; return 0; }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
def get_primes(n): isPrime = [True] * (n+1) isPrime[0] = isPrime[1] = False for i in xrange(2, n+1): if i*i > n: break if isPrime[i]: for j in xrange(i*i, n+1, i): isPrime[j] = False return [i for i in xrange(2, n+1) if isPrime[i]] N = 10**5 primes = get_primes(N+1000) d2 = [None] * (N+1) i = N lastP = primes[-1] for p in reversed(primes[:-1]): while i > p: d2[i] = abs(i - lastP) i -= 1 lastP = p while i >= 0: d2[i] = abs(i - lastP) i -= 1 def solve(): n, m = map(int, raw_input().split()) a = [] for i in xrange(n): a.append(list(map(int, raw_input().split()))) ans = 10**9 for i in xrange(n): tmp = sum(d2[x] for x in a[i]) ans = min(ans, tmp) for i in xrange(m): tmp = sum(d2[a[j][i]] for j in xrange(n)) ans = min(ans, tmp) print ans solve()
PYTHON
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
def f(n): m = int(n ** 0.5) + 1 t = [1, 0] * (n // 2 + 1) t[0], t[1], t[2] = 1, 1, 0 for i in range(3, m): if t[i] == 0: t[i * i :: 2 * i] = [1] * ((n - i * i) // (2 * i) + 1) for i in range(n - 1, -1, -1): if t[i]: t[i] = t[i + 1] + 1 return t q = f(100007) n, m = map(int, input().split()) t = [[q[j] for j in map(int, input().split())] for i in range(n)] print(min(min(sum(t[i]) for i in range(n)), min(sum(t[i][j] for i in range(n)) for j in range(m)))) # Made By Mostafa_Khaled
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
import java.io.*; import java.math.*; import java.util.*; public class Olimp { public static void main(String[] arg) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[][] a = new int[n][m]; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) a[i][j] = in.nextInt(); boolean[] pm = new boolean[110005]; for(int i = 2; i < 110005; i++) pm[i] = true; int i = 2; while (i < 110000){ if (pm[i]){ int j = i * 2; while (j < 110000){ pm[j] = false; j += i; } } i++; } int[][] d = new int[n][m]; int ans = Integer.MAX_VALUE; for(i = 0; i < n; i++){ for(int j = 0; j < m; j++){ int tmp = a[i][j]; while (!pm[tmp]){ tmp++; d[i][j]++; } } } for(i = 0; i < n; i++){ int tmp = 0; for(int j = 0; j < m; j++) tmp += d[i][j]; if (tmp < ans) ans = tmp; } for(i = 0; i < m; i++){ int tmp = 0; for(int j = 0; j < n; j++) tmp += d[j][i]; if (tmp < ans) ans = tmp; } System.out.println(ans); } }
JAVA
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> int Min(int a, int b) { return a < b ? a : b; } int main() { bool vis[110000]; int n, m, con[500][500], prime[12000], flag = 0, myMin = 100000000; for (int i = 2; i < 332; i++) { if (vis[i]) continue; for (int j = i * i; j < 110000; j += i) { vis[j] = true; } } for (int i = 2; i < 110000; i++) if (!vis[i]) prime[flag++] = i; scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &con[i][j]); } } for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum += prime[std::lower_bound(prime, prime + flag, con[i][j]) - prime] - con[i][j]; } myMin = Min(myMin, sum); } for (int i = 0; i < m; i++) { int sum = 0; for (int j = 0; j < n; j++) { sum += prime[std::lower_bound(prime, prime + flag, con[j][i]) - prime] - con[j][i]; } myMin = Min(myMin, sum); } printf("%d\n", myMin); }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
n, m = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(n)] isPrime = [False, False] + [True] * 101000 for i in range(2, len(isPrime)): if isPrime[i]: for j in range(i*i, len(isPrime), i): isPrime[j] = False nextPrime = [0] * len(isPrime) for i in range(len(isPrime) - 2, 0, -1): if isPrime[i]: nextPrime[i] = i else: nextPrime[i] = nextPrime[i+1] row_scores = [0] * n col_scores = [0] * m for i in range(n): for j in range(m): row_scores[i] += nextPrime[a[i][j]] - a[i][j] col_scores[j] += nextPrime[a[i][j]] - a[i][j] print(min(row_scores + col_scores))
PYTHON3
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; template <class c> struct rge { c b, e; }; template <class c> rge<c> range(c i, c j) { return rge<c>{i, j}; } template <class c> auto dud(c* x) -> decltype(cerr << *x, 0); template <class c> char dud(...); struct debug { template <class c> debug& operator<<(const c&) { return *this; } }; bool isPrime[1000005]; void sie(long long n) { memset(isPrime, true, sizeof isPrime); isPrime[0] = isPrime[1] = false; for (long long i = 2; i * i <= n; i++) { if (isPrime[i]) { for (long long j = i * i; j <= n; j += i) { isPrime[j] = false; } } } } vector<long long> pr; long long cnti[505], cntj[505]; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); sie(1000004); for (long long i = 2; i < 1000005; i++) { if (isPrime[i]) pr.push_back(i); } long long n, m; cin >> n >> m; vector<vector<long long> > a(n, vector<long long>(m)); for (long long i = 0; i < n; i++) { for (long long j = 0; j < m; j++) { cin >> a[i][j]; long long ind = lower_bound((pr).begin(), (pr).end(), a[i][j]) - pr.begin(); cnti[i] += (pr[ind] - a[i][j]); cntj[j] += (pr[ind] - a[i][j]); } } long long mn = 1e9; for (long long i = 0; i < n; i++) { mn = min(mn, cnti[i]); } for (long long i = 0; i < m; i++) { mn = min(mn, cntj[i]); } cout << mn << "\n"; return 0; }
CPP
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
import java.io.IOException; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { HashSet<Integer> primes; boolean[] p; public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int M = in.nextInt(); int[][] A = new int[N][M]; for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) A[i][j] = in.nextInt(); primes = new HashSet<Integer>(); p = new boolean[100010]; for(int i = 2; i < 100010; i++) if(!p[i]) { primes.add(i); if((long)i * i < 100010) for(int j = i * i; j < 100010; j += i) p[j] = true; } // rows int minRow = Integer.MAX_VALUE; for(int i = 0; i < N; i++) { int crt = 0; for(int j = 0; j < M; j++) crt += need(A[i][j]); minRow = Math.min(minRow, crt); } // cols int minCol = Integer.MAX_VALUE; for(int i = 0; i < M; i++) { int crt = 0; for(int j = 0; j < N; j++) crt += need(A[j][i]); minCol = Math.min(minCol, crt); } int ans = Math.min(minRow, minCol); out.println(ans); } private int need(int x) { int ret = 0; while(!primes.contains(x)) { x++; ret++; } return ret; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { return Integer.parseInt(nextString()); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } }
JAVA
271_B. Prime Matrix
You've got an n Γ— m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times. You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: * the matrix has a row with prime numbers only; * the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. Input The first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers β€” the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. Output Print a single integer β€” the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. Examples Input 3 3 1 2 3 5 6 1 4 4 1 Output 1 Input 2 3 4 8 8 9 2 9 Output 3 Input 2 2 1 3 4 2 Output 0 Note In the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3. In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2. In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.
2
8
#include <bits/stdc++.h> using namespace std; const int maxmn = 505; long long a[maxmn][maxmn]; long long luu1[maxmn][maxmn]; bool k[1000005]; long long maxx = 1e9; void readquick() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } int main() { readquick(); vector<long long> luu; memset(k, true, sizeof k); for (int i = 2; i <= sqrt(1000000); i++) { if (k[i] == true) { for (int j = i * i; j <= 1000000; j += i) { k[j] = false; } } } for (int i = 2; i <= 1000000; i++) { if (k[i] == true) luu.push_back(i); } int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; int w = lower_bound(luu.begin(), luu.end(), a[i][j]) - luu.begin(); luu1[i][j] = luu[w] - a[i][j]; } } for (int i = 1; i <= n; i++) { long long tong = 0; for (int j = 1; j <= m; j++) { tong += luu1[i][j]; } if (tong >= 0) { maxx = min(maxx, tong); } } for (int i = 1; i <= m; i++) { long long tong = 0; for (int j = 1; j <= n; j++) { tong += luu1[j][i]; } if (tong >= 0) { maxx = min(maxx, tong); } } cout << maxx; 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, s, t, x, y; long long ans; set<pair<int, int> > st; int rd() { char c; while (c = getchar(), c < 'A') ; return c; } int main() { scanf("%d%d%d%d", &m, &n, &t, &s); y = (rd() == 'D') ? 1 : -1, x = (rd() == 'R') ? 1 : -1; ans = 1; for (int i = 1; i <= 2 * (n + m); i++) { st.insert(pair<int, int>(s, t)); if (s == 1) x = 1; if (s == n) x = -1; if (t == 1) y = 1; if (t == m) y = -1; if (st.size() >= n + m - 2) return printf("%I64d\n", ans), 0; int z = min(x > 0 ? n - s : s - 1, y > 0 ? m - t : t - 1); ans += z, s += x * z, t += y * z; } return puts("-1"), 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; const int MAX = 100010; int n, m, x, y; int k; bool top[MAX], bottom[MAX], lft[MAX], rgt[MAX]; 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; } if (k == 0) { int d = min(n - 1 - x, m - 1 - y); ret += d; x += d; y += d; } else if (k == 1) { int d = min(n - 1 - x, y); ret += d; x += d; y -= d; } else if (k == 2) { int d = min(x, m - 1 - y); ret += d; x -= d; y += d; } else { int d = min(x, y); ret += d; x -= d; y -= 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; int n, m, s, dx, dy; long long ans; map<pair<int, int>, int> h; char a[5]; void work(int x, int y) { int nx, ny, t; if (dx == -1) t = x - 1; else t = n - x; if (dy == -1) t = min(t, y - 1); else t = min(t, m - y); ans += t; x += dx * t; y += dy * t; h[make_pair(x, y)]++; t = h[make_pair(x, y)]; if (t == 1) s--; else if (t >= 3) { printf("%d\n", -1); return; } if (s == 0) { printf("%I64d\n", ans + 1); return; } if (x == 1 || x == n) dx *= -1; if (y == 1 || y == m) dy *= -1; work(x, y); } void check(int x, int y, int k) { if ((x + y) % 2 == k % 2 && h.find(make_pair(x, y)) == h.end()) { h[make_pair(x, y)] = 1; s++; } } int main() { int i, j, x, y; scanf("%d%d", &n, &m); scanf("%d%d%s", &x, &y, a + 1); for (i = 1; i <= n; i++) { check(i, 1, x + y); check(i, m, x + y); } for (j = 1; j <= m; j++) { check(1, j, x + y); check(n, j, x + y); } h.clear(); if (a[1] == 'D') dx = 1; else dx = -1; if (a[2] == 'R') dy = 1; else dy = -1; if ((x == 1 && dx == -1) || (x == n && dx == 1)) dx *= -1; if ((y == 1 && dy == -1) || (y == m && dy == 1)) dy *= -1; h[make_pair(x, y)] = 1; s--; work(x, y); 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 = 100100; int n, m; int x, y; int l[N][4], r[N][4], u[N][4], d[N][4]; char s[N]; inline long long int get(int ot) { int lt(x); if (ot == 0) { int tmp(y - x); if (n - tmp <= m) x = n - tmp, y = n; else x = m, y = tmp + m; } else if (ot == 1) { int tmp(x + y); if (tmp - 1 <= m) x = tmp - 1, y = 1; else x = m, y = tmp - m; } else if (ot == 2) { int tmp(y - x); if (1 - tmp >= 1) x = 1 - tmp, y = 1; else x = 1, y = tmp + 1; } else if (ot == 3) { int tmp(x + y); if (tmp - n >= 1) x = tmp - n, y = n; else x = 1, y = tmp - 1; } return abs(lt - x); } inline int checkL() { for (int i = 0; i < 4; ++i) if (l[y][i]) return 0; return 1; } inline int checkR() { for (int i = 0; i < 4; ++i) if (r[y][i]) return 0; return 1; } inline int checkD() { for (int i = 0; i < 4; ++i) if (d[x][i]) return 0; return 1; } inline int checkU() { for (int i = 0; i < 4; ++i) if (u[x][i]) return 0; return 1; } inline int turn(int ot) { if (x == 1) { if (y == 1) return 0; else if (y == n) return 1; else if (ot == 2) return 1; else return 0; } else if (x == m) { if (y == 1) return 3; else if (y == n) return 2; else if (ot == 1) return 2; else return 3; } else if (y == 1) { if (x == 1) return 0; else if (x == m) return 3; else if (ot == 1) return 0; else return 3; } else if (y == n) { if (x == 1) return 1; else if (x == m) return 2; else if (ot == 0) return 1; else return 2; } return -1; } inline bool check(int ot) { if (x == 1) return l[y][ot]; if (x == m) return r[y][ot]; if (y == 1) return d[x][ot]; if (y == n) return u[x][ot]; return false; } int main() { int ot; scanf("%d%d", &n, &m); long long int ans(1); scanf("%d%d", &x, &y); scanf("%s", s + 1); swap(x, y); y = n - y + 1; if (s[1] == 'U' && s[2] == 'R') ot = 0; else if (s[1] == 'D' && s[2] == 'R') ot = 1; else if (s[1] == 'D' && s[2] == 'L') ot = 2; else if (s[1] == 'U' && s[2] == 'L') ot = 3; int tmp(0); if (x == 1) { tmp += checkL(), l[y][ot] = 1; if (y == 1) d[x][ot] = 1; if (y == n) u[x][ot] = 1; } if (x == m) { tmp += checkR(), r[y][ot] = 1; if (y == 1) d[x][ot] = 1; if (y == n) u[x][ot] = 1; } if (y == 1) { tmp += checkD(), d[x][ot] = 1; if (x == 1) l[y][ot] = 1; if (x == m) r[y][ot] = 1; } if (y == n) { tmp += checkU(), u[x][ot] = 1; if (x == 1) l[y][ot] = 1; if (x == m) r[y][ot] = 1; } int all(n + m - 2); for (; tmp < all;) { ans += get(ot); if (x == 1) { tmp += checkL(), l[y][ot] = 1; if (y == 1) d[x][ot] = 1; if (y == n) u[x][ot] = 1; } if (x == m) { tmp += checkR(), r[y][ot] = 1; if (y == 1) d[x][ot] = 1; if (y == n) u[x][ot] = 1; } if (y == 1) { tmp += checkD(), d[x][ot] = 1; if (x == 1) l[y][ot] = 1; if (x == m) r[y][ot] = 1; } if (y == n) { tmp += checkU(), u[x][ot] = 1; if (x == 1) l[y][ot] = 1; if (x == m) r[y][ot] = 1; } ot = turn(ot); if (check(ot)) { printf("-1"); return 0; } if (x == 1) l[y][ot] = 1; if (x == m) r[y][ot] = 1; if (y == 1) d[x][ot] = 1; if (y == n) u[x][ot] = 1; } printf("%lld", 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; int x, y, dx = 1, dy = 1; int tot = 0; char s[6]; set<pair<int, int> > vis; void move(int x, int y) { if (!vis.count(pair<int, int>(x, y))) { vis.insert(pair<int, int>(x, y)); tot++; } if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; if (y == m) dy = -1; } int main() { cin >> n >> m; cin >> x >> y >> s; if (s[0] == 'U') dx = -1; if (s[1] == 'L') dy = -1; move(x, y); long long ans = 1; for (int i = 1; i <= (n + m) * 2; i++) { int t = min(dx == 1 ? n - x : x - 1, dy == 1 ? m - y : y - 1); ans += t; x += dx * t; y += dy * t; move(x, y); if (tot == n + m - 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 MAXN = 100010; int n, m, x, y, vx, vy; int vis[5 * MAXN]; int get(int x, int y) { if (x == 1) return y; if (y == m) return m + x - 1; if (x == n) return m + m + n - 1 - y; return m + m + n + n - 2 - x; } int min(int a, int b) { return a > b ? b : a; } int max(int a, int b) { return a > b ? a : b; } int main() { scanf("%d%d", &n, &m); scanf("%d%d", &x, &y); char str[5]; scanf("%s", str); if (str[0] == 'D') vx = 1; else vx = -1; if (str[1] == 'R') vy = 1; else vy = -1; long long ans = 1, now = 0; memset(vis, 0, sizeof(vis)); if (x == 1 || y == 1 || x == n || y == m) { now = 1; vis[get(x, y)] = 1; } while (now < m + n - 2) { if (x + vx <= 0 || x + vx > n) vx = -vx; if (y + vy <= 0 || y + vy > m) vy = -vy; int t = min(max((1 - x) / vx, (n - x) / vx), max((1 - y) / vy, (m - y) / vy)); x = x + vx * t; y = y + vy * t; ans += t; int pos = get(x, y); if (!vis[pos]) now++; else if (vis[pos] >= 2) { printf("-1"); return 0; } vis[pos]++; } printf("%lld\n", ans); }
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, dire[4][2] = {{-1, -1}, {-1, 1}, {1, 1}, {1, -1}}, nowx, nowy, nowd, rest; long long ans; bool f[2][100005 * 2][2], posr[4][100005]; int transdire(char *st) { if (st[0] == 'U') if (st[1] == 'L') return 0; else return 1; else if (st[1] == 'R') return 2; else return 3; return 0; } void setpos(void) { int a, b; if (nowx == 1) a = 0, b = nowy; else if (nowx == n) a = 1, b = nowy; else if (nowy == 1) a = 2, b = nowx; else a = 3, b = nowx; if (!posr[a][b]) posr[a][b] = true, rest--; return; } bool makeflag(void) { int a, b, c; if (nowd == 0 || nowd == 2) { if (nowd == 0) c = 0; else c = 1; a = 0; b = nowy - nowx + n; } else { if (nowd == 1) c = 0; else c = 1; a = 1; b = nowx + nowy; } if (!f[a][b][c]) return f[a][b][c] = true; else return false; } void gostraight(void) { int dt; switch (nowd) { case 0: dt = min(nowx - 1, nowy - 1); break; case 1: dt = min(nowx - 1, m - nowy); break; case 2: dt = min(n - nowx, m - nowy); break; case 3: dt = min(n - nowx, nowy - 1); break; default: break; } ans += dt; nowx += dire[nowd][0] * dt; nowy += dire[nowd][1] * dt; setpos(); return; } bool notoveredge(int tryd) { int temx, temy; temx = nowx + dire[tryd][0]; temy = nowy + dire[tryd][1]; if (temx >= 1 && temx <= n && temy >= 1 && temy <= m) return true; else return false; } void rotate(void) { if (notoveredge(nowd)) return; if (notoveredge((nowd + 1) % 4)) { nowd = (nowd + 1) % 4; return; } if (notoveredge((nowd + 3) % 4)) { nowd = (nowd + 3) % 4; return; } nowd = (nowd + 2) % 4; return; } long long running(void) { if (nowx == 1 || nowx == n || nowy == 1 || nowy == m) setpos(), rotate(), gostraight(), makeflag(); else gostraight(); if (rest == 0) return ans; while (1) { rotate(); gostraight(); if (!makeflag()) return -1; if (rest == 0) return ans; } return -1; } int main() { char st[10]; memset(f, 0, sizeof(f)); scanf("%d%d", &n, &m); scanf("%d%d%s", &nowx, &nowy, st); nowd = transdire(st); ans = 1; rest = ((n + m) * 2 - 4) / 2; printf("%I64d\n", running()); 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; struct node { int x, y; node() {} node(int _x, int _y) : x(_x), y(_y) {} bool operator<(const node& o) const { return x == o.x ? y < o.y : x < o.x; } bool operator>(const node& o) const { return x == o.x ? y > o.y : x > o.x; } }; struct status { int p[4]; status() { memset(p, 0, sizeof(p)); } }; map<node, status> mp; int main() { int n, m, sx, sy, sdir; unsigned long long ans = 1; ios::sync_with_stdio(0); string tt; cin >> n >> m >> sx >> sy >> tt; if (tt == "DR") sdir = 0; if (tt == "DL") sdir = 1; if (tt == "UR") sdir = 2; if (tt == "UL") sdir = 3; mp[node(sx, sy)].p[sdir]++; int i = sx, j = sy; while (1) { int ii, jj, dir; if (sdir == 0) { if (n + j - i > m) ii = m + i - j, jj = m, dir = 1; if (n + j - i == m) ii = n, jj = m, dir = 3; if (n + j - i < m) ii = n, jj = n + j - i, dir = 2; } else if (sdir == 1) { if (i + j - 1 > n) ii = n, jj = i + j - n, dir = 3; if (i + j - 1 == n) ii = n, jj = 1, dir = 2; if (i + j - 1 < n) ii = i + j - 1, jj = 1, dir = 0; } else if (sdir == 2) { if (i + j - m > 1) ii = i + j - m, jj = m, dir = 3; if (i + j - m == 1) ii = 1, jj = m, dir = 1; if (i + j - m < 1) ii = 1, jj = i + j - 1, dir = 0; } else if (sdir == 3) { if (1 + i - j > 1) ii = 1 + i - j, jj = 1, dir = 2; if (1 + i - j == 1) ii = 1, jj = 1, dir = 0; if (1 + i - j < 1) ii = 1, jj = 1 + j - i, dir = 1; } mp[node(ii, jj)].p[dir]++; ans += abs(ii - i); i = ii, j = jj, sdir = dir; for (int I = 0; I < 4; I++) if (mp[node(ii, jj)].p[I] > 1) { cout << -1; return 0; } if (mp.size() == m + n - 2) { cout << ans; 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
import static java.lang.Math.*; //@SuppressWarnings("unused") public class D { private final static boolean autoflush = false; private static final int INF = (int) 1e9; 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; long res = 1; for (;;) { if (mark()) break; res += next(); } exit(res); } private int N, M, Z, K = 0; private int [] A, B, C, D, W, T; 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 boolean mark() { int X = W[0], Y = W[1]; 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; } private boolean inc(int [] A, int X) { --X; if (A[X] == 0) ++K; ++A[X]; if (A[X] == 3) exit(-1); return K == Z; } //////////////////////////////////////////////////////////////////////////////////// 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; struct Segment { int coverTime, coverSize; Segment() { coverTime = coverSize = 0; } Segment(int coverTime, int coverSize) : coverTime(coverTime), coverSize(coverSize) {} Segment operator+(const Segment &rhs) const { return Segment(0, coverSize + rhs.coverSize); } }; const int MAXNODE = 200000 << 2; struct SegmentTree { int n; Segment seg[MAXNODE]; static int LEFT(int idx) { return idx << 1; } static int RIGHT(int idx) { return (idx << 1) | 1; } void _build(int idx, int lower, int upper) { if (lower == upper) { seg[idx] = Segment(); return; } int middle = (lower + upper) >> 1; _build(LEFT(idx), lower, middle); _build(RIGHT(idx), middle + 1, upper); seg[idx] = seg[LEFT(idx)] + seg[RIGHT(idx)]; } void init(int n) { this->n = n; _build(1, 0, n - 1); } int x, v; void _modify(int idx, int lower, int upper) { if (lower == upper) { if (!seg[idx].coverTime) { seg[idx].coverSize = 1; } seg[idx].coverTime += v; if (!seg[idx].coverTime) { seg[idx].coverSize = 0; } return; } int middle = (lower + upper) >> 1; if (x <= middle) { _modify(LEFT(idx), lower, middle); } else if (middle < x) { _modify(RIGHT(idx), middle + 1, upper); } else { _modify(LEFT(idx), lower, middle); _modify(RIGHT(idx), middle + 1, upper); } seg[idx] = seg[LEFT(idx)] + seg[RIGHT(idx)]; } void modify(int x, int v) { this->x = x; this->v = v; _modify(1, 0, n - 1); } int l, r; Segment _calc(int idx, int lower, int upper) { if (l <= lower && upper <= r) { return seg[idx]; } int middle = (lower + upper) >> 1; if (r <= middle) { return _calc(LEFT(idx), lower, middle); } else if (middle < l) { return _calc(RIGHT(idx), middle + 1, upper); } else { return _calc(LEFT(idx), lower, middle) + _calc(RIGHT(idx), middle + 1, upper); } } Segment calc(int l, int r) { this->l = l; this->r = r; return _calc(1, 0, n - 1); } Segment calc(int x) { this->l = this->r = x; return _calc(1, 0, n - 1); } }; const int DX[4] = {-1, -1, 1, 1}; const int DY[4] = {-1, 1, 1, -1}; map<string, int> dirMap; void init() { dirMap["UL"] = 0; dirMap["UR"] = 1; dirMap["DR"] = 2; dirMap["DL"] = 3; } const int MAXN = 100010; int n, m, cnt[2][MAXN << 1]; vector<pair<pair<int, int>, int> > dirLst; SegmentTree sgt[2]; bool cover(int x, int y, int dir) { int pos = dir & 1 ? x + y : x - y + m - 1; if (cnt[dir & 1][pos] > 1) return false; cnt[dir & 1][pos]++; sgt[dir & 1].modify(pos, 1); return true; } void uncover(int x, int y, int dir) { int pos = dir & 1 ? x + y : x - y + m - 1; cnt[dir & 1][pos]--; sgt[dir & 1].modify(pos, -1); } pair<pair<int, int>, int> nextDir(int x, int y, int dir) { int step = min(DX[dir] > 0 ? n - 1 - x : x, DY[dir] > 0 ? m - 1 - y : y); x += DX[dir] * step; y += DY[dir] * step; if (DX[dir] > 0 && x == n - 1 || DX[dir] < 0 && !x) dir ^= 3; if (DY[dir] > 0 && y == m - 1 || DY[dir] < 0 && !y) dir ^= 1; return make_pair(make_pair(x, y), dir); } bool parity; bool fullyCover() { for (int row = parity; row < n; row += 2) { int column = 0; pair<pair<int, int>, int> state = nextDir(row, column, 2); if (!cnt[0][row - column + m - 1] && sgt[1].calc(row + column, state.first.first + state.first.second) .coverSize != abs(row - state.first.first) + 1) { return false; } } for (int column = parity; column < m; column += 2) { int row = 0; pair<pair<int, int>, int> state = nextDir(row, column, 2); if (!cnt[0][row - column + m - 1] && sgt[1].calc(row + column, state.first.first + state.first.second) .coverSize != abs(row - state.first.first) + 1) { return false; } } return true; } bool isValid(int x, int y) { return 0 <= x && x < n && 0 <= y && y < m; } void fix(int &x, int &y, int &dir) { if (isValid(x + DX[dir], y + DY[dir])) return; if (!x && !y) dir = 2; else if (!x && y == m - 1) dir = 3; else if (x == n - 1 && !y) dir = 1; else if (x == n - 1 && y == m - 1) dir = 0; else if (!x || x == n - 1) dir ^= 3; else dir ^= 1; } int main() { init(); scanf("%d%d", &n, &m); int x, y, dir; char dirStr[5]; scanf("%d%d%s", &x, &y, dirStr); x--; y--; parity = (x + y) & 1; dir = dirMap[dirStr]; fix(x, y, dir); sgt[0].init(n + m); sgt[1].init(n + m); long long res = 1; while (cover(x, y, dir)) { dirLst.push_back(make_pair(make_pair(x, y), dir)); pair<pair<int, int>, int> state = nextDir(x, y, dir); res += abs(x - state.first.first); x = state.first.first; y = state.first.second; dir = state.second; } if (!fullyCover()) { puts("-1"); } else { for (int o = ((int)(dirLst).size()) - 1; o >= 0; o--) { int x = dirLst[o].first.first, y = dirLst[o].first.second, dir = dirLst[o].second; uncover(x, y, dir); pair<pair<int, int>, int> state = nextDir(x, y, dir); int x0 = state.first.first, y0 = state.first.second; res -= abs(x - x0); if (cnt[dir & 1][dir & 1 ? x + y : x - y + m - 1]) continue; int l = dir & 1 ? x - y + m - 1 : x + y, r = dir & 1 ? x0 - y0 + m - 1 : x0 + y0; if (l > r) swap(l, r); Segment segment = sgt[dir & 1 ^ 1].calc(l, r); if (segment.coverSize == r - l + 1) continue; for (;; x0 -= DX[dir], y0 -= DY[dir]) { if (!sgt[dir & 1 ^ 1] .calc(dir & 1 ? x0 - y0 + m - 1 : x0 + y0) .coverSize) { res += abs(x - x0); break; } if (x0 == x && y0 == y) break; } break; } printf("%I64d\n", res); } 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 = 100005; int U[N], D[N], L[N], R[N]; int n, m, tot, cnt, xs, ys, ds, x, y, d; int sign[2] = {-1, 1}; long long ans; int visit(int x, int y) { int ret; if (x == 1) { ret = U[y]; U[y] = 1; } if (x == n) { ret = D[y]; D[y] = 1; } if (y == 1) { ret = L[x]; L[x] = 1; } if (y == m) { ret = R[x]; R[x] = 1; } return ret; } void getnext(int& x, int& y, int d) { int l = min(((d & 2) ? n - x : x - 1), ((d & 1) ? m - y : y - 1)); ans += l; x += sign[(d & 2) != 0] * l; y += sign[(d & 1) != 0] * l; } void correct(int x, int y, int& d) { if (x == 1) d |= 2; else if (x == n) d &= 1; if (y == 1) d |= 1; else if (y == m) d &= 2; } char s[111]; int main() { cin >> n >> m; ans = 1; tot = n + m - 2; cin >> xs >> ys >> s; ds = ((s[0] == 'D') << 1) | (s[1] == 'R'); correct(xs, ys, ds); x = xs; y = ys; d = ds; cnt += !visit(x, y); while (true) { getnext(x, y, d); correct(x, y, d); if ((cnt += !visit(x, y)) == tot) break; if (x == xs && y == ys && d == ds) break; } cout << (cnt == tot ? ans : -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; template <class F, class T> T convert(F a, int p = -1) { stringstream ss; if (p >= 0) ss << fixed << setprecision(p); ss << a; T r; ss >> r; return r; } template <class T> T gcd(T a, T b) { T r; while (b != 0) { r = a % b; a = b; b = r; } return a; } template <class T> T lcm(T a, T b) { return a / gcd(a, b) * b; } template <class T> T sqr(T x) { return x * x; } template <class T> T cube(T x) { return x * x * x; } template <class T> int getbit(T s, int i) { return (s >> i) & 1; } template <class T> T onbit(T s, int i) { return s | (T(1) << i); } template <class T> T offbit(T s, int i) { return s & (~(T(1) << i)); } template <class T> int cntbit(T s) { return s == 0 ? 0 : cntbit(s >> 1) + (s & 1); } const int bfsz = 1 << 16; char bf[bfsz + 5]; int rsz = 0; int ptr = 0; char gc() { if (rsz <= 0) { ptr = 0; rsz = (int)fread(bf, 1, bfsz, stdin); if (rsz <= 0) return EOF; } --rsz; return bf[ptr++]; } void ga(char &c) { c = EOF; while (!isalpha(c)) c = gc(); } int gs(char s[]) { int l = 0; char c = gc(); while (isspace(c)) c = gc(); while (c != EOF && !isspace(c)) { s[l++] = c; c = gc(); } s[l] = '\0'; return l; } template <class T> bool gi(T &v) { v = 0; char c = gc(); while (c != EOF && c != '-' && !isdigit(c)) c = gc(); if (c == EOF) return false; bool neg = c == '-'; if (neg) c = gc(); while (isdigit(c)) { v = v * 10 + c - '0'; c = gc(); } if (neg) v = -v; return true; } const double PI = acos(-1.0); const double eps = 1e-9; const int dr[] = {-1, 0, +1, 0}; const int dc[] = {0, +1, 0, -1}; const int inf = (int)1e9 + 5; const long long linf = (long long)1e17 + 5; const long long mod = 1000000007; int n, m; int r, c, h; map<pair<int, int>, int> M; map<pair<pair<int, int>, int>, int> M1; long long res = 0; string str[4] = {"UL", "UR", "DR", "DL"}; string s; int main() { cin >> n >> m; cin >> r >> c >> s; for (int i = 0; i < (4); ++i) if (str[i].compare(s) == 0) { h = i; break; } int rr, cc, run = 1; ; M.clear(); res++; M[make_pair(r, c)] = 1; M1[make_pair(make_pair(r, c), h)] = 1; while (run < n + m - 2) { if (h == 0) { rr = r - c + 1; cc = 1; if (rr < 1) { cc = cc - rr + 1; rr = 1; } if (rr == 1 && cc == 1) h = 2; else if (rr == 1) h = 3; else if (cc == 1) h = 1; } else if (h == 1) { rr = r - m + c; cc = m; if (rr < 1) { cc = cc + rr - 1; rr = 1; } if (rr == 1 && cc == m) h = 3; else if (rr == 1) h = 2; else if (cc == m) h = 0; } else if (h == 2) { rr = r + m - c; cc = m; if (rr > n) { cc = cc - rr + n; rr = n; } if (rr == n && cc == m) h = 0; else if (rr == n) h = 1; else if (cc == m) h = 3; } else { rr = r + c - 1; cc = 1; if (rr > n) { cc = cc + rr - n; rr = n; } if (rr == n && cc == 1) h = 1; else if (rr == n) h = 0; else if (cc == 1) h = 2; } if (M1[make_pair(make_pair(rr, cc), h)]) break; if (!M[make_pair(rr, cc)]) run++; M[make_pair(rr, cc)] = 1; M1[make_pair(make_pair(rr, cc), h)] = 1; res += abs(r - rr); r = rr; c = cc; } if (run < n + m - 2) { cout << -1; return 0; } cout << res; 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; int mod(int a) { return a > 0 ? a : -a; } void save(int x, int y) { if (!vis.count(pair<int, int>(x, y))) { vis.insert(pair<int, int>(x, y)); if (x == 1 || x == n || y == 1 || y == m) 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 + 2 * 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; int main() { int n = 0, m = 0; cin >> n >> m; vector<vector<int>> v(n + 1); for (int i = 1; i < n + 1; ++i) { if ((i == 1) || (i == n)) v[i].resize(m + 1); else v[i].resize(2); } int fx = 0, fy = 0; cin >> fx >> fy; int x = fx, y = fy, x0 = 0, y0 = 0; int vert, hori; for (int i = 0; i < 2; ++i) { char c; cin >> c; switch (c) { case 'U': vert = -1; ; break; case 'D': vert = 1; break; case 'L': hori = -1; break; case 'R': hori = 1; break; } } int h0 = hori, v0 = vert; long long sum = 1; int max = m + n - 2; int time = 1; v[x][((x == 1) || (x == n)) ? y : y / m] = 1; while (true) { int dx = 0, dy = 0; if (y == 1) hori = 1; if (y == m) hori = -1; if (x == 1) vert = 1; if (x == n) vert = -1; dy = (hori == 1) ? (m - y) : (y - 1); dx = (vert == 1) ? (n - x) : (x - 1); int d = (dx < dy) ? dx : dy; x += d * vert; y += d * hori; sum += d; x0 = x; y0 = ((x == 1) || (x == n)) ? y : y / m; if (v[x0][y0] != 1) { ++time; v[x0][y0] = 1; } if ((x == fx) && (y == fy)) { if (((x == 1) || (x == n)) && (hori == h0)) break; if (((y == 1) || (y == m)) && (vert == v0)) break; if (((x == 1) || (x == n)) && ((y == 1) || (y == m))) break; } if (time == max) break; } if (time == max) cout << sum; else cout << -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, x, y, cnt; long long ans; string str; map<pair<int, int>, int> vis; int main() { scanf("%d", &n); ; scanf("%d", &m); ; scanf("%d", &x); ; scanf("%d", &y); ; cin >> str; int dx, dy; (str[0] == 'U') ? dx = -1 : dx = 1; (str[1] == 'L') ? dy = -1 : dy = 1; cnt = 0; int tim = 0; if (x == 1 || x == n || y == 1 || y == m) cnt++, vis[make_pair(x, y)] = 1; while (cnt != n + m - 2) { if (++tim >= 500000) { puts("-1"); return 0; } int tx, ty; if (dx == 1) tx = abs(n - x); else tx = abs(1 - x); if (dy == 1) ty = abs(m - y); else ty = abs(1 - y); int tmp = min(tx, ty); x += dx * tmp; y += dy * tmp; ans += tmp; if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; if (y == m) dy = -1; if (!vis[make_pair(x, y)]) cnt++, vis[make_pair(x, y)] = 1; } cout << ans + 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 N = 1e5 + 7; const int INF = 1e9 + 7; const int dx[] = {-1, -1, 1, 1}; const int dy[] = {-1, 1, -1, 1}; int n, m, xs, ys, ds; char str[10]; long long TS, ts[2][N][4], st[2][N][4]; bool isEnd(int x, int y, int d) { if (x == 1 || x == n) { if (~ts[x == n][y][d]) return true; ts[x == n][y][d] = TS; } else { if (~st[y == m][x][d]) return true; st[y == m][x][d] = TS; } return false; } bool up[N], dw[N]; void upd(long long &x, long long y) { if (x == -1) x = y; else if (~y) x = min(x, y); } long long gao(int n, int m, long long ts[2][N][4]) { long long ret = 0; for (int i = (1); i < (m + 1); ++i) { long long uts = -1, dts = -1; for (int j = (0); j < (4); ++j) upd(uts, ts[0][i][j]), upd(dts, ts[1][i][j]); up[i] = ~uts, dw[i] = ~dts; if ((up[i] ^ dw[i]) != !(n & 1)) return -1; if (i > 1 && (up[i - 1] == up[i] || dw[i - 1] == dw[i])) return -1; if (~uts) ret = max(ret, uts); if (~dts) ret = max(ret, dts); } return ret; } long long solve(int x, int y, int d) { memset(ts, -1, sizeof(ts)); memset(st, -1, sizeof(st)); TS = 0; while (!isEnd(x, y, d)) { if ((x == 1 && dx[d] < 0) || (x == n && dx[d] > 0)) d = (d + 2) & 3; if ((y == 1 && dy[d] < 0) || (y == m && dy[d] > 0)) d ^= 1; int t = min(dx[d] < 0 ? x - 1 : n - x, dy[d] < 0 ? y - 1 : m - y); TS += t, x += dx[d] * t, y += dy[d] * t; } long long ret = max(gao(n, m, ts), gao(m, n, st)); return ret; } int main() { scanf("%d%d%d%d %s", &n, &m, &xs, &ys, str); if (strcmp(str, "UL") == 0) { ds = 0; } else if (strcmp(str, "UR") == 0) { ds = 1; } else if (strcmp(str, "DL") == 0) { ds = 2; } else { ds = 3; } long long ans = solve(xs, ys, ds); if (~ans) ++ans; printf("%lld", 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 run(int casenr) { int h, w, x, y, dx, dy; char sdir[10]; scanf("%d%d%d%d%s", &h, &w, &x, &y, sdir); --x, --y; if (strcmp(sdir, "UL") == 0) { dx = -1; dy = -1; } else if (strcmp(sdir, "UR") == 0) { dx = -1; dy = +1; } else if (strcmp(sdir, "DL") == 0) { dx = +1; dy = -1; } else if (strcmp(sdir, "DR") == 0) { dx = +1; dy = +1; } else assert(false); vector<int> cnt1(h + w - 1, 0), cnt2(h + w - 1, 0); int d1, d1l, d1r, d1cnt = 0, d1need, d2, d2l, d2r, d2cnt = 0, d2need; if ((h - 1) % 2 == (x + y) % 2) { d1 = 0; d1l = d1r = h - 1; d1need = 1; } else { d1 = 1; d1l = h - 2; d1r = h; d1need = 2; } if ((w - 1) % 2 == (x + y) % 2) { d2 = w - 1 + h - 1; d2l = d2r = w - 1; d2need = 1; } else { d2 = w - 2 + h - 1; d2l = w - 2; d2r = w; d2need = 2; } long long ret = 1; while (d1 <= h - 1 || d2 >= h - 1) { int nx = x + dx, ny = y + dy; if (nx < 0 || nx >= h) dx = -dx; if (ny < 0 || ny >= w) dy = -dy; int xcnt = dx < 0 ? x : h - 1 - x, ycnt = dy < 0 ? y : w - 1 - y, cnt = min(xcnt, ycnt); assert(cnt >= 1); nx = x + cnt * dx, ny = y + cnt * dy; ret += cnt; if ((x + y) == (nx + ny)) { ++cnt2[x + y]; if (cnt2[x + y] >= 3) { printf("-1\n"); return; } if (cnt2[x + y] == 1) { if (d1l <= x + y && x + y <= d1r) ++d1cnt; if (d2l <= x + y && x + y <= d2r) ++d2cnt; } } else { ++cnt1[y - x + h - 1]; if (cnt1[y - x + h - 1] >= 3) { printf("-1\n"); return; } } while (d1 <= h - 1 && (cnt1[d1] > 0 || d1cnt >= d1need)) { d1 += 2; d1need += 2; d1l -= 2; int od1r = d1r; d1r += 2; if (d1need > w) { d1need = w; d1r = h - 1 + w - 1 - d1 + w - 1; } if (d1l >= 0 && cnt2[d1l] > 0) ++d1cnt; if (d1r > od1r && d1r < h + w - 1 && cnt2[d1r] > 0) ++d1cnt; if (d1r < od1r && od1r < h + w - 1 && cnt2[od1r] > 0) --d1cnt; } while (d2 >= h - 1 && (cnt1[d2] > 0 || d2cnt >= d2need)) { d2 -= 2; d2need += 2; d2l -= 2; int od2r = d2r; d2r += 2; if (d2need > h) { d2need = h; d2r = h - 1 + d2; } if (d2l >= 0 && cnt2[d2l] > 0) ++d2cnt; if (d2r > od2r && d2r < h + w - 1 && cnt2[d2r] > 0) ++d2cnt; if (d2r < od2r && od2r < h + w - 1 && cnt2[od2r] > 0) --d2cnt; } x = nx; y = ny; } while (cnt1[y - x + h - 1] + cnt2[x + y] > 1) { --ret; x -= dx; y -= dy; } cout << ret << endl; } int main() { run(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; map<int, int> A[110000]; int n, m, now, gox, goy, k1, k2; char ch[10]; int main() { scanf("%d%d", &n, &m); scanf("%d%d", &k1, &k2); scanf("%s", ch + 1); gox = 1; goy = 1; if (ch[1] == 'U') gox = -1; if (ch[2] == 'L') goy = -1; int rem = n + m - 2, ti = 0; long long ans = 1; if (k1 == 1 || k1 == n || k2 == 1 || k2 == m) { A[k1][k2] = 1; rem--; } while (1) { ti++; if (ti >= 500000) { cout << -1 << endl; return 0; } int dis = 1e9; if (gox == 1) dis = min(dis, n - k1); else dis = min(dis, k1 - 1); if (goy == 1) dis = min(dis, m - k2); else dis = min(dis, k2 - 1); k1 += gox * dis; k2 += goy * dis; ans += dis; if (k1 == 1) gox = 1; if (k1 == n) gox = -1; if (k2 == 1) goy = 1; if (k2 == m) goy = -1; if (A[k1][k2] == 0) { rem--; A[k1][k2] = 1; } if (rem == 0) { 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 main() { int n, m; int xs, ys; scanf("%d %d", &n, &m); char s[5]; scanf("%d %d %s", &xs, &ys, s); int dx = -1, dy = -1; if (s[0] == 'D') dx = 1; if (s[1] == 'R') dy = 1; int x = xs, y = ys; if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; if (y == m) dy = -1; int dxs = dx, dys = dy; set<pair<int, int> > se; se.insert({x, y}); long long ans = 1; while (se.size() < n + m - 2) { int moves = 1000000; if (dx == 1) moves = min(moves, n - x); else moves = min(moves, x - 1); if (dy == 1) moves = min(moves, m - y); else moves = min(moves, y - 1); x += moves * dx, y += moves * dy; if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; if (y == m) dy = -1; ans += moves; if (x == xs && y == ys && dx == dxs && dy == dys) { puts("-1"); return 0; } se.insert({x, y}); } printf("%I64d\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, sx, sy, dx, dy, NumBorder; long long ans; set<pair<int, int> > memory; void prepare() { char ts[5]; scanf("%d %d", &n, &m); scanf("%d %d %s", &sx, &sy, ts); if (ts[0] == 'D') dx = 1; else dx = -1; if (ts[1] == 'R') dy = 1; else dy = -1; NumBorder = 0; for (int i = 1; i <= m; ++i) { if ((1 + i) % 2 == (sx + sy) % 2) ++NumBorder; if (n > 1 && (n + i) % 2 == (sx + sy) % 2) ++NumBorder; } for (int i = 2; i < n; ++i) { if ((1 + i) % 2 == (sx + sy) % 2) ++NumBorder; if (m > 1 && (m + i) % 2 == (sx + sy) % 2) ++NumBorder; } } bool isfull() { return memory.size() == NumBorder; } void remember() { memory.insert(make_pair(sx, sy)); } bool inmap(const int tx, const int ty) { return tx >= 1 && tx <= n && ty >= 1 && ty <= m; } void gonext() { int l = 0, r = n + m, mid; while (r > l) { mid = (l + r) >> 1; if (inmap(sx + dx * mid, sy + dy * mid)) l = mid + 1; else r = mid; } int step = l - 1; ans += step; sx += step * dx; sy += step * dy; if (sx == 1) dx = 1; if (sx == n) dx = -1; if (sy == 1) dy = 1; if (sy == m) dy = -1; remember(); } int main() { prepare(); remember(); ans = 1; int BAR = (n + m) * 4; while (BAR--) { if (isfull()) { cout << ans << endl; return 0; } gonext(); } 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, i, j, k, x, y, dx, dy, l1, l2, l; long long ans; char s[5]; set<pair<int, int> > Hash; 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; for (i = n + n + m + m; i; --i) { Hash.insert(make_pair(x, y)); if (Hash.size() == n + m - 2) { printf("%I64d\n", ans + 1); return 0; } if (dx == -1) l1 = x - 1; else l1 = n - x; if (dy == -1) l2 = y - 1; else l2 = m - y; l = min(l1, l2); x += dx * l; y += dy * l; ans += l; if (l1 == l) dx *= -1; if (l2 == l) dy *= -1; } printf("-1\n"); }
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 n, m; map<long long, bool> already; int mask(int x, int y) { return x * 1000000LL + y; } int MAIN() { while (cin >> n >> m) { already.clear(); long long x, y; cin >> x >> y; bool eq = (x % 2 == y % 2); int dx, dy; string dir; cin >> dir; if (dir[0] == 'U') dx = -1; else dx = 1; if (dir[1] == 'L') dy = -1; else dy = 1; long long ans = 0; int need = 0; for (int i = 1; i <= m; i++) { long long t = mask(1, i); if (already.count(t) == false && (1 % 2 == i % 2) == eq) { already[t] = true; need++; } t = mask(n, i); if (already.count(t) == false && (n % 2 == i % 2) == eq) { already[t] = true; need++; } } for (int i = 1; i <= n; i++) { long long t = mask(i, 1); if (already.count(t) == false && (i % 2 == 1 % 2) == eq) { already[t] = true; need++; } t = mask(i, m); if (already.count(t) == false && (i % 2 == m % 2) == eq) { already[t] = true; need++; } } already.clear(); ans++; if (x == 1 || x == n || y == 1 || y == m) if ((x % 2 == y % 2) == eq) { long long t = mask(x, y); already[t] = true; need--; } while (ans <= (n * m * 5)) { if (need == 0) break; long long minMov = 10000000; if (dx == 1) minMov = min(minMov, n - x); else minMov = min(minMov, x - 1); if (dy == 1) minMov = min(minMov, m - y); else minMov = min(minMov, y - 1); ans += minMov; x += minMov * dx; y += minMov * dy; if (x + dx <= 0 || x + dx > n) dx *= -1; if (y + dy <= 0 || y + dy > m) dy *= -1; long long t = mask(x, y); if (already.count(t) == false) { need--; already[t] = true; if (need == 0) break; } } if (need > 0) cout << -1 << endl; else cout << ans << endl; } return 0; } int main() { ios ::sync_with_stdio(false); cout << fixed << setprecision(16); return MAIN(); }
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 MAX_N = 100000; const int D[4][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; set<pair<int, int> > s; set<pair<pair<int, int>, int> > vis; char dir[10]; int sx, sy, h, w, d, tar; inline void update(int& a, int b) { if (b < a) a = b; } int main() { scanf("%d%d%d%d%s", &h, &w, &sx, &sy, dir); tar = ((h + w) * 2 - 4) >> 1; if (dir[0] == 'U' && dir[1] == 'L') d = 3; else if (dir[0] == 'U' && dir[1] == 'R') d = 2; else if (dir[0] == 'D' && dir[1] == 'L') d = 1; else d = 0; --tar; s.insert(make_pair(sx, sy)); vis.insert(make_pair(make_pair(sx, sy), d)); long long ans = 1; pair<int, int> p1; pair<pair<int, int>, int> p2; while (tar > 0) { if ((D[d][0] == 1 && sx == h) || (D[d][0] == -1 && sx == 1)) d ^= 2; if ((D[d][1] == 1 && sy == w) || (D[d][1] == -1 && sy == 1)) d ^= 1; int g = 0x3f3f3f3f; if (D[d][0] == 1) update(g, h - sx); else update(g, sx - 1); if (D[d][1] == 1) update(g, w - sy); else update(g, sy - 1); ans += g; sx += D[d][0] * g; sy += D[d][1] * g; p1 = make_pair(sx, sy); if (s.find(p1) == s.end()) { --tar; s.insert(p1); } p2 = make_pair(p1, d); if (vis.find(p2) != vis.end()) { printf("-1\n"); return 0; } else vis.insert(p2); } printf( "%I64d" "\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; const int dx[4] = {1, 1, -1, -1}; const int dy[4] = {1, -1, -1, 1}; int sx, sy, n, m, sd; string sd_str; set<pair<pair<int, int>, int> > s; set<pair<int, int> > ps; long long ans = 0; inline bool on_edge(int x, int y) { return x == 1 || x == n || y == 1 || y == m; } inline pair<int, int> move(const pair<int, int> &pt, int dir) { int delta_x, delta_y; if (dir == 0 || dir == 1) delta_x = n - pt.first; else delta_x = pt.first - 1; if (dir == 0 || dir == 3) delta_y = m - pt.second; else delta_y = pt.second - 1; int delta = min(delta_x, delta_y); ans += delta; return make_pair(pt.first + dx[dir] * delta, pt.second + dy[dir] * delta); } int main() { cin >> n >> m >> sx >> sy >> sd_str; pair<int, int> now = make_pair(sx, sy); if (sd_str == "DR") sd = 0; else if (sd_str == "DL") sd = 1; else if (sd_str == "UL") sd = 2; else sd = 3; s.insert(make_pair(now, sd)); ps.insert(now); ans = 1; while (1) { now = move(now, sd); if (now.first == 1 || now.first == n) { if (sd == 0 && now.first == n) sd = 3; else if (sd == 3 && now.first == 1) sd = 0; else if (sd == 1 && now.first == n) sd = 2; else if (sd == 2 && now.first == 1) sd = 1; } if (now.second == 1 || now.second == m) { if (sd == 0 && now.second == m) sd = 1; else if (sd == 1 && now.second == 1) sd = 0; else if (sd == 3 && now.second == m) sd = 2; else if (sd == 2 && now.second == 1) sd = 3; } if (!ps.count(now)) { ps.insert(now); } if (ps.size() == m + n - 2) break; if (s.count(make_pair(now, sd))) { ans = -1; break; } s.insert(make_pair(now, sd)); } 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 dx[] = {1, 1, -1, -1}; int dy[] = {1, -1, 1, -1}; int main() { int n, m; scanf("%d%d", &n, &m); int x, y; char s[4]; scanf("%d%d%s", &x, &y, s); int d; int row[2][100010], line[2][100010]; if (s[0] == 'D' && s[1] == 'R') d = 0; if (s[0] == 'D' && s[1] == 'L') d = 1; if (s[0] == 'U' && s[1] == 'R') d = 2; if (s[0] == 'U' && s[1] == 'L') d = 3; int need = 0; memset(row, 0, sizeof(row)); memset(line, 0, sizeof(line)); for (int i = 1; i <= m; i++) { if ((i + 1) % 2 == (x + y) % 2) need++; if ((i + n) % 2 == (x + y) % 2) need++; } for (int i = 1; i <= n; i++) { if ((i + 1) % 2 == (x + y) % 2) need++; if ((i + m) % 2 == (x + y) % 2) need++; } if ((1 + 1) % 2 == (x + y) % 2) need--; if ((1 + m) % 2 == (x + y) % 2) need--; if ((n + 1) % 2 == (x + y) % 2) need--; if ((n + m) % 2 == (x + y) % 2) need--; int now = 0; long long ans = 1; if (x == 1 || x == n || y == 1 || y == m) { now += 1; if (d == 0) { if (x == n) { if (y == m) d = 3; else d = 2; } else if (y == m) d = 1; } if (d == 1) { if (x == n) { if (y == 1) d = 2; else d = 3; } else if (y == 1) d = 0; } if (d == 2) { if (x == 1) { if (y == m) d = 1; else d = 0; } else if (y == m) d = 3; } if (d == 3) { if (x == 1) { if (y == 1) d = 0; else d = 1; } else if (y == 1) d = 2; } } if (x == 1) row[0][y] = 1; if (x == n) row[1][y] = 1; if (y == 1) line[0][x] = 1; if (y == m) line[1][x] = 1; bool flag = true; while (now < need) { int dn; if (d == 0) dn = ((n - x) < (m - y) ? (n - x) : (m - y)); if (d == 1) dn = ((n - x) < (y - 1) ? (n - x) : (y - 1)); if (d == 2) dn = ((x - 1) < (m - y) ? (x - 1) : (m - y)); if (d == 3) dn = ((x - 1) < (y - 1) ? (x - 1) : (y - 1)); ans += dn; int nx = x + dn * dx[d]; int ny = y + dn * dy[d]; int nd; if (d == 0) { if (nx == n) { if (row[1][ny] == 0) now++; row[1][ny]++; if (row[1][ny] > 2) flag = false; if (ny == m) nd = 3; else nd = 2; } else if (ny == m) { if (line[1][nx] == 0) now++; line[1][nx]++; if (line[1][nx] > 2) flag = false; nd = 1; } } if (d == 1) { if (nx == n) { if (row[1][ny] == 0) now++; row[1][ny]++; if (row[1][ny] > 2) flag = false; if (ny == 1) nd = 2; else nd = 3; } else if (ny == 1) { if (line[0][nx] == 0) now++; line[0][nx]++; if (line[0][nx] > 2) flag = false; nd = 0; } } if (d == 2) { if (nx == 1) { if (row[0][ny] == 0) now++; row[0][ny]++; if (row[0][ny] > 2) flag = false; if (ny == m) nd = 1; else nd = 0; } else if (ny == m) { if (line[1][nx] == 0) now++; line[1][nx]++; if (line[1][nx] > 2) flag = false; nd = 3; } } if (d == 3) { if (nx == 1) { if (row[0][ny] == 0) now++; row[0][ny]++; if (row[0][ny] > 2) flag = false; if (ny == 1) nd = 0; else nd = 1; } else if (ny == 1) { if (line[0][nx] == 0) now++; line[0][nx]++; if (line[0][nx] > 2) flag = false; nd = 2; } } x = nx; y = ny; d = nd; if (!flag) break; } if (!flag) ans = -1; printf("%I64d\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> template <typename T> void Read(T &x) { x = 0; int f = 1; char c; while ((c = std::getchar()) < '0' || c > '9') if (c == '-') f = -1; x = c - '0'; while ((c = std::getchar()) >= '0' && c <= '9') x = x * 10 + c - '0'; x *= f; } template <typename T, typename... Args> void Read(T &x, Args &...args) { Read(x); Read(args...); } template <typename T> void checkmax(T &x, T y) { if (x < y) x = y; } template <typename T> void checkmin(T &x, T y) { if (x > y) x = y; } int n, m, x, y, d1, d2; char s[10]; std::map<std::pair<int, int>, int> vis; int main(int argc, char const *argv[]) { Read(n, m, x, y); std::size_t tot = n + m - 2; std::scanf("%s", s); d1 = s[0] == 'D'; d2 = s[1] == 'R'; if (x == 1 || x == n || y == 1 || y == m) vis[{x, y}] = 1; long long ans = 0LL; while (vis.size() < tot) { int dis = std::min(d1 ? n - x : x - 1, d2 ? m - y : y - 1); d1 ? x += dis : x -= dis; d2 ? y += dis : y -= dis; if ((x == 1 && !d1) || (x == n && d1)) d1 ^= 1; if ((y == 1 && !d2) || (y == m && d2)) d2 ^= 1; ans += dis; if (vis[{x, y}] == 2) { std::printf("-1"); return 0; } if (dis) vis[{x, y}]++; } std::printf("%lld", 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 tope = 100001; int n, m; int vistoi[2][tope][2][2]; int vistoj[2][tope][2][2]; void rebota(int i, int j, int &di, int &dj) { if (i == 0) { if (di == 0) di = 1; } else if (i == n - 1) { if (di == 1) di = 0; } if (j == 0) { if (dj == 0) dj = 1; } else if (j == m - 1) { if (dj == 1) dj = 0; } } bool sehavisto(int i, int j, int di, int dj) { return (i == 0 and vistoi[0][j][di][dj]) or (i == n - 1 and vistoi[1][j][di][dj]) or (j == 0 and vistoj[0][i][di][dj]) or (j == m - 1 and vistoj[1][i][di][dj]); } void marcavisto(int i, int j, int di, int dj) { if (i == 0) vistoi[0][j][di][dj] = 1; if (i == n - 1) vistoi[1][j][di][dj] = 1; if (j == 0) vistoj[0][i][di][dj] = 1; if (j == m - 1) vistoj[1][i][di][dj] = 1; } int main() { cin >> n >> m; int i, j, di, dj; string s; cin >> i >> j >> s; i--; j--; if (s == "UL") { di = 0; dj = 0; } else if (s == "UR") { di = 0; dj = 1; } else if (s == "DL") { di = 1; dj = 0; } else if (s == "DR") { di = 1; dj = 1; } rebota(i, j, di, dj); long long int coste = 1, costeant; int puntas = 0; while (not sehavisto(i, j, di, dj)) { marcavisto(i, j, di, dj); puntas += (i == 0 and j == 0) or (i == n - 1 and j == 0) or (i == 0 and j == m - 1) or (i == n - 1 and j == m - 1); if (puntas == 2) break; costeant = coste; if (di == 0 and dj == 0) { if (i >= j) { coste += j; i -= j; j = 0; } else { coste += i; j -= i; i = 0; } } else if (di == 0 and dj == 1) { if (i >= m - 1 - j) { coste += m - 1 - j; i -= (m - 1 - j); j = m - 1; } else { coste += i; j += i; i = 0; } } else if (di == 1 and dj == 0) { if (n - 1 - i >= j) { coste += j; i += j; j = 0; } else { coste += n - 1 - i; j -= (n - 1 - i); i = n - 1; } } else if (di == 1 and dj == 1) { if (n - 1 - i >= m - 1 - j) { coste += m - 1 - j; i += (m - 1 - j); j = m - 1; } else { coste += n - 1 - i; j += (n - 1 - i); i = n - 1; } } rebota(i, j, di, dj); } if (puntas != 2) coste = costeant; bool error = false; int paridad = 1 - vistoi[0][0][1][1]; for (int j = paridad; j < m and not error; j += 2) error = not(vistoi[0][j][1][0] or vistoi[0][j][1][1]); for (int i = paridad; i < n and not error; i += 2) error = not(vistoj[0][i][0][1] or vistoj[0][i][1][1]); int paridadi = paridad; if (n % 2 == 0) paridadi = 1 - paridad; for (int j = paridadi; j < m and not error; j += 2) error = not(vistoi[1][j][0][0] or vistoi[1][j][0][1]); int paridadj = paridad; if (m % 2 == 0) paridadj = 1 - paridad; for (int i = paridadj; i < n and not error; i += 2) error = not(vistoj[1][i][0][0] or vistoj[1][i][1][0]); if (error) cout << -1 << endl; else { cout << coste << 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; struct State { int x, y, vec; bool operator<(const State &a) const { if (x != a.x) return x < a.x; else if (y != a.y) return y < a.y; else return vec < a.vec; } }; int main() { int n, m; scanf("%d%d", &n, &m); int x, y; scanf("%d%d", &x, &y); string s; cin >> s; int vec; if (s == "UL") vec = 0; else if (s == "UR") vec = 1; else if (s == "DL") vec = 2; else vec = 3; set<State> st, udst; State now, udnow; now.x = x; now.y = y; now.vec = vec; udnow.x = x; udnow.y = y; udnow.vec = 0; long long ans = 0; while (1) { int &vec = now.vec; if (st.find(now) != st.end()) break; st.insert(now); udst.insert(udnow); if (udst.size() == n + m - 2) break; int step = 0; if (now.vec == 0) { step = min(now.x - 1, now.y - 1); now.x -= step; now.y -= step; if (now.x == now.y) vec = 3; else if (now.x < now.y) vec = 2; else vec = 1; } else if (now.vec == 1) { step = min(now.x - 1, m - now.y); now.x -= step; now.y += step; if (now.x == m - now.y + 1) vec = 2; else if (now.x < m - now.y + 1) vec = 3; else vec = 0; } else if (now.vec == 2) { step = min(n - now.x, now.y - 1); now.x += step; now.y -= step; if (n - now.x + 1 == now.y) vec = 1; else if (n - now.x + 1 < now.y) vec = 0; else vec = 3; } else { step = min(n - now.x, m - now.y); now.x += step; now.y += step; if (n - now.x == m - now.y) vec = 0; else if (n - now.x < m - now.y) vec = 1; else vec = 2; } ans += step; udnow = now; udnow.vec = 0; } if (udst.size() != n + m - 2) ans = -1; else ++ans; printf("%I64d\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; const long long mod = 1e9 + 7; const long long maxn = 1e6 + 7; inline long long read() { long long res = 0, tmp = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') tmp = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') res = (res << 1) + (res << 3) + (ch ^ 48), ch = getchar(); return res * tmp; } inline void write(long long x) { if (x < 0) putchar('-'), x = -x; if (x > 9) write(x / 10); putchar(x % 10 + '0'); } void fre() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); } long long max(long long a, long long b) { return a > b ? a : b; } long long min(long long a, long long b) { return a < b ? a : b; } void hour() { cerr << "θΏθ‘Œζ—Άι—΄οΌš" << 1.0 * clock() / CLOCKS_PER_SEC << "s" << endl; } long long a[maxn][4], l[4], n, m, x, y, t, r, ans = 1; string s; int main() { n = read(); m = read(); x = read(); y = read(); if (n * m * x * y % 2 == 1) return puts("-1"); cin >> s; t = (s == "UL" ? 1 : (s == "UR" ? 2 : (s == "DL" ? 3 : 4))); if (x == n) a[y][0] = 1, l[0]++; if (y == m) a[x][1] = 1, l[1]++; if (x == 1) a[y][2] = 1, l[2]++; if (y == 1) a[x][3] = 1, l[3]++; while (++r < maxn) { if (l[0] + l[1] + l[2] + l[3] == n + m - (n * m % 2) * 2) { write(ans); return 0; } if (t == 1) { if (x - 1 > y - 1) { ans += y - 1; x -= (y - 1); y = 1; } else { ans += x - 1; y -= (x - 1); x = 1; } if (x == 1 && y == 1) { if (a[y][2] == 0) a[y][2] = 1, l[2]++; if (a[x][3] == 0) a[x][3] = 1, l[3]++; if (a[y + 1][2] == a[y][2] || a[y - 1][2] == a[y][2] || a[x + 1][3] == a[x][3] || a[x - 1][3] == a[x][3]) return puts("-1"); t = 4; } else if (x == 1) { if (a[y][2] == 0) a[y][2] = 1, l[2]++; if (a[y + 1][2] == a[y][2] || a[y - 1][2] == a[y][2]) return puts("-1"); t = 3; } else { if (a[x][3] == 0) a[x][3] = 1, l[3]++; if (a[x + 1][3] == a[x][3] || a[x - 1][3] == a[x][3]) return puts("-1"); t = 2; } } else if (t == 2) { if (x - 1 > m - y) { ans += m - y; x -= (m - y); y = m; } else { ans += x - 1; y += (x - 1); x = 1; } if (x == 1 && y == m) { if (a[y][2] == 0) a[y][2] = 1, l[2]++; if (a[x][1] == 0) a[x][1] = 1, l[1]++; if (a[y + 1][2] == a[y][2] || a[y - 1][2] == a[y][2] || a[x + 1][1] == a[x][1] || a[x - 1][1] == a[x][1]) return puts("-1"); t = 3; } else if (x == 1) { if (a[y][2] == 0) a[y][2] = 1, l[2]++; if (a[y + 1][2] == a[y][2] || a[y - 1][2] == a[y][2]) return puts("-1"); t = 4; } else { if (a[x][1] == 0) a[x][1] = 1, l[1]++; if (a[x + 1][1] == a[x][1] || a[x - 1][1] == a[x][1]) return puts("-1"); t = 1; } } else if (t == 3) { if (n - x > y - 1) { ans += y - 1; x += (y - 1); y = 1; } else { ans += n - x; y -= (n - x); x = n; } if (x == n && y == 1) { if (a[y][0] == 0) a[y][0] = 1, l[0]++; if (a[x][3] == 0) a[x][3] = 1, l[3]++; if (a[y + 1][0] == a[y][0] || a[y - 1][0] == a[y][0] || a[x + 1][3] == a[x][3] || a[x - 1][3] == a[x][3]) return puts("-1"); t = 2; } else if (x == n) { if (a[y][0] == 0) a[y][0] = 1, l[0]++; if (a[y + 1][0] == a[y][0] || a[y - 1][0] == a[y][0]) return puts("-1"); t = 1; } else { if (a[x][3] == 0) a[x][3] = 1, l[3]++; if (a[x + 1][3] == a[x][3] || a[x - 1][3] == a[x][3]) return puts("-1"); t = 4; } } else if (t == 4) { if (n - x > m - y) { ans += m - y; x += (m - y); y = m; } else { ans += n - x; y += (n - x); x = n; } if (x == n && y == m) { if (a[y][0] == 0) a[y][0] = 1, l[0]++; if (a[x][1] == 0) a[x][1] = 1, l[1]++; if (a[y + 1][0] == a[y][0] || a[y - 1][0] == a[y][0] || a[x + 1][1] == a[x][1] || a[x - 1][1] == a[x][1]) return puts("-1"); t = 1; } else if (x == n) { if (a[y][0] == 0) a[y][0] = 1, l[0]++; if (a[y + 1][0] == a[y][0] || a[y - 1][0] == a[y][0]) return puts("-1"); t = 2; } else { if (a[x][1] == 0) a[x][1] = 1, l[1]++; if (a[x + 1][1] == a[x][1] || a[x - 1][1] == a[x][1]) return puts("-1"); t = 3; } } } 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
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class Count { static Map<String, Integer> dirs = new HashMap<String, Integer>(); static int[][] d = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}}; FastScanner in; PrintWriter out; int n, m, x, y; long ans; public static void main(String[] args) { new Count().run(); } void solve() { n = in.nextInt(); m = in.nextInt(); x = in.nextInt() - 1; y = in.nextInt() - 1; dirs.put("UL", 0); dirs.put("UR", 1); dirs.put("DL", 2); dirs.put("DR", 3); boolean[][][] hor, ver; boolean[][] washor, wasver; hor = new boolean[m][2][4]; ver = new boolean[n][2][4]; washor = new boolean[m][2]; wasver = new boolean[n][2]; long remwas = (m + n) - 2; String dir = in.next(); ans = 1; int curDirection = dirs.get(dir); while (true) { curDirection = getCorrectDir(x, y, curDirection); int oldx = x, oldy = y; if (x == 0) { if (!washor[y][0]) { washor[y][0] = true; remwas--; } } if (x == n - 1) { if (!washor[y][1]) { washor[y][1] = true; remwas--; } } if (y == 0 && x != 0 && x != n - 1) { if (!wasver[x][0]) { wasver[x][0] = true; remwas--; } } if (y == m - 1 && x != 0 && x != n - 1) { if (!wasver[x][1]) { wasver[x][1] = true; remwas--; } } if (remwas == 0) { out.print(ans); return; } if (curDirection == 0) { int val = Math.min(x, y); x -= val; y -= val; if (oldx == n - 1) { if (hor[oldy][1][curDirection]) { fail(); return; } hor[oldy][1][curDirection] = true; } if (oldy == m - 1) { if (ver[oldx][1][curDirection]) { fail(); return; } ver[oldx][1][curDirection] = true; } ans += val; } if (curDirection == 1) { int val = Math.min(x, m - 1 - y); x -= val; y += val; if (oldx == n - 1) { if (hor[oldy][1][curDirection]) { fail(); return; } hor[oldy][1][curDirection] = true; } if (oldy == 0) { if (ver[oldx][0][curDirection]) { fail(); return; } ver[oldx][0][curDirection] = true; } ans += val; } if (curDirection == 2) { int val = Math.min(n - 1 - x, y); ; x += val; y -= val; if (oldx == 0) { if (hor[oldy][0][curDirection]) { fail(); return; } hor[oldy][0][curDirection] = true; } if (oldy == m - 1) { if (ver[oldx][1][curDirection]) { fail(); return; } ver[oldx][1][curDirection] = true; } ans += val; } if (curDirection == 3) { int val = Math.min(n - 1 - x, m - 1 - y); ; x += val; y += val; if (oldx == 0) { if (hor[oldy][0][curDirection]) { fail(); return; } hor[oldy][0][curDirection] = true; } if (oldy == 0) { if (ver[oldx][0][curDirection]) { fail(); return; } ver[oldx][0][curDirection] = true; } ans += val; } } } void fail() { out.print("-1"); } int getCorrectDir(int x, int y, int dir) { //UL if (dir == 0) { if (x == 0 && y == 0) { return 3; } if (x != 0 && y != 0) { return dir; } else { if (x == 0) { return 2; } else { return 1; } } } //UR if (dir == 1) { if (x == 0 && y == m - 1) { return 2; } if (x != 0 && y != m - 1) { return dir; } else { if (x == 0) { return 3; } else { return 0; } } } //DL if (dir == 2) { if (x == n - 1 && y == 0) { return 1; } if (x != n - 1 && y != 0) { return dir; } else { if (x == n - 1) { return 0; } else { return 3; } } } //DR if (dir == 3) { if (x == n - 1 && y == m - 1) { return 0; } if (x != n - 1 && y != m - 1) { return dir; } else { if (x == n - 1) { return 1; } else { return 2; } } } return -1; } void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(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 double pi = acos(-1.0); const double eps = 1e-8; inline int sign(double x) { if (x < -eps) return -1; return x > eps; } struct Tpoint { double x, y; Tpoint() {} Tpoint(double x, double y) : x(x), y(y) {} inline double norm() { return sqrt(x * x + y * y); } inline void rotate(double ang) { double co = cos(ang), si = sin(ang); double tx = x, ty = y; x = tx * co - ty * si; y = tx * si + ty * co; } }; inline Tpoint operator+(const Tpoint &a, const Tpoint &b) { return Tpoint(a.x + b.x, a.y + b.y); } inline Tpoint operator-(const Tpoint &a, const Tpoint &b) { return Tpoint(a.x - b.x, a.y - b.y); } inline Tpoint operator*(const Tpoint &a, const double &b) { return Tpoint(a.x * b, a.y * b); } inline Tpoint operator/(const Tpoint &a, const double &b) { return Tpoint(a.x / b, a.y / b); } inline double det(const Tpoint &a, const Tpoint &b) { return a.x * b.y - a.y * b.x; } inline double dot(const Tpoint &a, const Tpoint &b) { return a.x * b.x + a.y * b.y; } const int dx[] = {-1, -1, 1, 1}; const int dy[] = {-1, 1, -1, 1}; int main() { int n, m, x, y; scanf("%d%d", &n, &m); char sdir[100]; scanf("%d%d%s", &x, &y, sdir); int dir = 0; if (sdir[0] == 'D') { dir |= 2; } if (sdir[1] == 'R') { dir |= 1; } int target = 0; for (int i = 1; i <= n; ++i) { if ((i + 1) % 2 == (x + y) % 2) { ++target; } if ((i + m) % 2 == (x + y) % 2) { ++target; } } for (int i = 2; i < m; ++i) { if ((i + 1) % 2 == (x + y) % 2) { ++target; } if ((i + n) % 2 == (x + y) % 2) { ++target; } } set<pair<int, int> > visit; long long total_time = 1; for (int t = 0; t < (n + m) * 4; ++t) { visit.insert(make_pair(x, y)); if ((int)visit.size() == target) { printf("%I64d\n", total_time); return 0; } int l = 0, r = max(n, m) + 1; while (l + 1 < r) { int mid = (l + r) / 2; int xx = x + dx[dir] * mid; int yy = y + dy[dir] * mid; if (xx >= 1 && xx <= n && yy >= 1 && yy <= m) { l = mid; } else { r = mid; } } total_time += l; x += dx[dir] * l; y += dy[dir] * l; if (x == 1 || x == n) { dir ^= 2; } if (y == 1 || y == m) { dir ^= 1; } if (x == 1 && y == 1) { dir = 3; } else if (x == 1 && y == m) { dir = 2; } else if (x == n && y == 1) { dir = 1; } else if (x == n && y == m) { dir = 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; void _fill_int(int* p, int val, int rep) { int i; for (i = 0; i < rep; i++) p[i] = val; } int GETi() { int i; scanf("%d", &i); return i; } template <class T> T sqr(T val) { return val * val; } int W, H; int TX[2][100001]; int TY[2][100001]; int CT = 0; void solve() { int f, r, i, j, k, l, x, y, cur, tar, dx, dy, sx, sy; char st[4]; H = GETi(); W = GETi(); sy = GETi() - 1; sx = GETi() - 1; scanf("%s", st); ; dx = (st[1] == 'R') ? 1 : -1; dy = (st[0] == 'U') ? -1 : 1; for (x = 0; x < W; x++) { if (((sx + sy) % 2) == (x % 2)) { TX[0][x]++; CT++; } if (((sx + sy) % 2) == ((x + H - 1) % 2)) { TX[1][x]++; CT++; } } for (y = 0; y < H; y++) { if (((sx + sy) % 2) == (y % 2)) { TY[0][y]++; CT++; } if (((sx + sy) % 2) == ((y + W - 1) % 2)) { TY[1][y]++; CT++; } } signed long long res = 1; for (i = 0; i < 1000000; i++) { if (sx == 0 && TY[0][sy]) { TY[0][sy] = 0; CT--; } if (sx == W - 1 && TY[1][sy]) { TY[1][sy] = 0; CT--; } if (sy == 0 && TX[0][sx]) { TX[0][sx] = 0; CT--; } if (sy == H - 1 && TX[1][sx]) { TX[1][sx] = 0; CT--; } if (CT == 0) { cout << res << endl; return; } if (sx == 0) dx = 1; if (sx == W - 1) dx = -1; if (sy == 0) dy = 1; if (sy == H - 1) dy = -1; int ml = 1000000; if (dx > 0) ml = min(ml, W - 1 - sx); if (dx < 0) ml = min(ml, sx); if (dy > 0) ml = min(ml, H - 1 - sy); if (dy < 0) ml = min(ml, sy); res += ml; sx += ml * dx; sy += ml * dy; } printf("-1\n"); return; } int main(int argc, char** argv) { if (argc > 1) freopen(argv[1], "r", stdin); 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; void open() { freopen("data.txt", "r", stdin); } void out() { freopen("out.txt", "w", stdout); } const int maxn = 1e5 + 5; const int INF = 0x3f3f3f3f; map<int, int> mymap[maxn]; int main() { int n, m, x, y, dx, dy, cnt = 0; char str[5]; scanf("%d%d%d%d%s", &n, &m, &x, &y, str); if (str[0] == 'U') dx = -1; else dx = 1; if (str[1] == 'L') dy = -1; else dy = 1; int tot = n + m - 2; if (x == 1 || x == n || y == 1 || y == m) { tot--; mymap[x][y] = 1; } long long ans = 1; while (1) { cnt++; if (cnt > 1e6) return puts("-1"), 0; int tmp = INF; if (dx == 1) tmp = min(n - x, tmp); else tmp = min(tmp, x - 1); if (dy == 1) tmp = min(m - y, tmp); else tmp = min(tmp, y - 1); ans += tmp; x += dx * tmp; y += dy * tmp; if (x == 1) dx = 1; else if (x == n) dx = -1; if (y == 1) dy = 1; else if (y == m) dy = -1; if (!mymap[x][y]) { mymap[x][y] = 1; tot--; } if (!tot) { 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; int dx, dy; int x, y; char s[100005]; map<int, int> a[100010]; int main() { cin >> n >> m; cin >> x >> y; scanf("%s", s + 1); long long sum = 0; if (s[1] == 'U') dx = -1; else dx = 1; if (s[2] == 'L') dy = -1; else dy = 1; int cnt = n + m - 2; if (x == 1 || x == n || y == 1 || y == m) { a[x][y] = 1; cnt--; } long long ji = 0; while (1) { ji++; if (ji >= 1e7) { cout << -1 << endl; return 0; } int dis = int(0x3f3f3f3f); 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; sum += 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) { cnt--; a[x][y] = 1; } if (!cnt) { cout << sum + 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> int n, m; int a[400000]; int b[400000][4]; int dx[4] = {1, 1, -1, -1}; int dy[4] = {1, -1, 1, -1}; int min(int a, int b) { if (a < b) { return a; } else { return b; } } int f(int x, int y) { if (x == 1) { return y - 1; } else if (x == n) { return m + y - 1; } else if (y == 1) { return 2 * m + x - 1; } else { return 2 * m + n + x - 1; } } int main() { int x, y, p, r = 0, i; long long sum = 1; char s[3]; scanf("%d %d", &n, &m); scanf("%d %d %s", &x, &y, s); if (s[0] == 'D') { if (s[1] == 'R') { p = 0; } else { p = 1; } } else { if (s[1] == 'R') { p = 2; } else { p = 3; } } for (i = 1; i <= m; i++) { if ((x + y) % 2 != (i + 1) % 2) a[f(1, i)] = 1; if ((x + y) % 2 != (i + n) % 2) a[f(n, i)] = 1; } for (i = 1; i <= n; i++) { if ((x + y) % 2 != (i + 1) % 2) a[f(i, 1)] = 1; if ((x + y) % 2 != (i + m) % 2) a[f(i, m)] = 1; } a[2 * m] = a[2 * m + n - 1] = a[2 * m + n] = a[2 * m + 2 * n - 1] = a[f(x, y)] = 1; for (i = 0; i < 2 * m + 2 * n; i++) { if (a[i] == 0) r++; } while (1) { int c = 1e9; if (p < 2) { c = min(c, n - x); } else { c = min(c, x - 1); } if (p & 1) { c = min(c, y - 1); } else { c = min(c, m - y); } x += dx[p] * c; y += dy[p] * c; sum += c; if (a[f(x, y)] == 0) r--; if (r == 0) break; a[f(x, y)] = 1; if (b[f(x, y)][p] == 1) { puts("-1"); return 0; } b[f(x, y)][p] = 1; if (x == 1 || x == n) p = (p + 2) % 4; if (y == 1) p = (p + 3) % 4; if (y == m) p = (p + 1) % 4; } printf("%I64d\n", sum); 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, x, y; cin >> n >> m >> x >> y; set<pair<int, int> > st; char cm[2]; cin >> cm; int fx, fy; if (cm[0] == 'U') { fx = -1; } else { fx = 1; } if (cm[1] == 'L') { fy = -1; } else { fy = 1; } long long ans = 1; for (int i = 0; i <= n + n + m + m; i++) { st.insert(pair<int, int>(x, y)); if ((int)st.size() == n + m - 2) { cout << ans; return 0; } int ga, gb; if (fx == -1) { ga = x - 1; } else { ga = n - x; } if (fy == -1) { gb = y - 1; } else { gb = m - y; } int move = min(ga, gb); x += fx * move; y += fy * move; ans += 1LL * move; if (x * fx == -1 || x * fx == n) { fx = -fx; } if (y * fy == -1 || y * fy == m) { fy = -fy; } } 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
#include <bits/stdc++.h> using namespace std; set<pair<int, int> > st; int n, m; pair<int, int> get_dir(char a[5]) { int x = 1; if (a[0] == 'U') { x = -1; } int y = 1; if (a[1] == 'L') y = -1; return make_pair(x, y); } pair<int, int> nxt_dir(pair<int, int> pos, pair<int, int> dir) { if (pos.first == 1 && dir.first == -1) dir.first *= -1; if (pos.first == n && dir.first == 1) dir.first *= -1; if (pos.second == 1 && dir.second == -1) dir.second *= -1; if (pos.second == m && dir.second == 1) dir.second *= -1; return dir; } long long ans = 0; pair<int, int> nxt_pos(pair<int, int> pos, pair<int, int> dir) { int ca, cb; if (dir.first == 1) ca = n - pos.first; else ca = pos.first - 1; if (dir.second == 1) cb = m - pos.second; else cb = pos.second - 1; int mov = min(ca, cb); ans += mov; return make_pair(pos.first + dir.first * mov, pos.second + dir.second * mov); } int main() { scanf("%d %d", &n, &m); if (n == 1 && m == 1) { cout << 0 << endl; return 0; } int a, b; scanf("%d %d", &a, &b); char dir[5]; int oa = a & 1, ob = b & 1; scanf("%s", dir); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j += m - 1) { if ((i & 1) == oa && (j & 1) == ob) { st.insert(make_pair(i, j)); } else if ((i & 1) == oa ^ 1 && (j & 1) == ob ^ 1) { st.insert(make_pair(i, j)); } } } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j += n - 1) { if ((i & 1) == oa && (j & 1) == ob) { st.insert(make_pair(j, i)); } else if ((i & 1) == oa ^ 1 && (j & 1) == ob ^ 1) { st.insert(make_pair(j, i)); } } } int sz = st.size() * 8; pair<int, int> now = make_pair(a, b); pair<int, int> di = get_dir(dir); st.erase(now); ans = 1; for (int t = 0; t < sz; t++) { now = nxt_pos(now, di); di = nxt_dir(now, di); st.erase(now); if (st.size() == 0) { cout << ans << endl; return 0; } } cout << -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 N = 100010; const int M = 4; int now[2], dila[2]; int vis[N][4], n, m, cnt, ans_cnt; char s[4]; long long ans; int main() { int i, j, k, *p; bool lose = false; scanf("%d%d%d%d%s", &n, &m, &now[0], &now[1], s); if (s[0] == 'U') dila[0] = -1; else dila[0] = 1; if (s[1] == 'L') dila[1] = -1; else dila[1] = 1; if (now[0] == 1) vis[now[1]][0]++, cnt++; if (now[0] == n) vis[now[1]][2]++, cnt++; if (now[1] == 1) vis[now[0]][1]++, cnt++; if (now[1] == m) vis[now[0]][3]++, cnt++; ans_cnt += (m - (((now[1] - now[0] + 1) % 2 - 2) % 2 + 2)) / 2 + 1; ans_cnt += (n - (((now[0] - now[1] + 1) % 2 - 2) % 2 + 2)) / 2 + 1; ans_cnt += (m - (((now[1] + (n - now[0])) % 2 - 2) % 2 + 2)) / 2 + 1; ans_cnt += (n - (((now[0] + (m - now[1])) % 2 - 2) % 2 + 2)) / 2 + 1; ans++; while (cnt < ans_cnt && !lose) { k = 0x7fffffff; if (dila[0] == 1) k = min(k, n - now[0]); else k = min(k, now[0] - 1); if (dila[1] == 1) k = min(k, m - now[1]); else k = min(k, now[1] - 1); ans += k; now[0] += dila[0] * k; now[1] += dila[1] * k; if (now[0] == 1) { p = &vis[now[1]][0]; (*p)++; if (*p == 1) cnt++; if (*p > M) lose = true; if (dila[0] == -1) dila[0] = -dila[0]; } if (now[0] == n) { p = &vis[now[1]][2]; (*p)++; if (*p == 1) cnt++; if (*p > M) lose = true; if (dila[0] == 1) dila[0] = -dila[0]; } if (now[1] == 1) { p = &vis[now[0]][1]; (*p)++; if (*p == 1) cnt++; if (*p > M) lose = true; if (dila[1] == -1) dila[1] = -dila[1]; } if (now[1] == m) { p = &vis[now[0]][3]; (*p)++; if (*p == 1) cnt++; if (*p > M) lose = true; if (dila[1] == 1) dila[1] = -dila[1]; } } if (lose) 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, tot, a, b, w, f[4][100010], dx, dy; long long ans; char ch[10]; void doit(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 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%d%d%s", &n, &m, &x, &y, ch); ch[0] == 'D' ? dx = 1 : dx = -1; ch[1] == 'R' ? dy = 1 : dy = -1; ans = 1; for (int i = 1; i <= 2 * (n + m - 2); i++) { doit(x, y); if (tot >= n + m - 2) return printf("%I64d", ans), 0; w = min(dx > 0 ? n - x : x - 1, dy > 0 ? m - y : y - 1); ans += w; x += w * dx; y += dy * w; } return printf("-1"), 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; string str; int n, m, x, y; int use[100010][4]; int movex[] = {-1, -1, 1, 1}; int movey[] = {-1, 1, -1, 1}; int Judge(int x, int y) { int ans; if (x == 1) ans = use[y][0]++; if (x == n) ans = use[y][1]++; if (y == 1) ans = use[x][2]++; if (y == m) ans = use[x][3]++; return ans; } long long work() { long long ans = 1; int cnt = 0, dir = (str[0] == 'D') * 2 + (str[1] == 'R'); for (int i = 1; i <= n; ++i) cnt += (((i + m) & 1) == ((x + y) & 1)) + (((i + 1) & 1) == ((x + y) & 1)); for (int i = 2; i < m; ++i) cnt += (((i + n) & 1) == ((x + y) & 1)) + (((i + 1) & 1) == ((x + y) & 1)); cnt -= Judge(x, y) == 0; while (1) { int d1 = dir >> 1, d2 = dir & 1, newx, newy; if (d1 == 0 && d2 == 0) { newx = 1, newy = y - x + 1; if (newy < 1) newx += 1 - newy, newy = 1; } if (d1 == 0 && d2 == 1) { newx = 1, newy = x + y - 1; if (newy > m) newx += newy - m, newy = m; } if (d1 == 1 && d2 == 0) { newx = n, newy = x + y - n; if (newy < 1) newx -= 1 - newy, newy = 1; } if (d1 == 1 && d2 == 1) { newx = n, newy = y - x + n; if (newy > m) newx -= newy - m, newy = m; } ans += abs(newx - x), x = newx, y = newy; int vec = 0; if (x + movex[dir] < 1 || x + movex[dir] > n) vec ^= 2; if (y + movey[dir] < 1 || y + movey[dir] > m) vec ^= 1; dir ^= vec; int c = Judge(x, y); cnt -= c == 0; if (cnt == 0) break; if (c == 4) return -1; } return ans; } int main() { cin >> n >> m >> x >> y >> str; cout << work() << 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.*; public class Main { public static Pair make_pair(int x ,int y) { Pair tmp = new Pair(); tmp.a = x; tmp.b=y; return tmp; } public static Triple make_trip(int x ,int y, int z) { Triple tt = new Triple(); tt.a = x; tt.b=y; tt.c = z; return tt; } static Scanner cin = new Scanner (System.in); static Set< Pair > set1 = new HashSet< Pair >(); static Set< Triple > set2 = new HashSet< Triple >(); static int x, y; public static Boolean check(int xx, int yy) { return ((xx+yy) & 1) == ((x+y) & 1); } public static void main(String args[]) { int n, m, p; String tmp; char c, d; long ans; n = cin.nextInt(); m = cin.nextInt(); x = cin.nextInt(); y = cin.nextInt(); tmp = cin.next(); c = tmp.charAt(0); d = tmp.charAt(1); p = 0; ans = 1; if (c == 'U') p += 2; if (d == 'R') p ++; for (int i = 1; i <= m; i++) { if (check(1, i)) set1.add(make_pair(1, i)); if (check(n, i)) set1.add(make_pair(n, i)); } for (int i = 1; i <= n; i++) { if (check(i, 1)) set1.add(make_pair(i, 1)); if (check(i, m)) set1.add(make_pair(i, m)); } set1.remove(make_pair(x, y)); int tk = 0; while (set1.size() != 0 && set2.contains(make_trip(x, y, p)) == false) { //System.out.printf("%d %d %d\n", x, y, p); set2.add(make_trip(x, y, p)); if (p == 0) {if (n-x < y-1) {p = 2; tk = n-x;} else {p = 1; tk = y-1;} x+=tk; y-=tk;} else if (p == 1) {if (n-x < m-y) {p = 3; tk = n-x;} else {p = 0; tk = m-y;} x+=tk; y+=tk;} else if (p == 2) {if (x-1 < y-1) {p = 0; tk = x-1;} else {p = 3; tk = y-1;} x-=tk; y-=tk;} else if (p == 3) {if (x-1 < m-y) {p = 1; tk = x-1;} else {p = 2; tk = m-y;} x-=tk; y+=tk;}; ans += tk; set1.remove(make_pair(x, y)); } if (set1.size() == 0) System.out.println(ans); else System.out.println(-1); } } class Pair { int a, b; @Override public boolean equals(Object obj) { if (obj == null || a != ((Pair) obj).a || b != ((Pair) obj).b) return false; return true; } @Override public int hashCode() { final long base = 1000000007; long result = (a * (long)100000 % base + b-1) % base; return (int)result; } } class Triple { int a, b, c; @Override public boolean equals(Object obj) { if (obj == null || a != ((Triple) obj).a || b != ((Triple) obj).b || c != ((Triple) obj).c) return false; return true; } @Override public int hashCode() { final long base = 1000000007; long result = (a*313*313%base + b*313%base + c) % base; return (int)result; } }
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<long long, long long> mp[100010]; const int INF = 2147483647; int n, m, x, y; char c[3]; int sx, sy; long long t, tot = 0, sum = 1; int dis = INF; int main() { scanf("%d%d%d%d%s", &n, &m, &x, &y, c + 1); if (c[1] == 'U') sx = -1; else sx = 1; if (c[2] == 'L') sy = -1; else sy = 1; t = n + m - 2; if (x == 1 || x == n || y == 1 || y == m) { t--; mp[x][y] = 1; } while (1) { dis = INF; tot++; if (tot >= 1234567) { puts("-1"); return 0; } if (sx == 1) dis = min(dis, n - x); else dis = min(dis, x - 1); if (sy == 1) dis = min(dis, m - y); else dis = min(dis, y - 1); x = x + sx * dis; y = y + sy * dis; sum += dis; if (x == 1) sx = 1; else if (x == n) sx = -1; if (y == 1) sy = 1; else if (y == m) sy = -1; if (!mp[x][y]) { mp[x][y] = 1; t--; } if (t == 0) { printf("%I64d\n", sum); 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; const int N = 100005; pair<int, int> p, q; int way[4][2] = {1, 1, -1, 1, 1, -1, -1, -1}; int n, m, dir; char str[5]; set<pair<int, int> > s; int main() { scanf("%d %d", &n, &m); scanf("%d %d %s", &p.first, &p.second, str); if (strcmp(str, "DR") == 0) dir = 0; else if (strcmp(str, "UR") == 0) dir = 1; else if (strcmp(str, "DL") == 0) dir = 2; else dir = 3; for (int i = 1; i <= m; i++) { if ((1 + i) % 2 == (p.first + p.second) % 2) s.insert(make_pair(1, i)); if ((n + i) % 2 == (p.first + p.second) % 2) s.insert(make_pair(n, i)); } for (int i = 2; i < n; i++) { if ((i + 1) % 2 == (p.first + p.second) % 2) s.insert(make_pair(i, 1)); if ((m + i) % 2 == (p.first + p.second) % 2) s.insert(make_pair(i, m)); } s.erase(p); long long ret = 1; for (int t = 0; t < (n + m) * 4 && !s.empty(); t++) { int low = 0, high = min(n, m), mid, ans; while (low <= high) { mid = (low + high) >> 1; q.first = p.first + way[dir][0] * mid; q.second = p.second + way[dir][1] * mid; if (q.first >= 1 && q.second >= 1 && q.first <= n && q.second <= m) ans = mid, low = mid + 1; else high = mid - 1; } q.first = p.first + way[dir][0] * ans; q.second = p.second + way[dir][1] * ans; ret += ans; if (s.find(q) != s.end()) { s.erase(q); } if (q.first == 1 && q.second == 1) { dir = 0; } else if (q.first == 1 && q.second == m) { dir = 2; } else if (q.first == n && q.second == 1) { dir = 1; } else if (q.first == n && q.second == m) { dir = 3; } else if (q.first == 1) { if (dir == 1) dir = 0; else if (dir == 3) dir = 2; } else if (q.first == n) { if (dir == 2) dir = 3; else if (dir == 0) dir = 1; } else if (q.second == 1) { if (dir == 2) dir = 0; else if (dir == 3) dir = 1; } else if (q.second == m) { if (dir == 1) dir = 3; else if (dir == 0) dir = 2; } p = q; } if (s.empty()) printf("%I64d\n", ret); else 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; bool f[4][100033]; int n, m, dx, dy, x, y, cnt = 0; long long ans = 1; char s[5]; int main() { scanf("%d%d%d%d%s", &n, &m, &x, &y, s); dx = s[0] == 'D' ? 1 : -1; dy = s[1] == 'R' ? 1 : -1; for (int i = 1, a, b; i <= 2 * (n + m - 2); i++) { if (x == 1) a = 0, b = y; else if (x == n) a = 1, b = y; else if (y == 1) a = 2, b = x; else a = 3, b = x; if (!f[a][b]) f[a][b] = 1, cnt++; if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; else if (y == m) dy = -1; if (cnt >= n + m - 2) return printf("%I64d\n", ans), 0; int v = min(dx > 0 ? n - x : x - 1, dy > 0 ? m - y : y - 1); ans += v, x += v * dx, y += v * dy; } return puts("-1"), 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 = 105000; int n, m; int nx, ny; int dx, dy; char dir[5]; bool up[N], down[N], leftt[N], rightt[N]; int cc = 0; long long ans = 1; void add() { if (nx == 1) { if (!up[ny]) { cc++; up[ny] = 1; } } if (nx == n) { if (!down[ny]) { cc++; down[ny] = 1; } } if (ny == 1) { if (!leftt[nx]) { cc++; leftt[nx] = 1; } } if (ny == m) { if (!rightt[nx]) { cc++; rightt[nx] = 1; } } } void Do() { int needx = max((1 - nx) / dx, (n - nx) / dx); int needy = max((1 - ny) / dy, (m - ny) / dy); int need = min(needx, needy); nx += dx * need; ny += dy * need; if (needx == need) dx = -dx; if (needy == need) dy = -dy; ans += need; add(); } int main() { int i; scanf("%d%d%d%d%s", &n, &m, &nx, &ny, dir); int key = n / 2 + m / 2; key <<= 1; if (n & 1) { if ((nx + ny) % 2 == 0) key++; if ((nx + ny) % 2 == (1 + m) % 2) key++; } if (m & 1) { if ((nx + ny) % 2 == 0) key++; if ((nx + ny) % 2 == (1 + n) % 2) key++; } int maxz = (n + m) * 5; if (dir[0] == 'U') dx = -1; else dx = 1; if (dir[1] == 'L') dy = -1; else dy = 1; add(); for (i = 1; i <= maxz; i++) { Do(); if (cc == key) { 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; int xx[4] = {-1, -1, 1, 1}, yy[4] = {-1, 1, -1, 1}, n, m, x, y, mk; long long ans; set<pair<int, int> > A; char s[3]; void read(int &x) { char ch = getchar(); int mark = 1; for (; ch != '-' && (ch < '0' || ch > '9'); ch = getchar()) ; if (ch == '-') mark = -1, ch = getchar(); for (x = 0; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - 48; x *= mark; } bool Rflct(int &x, int &y, int &mk) { if (mk == 0) { int t = min(x - 1, y - 1); ans += t; x -= t; y -= t; if (x == 1 && y == 1) { mk = 3; return 1; } else if (x == 1) mk = 2; else mk = 1; } else if (mk == 1) { int t = min(x - 1, m - y); ans += t; x -= t; y += t; if (x == 1 && y == m) { mk = 2; return 1; } else if (x == 1) mk = 3; else mk = 0; } else if (mk == 2) { int t = min(n - x, y - 1); ans += t; x += t; y -= t; if (x == n && y == 1) { mk = 1; return 1; } else if (x == n) mk = 0; else mk = 3; } else { int t = min(n - x, m - y); ans += t; x += t; y += t; if (x == n && y == m) { mk = 0; return 1; } else if (x == n) mk = 1; else mk = 2; } return 0; } int main() { read(n); read(m); read(x); read(y); scanf("%s", s); if (s[0] == 'U') if (s[1] == 'L') mk = 0; else mk = 1; else if (s[1] == 'L') mk = 2; else mk = 3; int cnt = n + m - 3; A.insert(make_pair(x, y)); for (int _ = 1;; _++) { if (_ >= 500000) { printf("-1\n"); return 0; } Rflct(x, y, mk); if (A.find(make_pair(x, y)) == A.end()) { A.insert(make_pair(x, y)); cnt--; if (cnt == 0) { printf("%I64d\n", ans + 1); 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 i, j, m, n, p, k, rest; char We[3]; long long ans; struct Node { int x, y, pos; } A; map<pair<int, int>, int> mp[4], Mp; int P(char *a) { if (a[0] == 'U' && a[1] == 'L') return 0; if (a[0] == 'U' && a[1] == 'R') return 1; if (a[0] == 'D' && a[1] == 'L') return 2; if (a[0] == 'D' && a[1] == 'R') return 3; } Node get(Node A) { if (A.pos == 0) { int w = min(A.x, A.y) - 1; ans += w; A.x -= w; A.y -= w; if (A.x == 1 && A.y == 1) A.pos = 3; else if (A.x == 1) A.pos = 2; else A.pos = 1; } else if (A.pos == 1) { int w = min(A.x - 1, m - A.y); ans += w; A.x -= w; A.y += w; if (A.x == 1 && A.y == m) A.pos = 2; else if (A.x == 1) A.pos = 3; else A.pos = 0; } else if (A.pos == 2) { int w = min(n - A.x, A.y - 1); ans += w; A.x += w; A.y -= w; if (A.x == n && A.y == 1) A.pos = 1; else if (A.x == n) A.pos = 0; else A.pos = 3; } else { int w = min(n - A.x, m - A.y); ans += w; A.x += w; A.y += w; if (A.x == n && A.y == m) A.pos = 0; else if (A.x == n) A.pos = 1; else A.pos = 2; } return A; } int main() { scanf("%d%d", &n, &m); scanf("%d%d%s", &A.x, &A.y, We); A.pos = P(We), rest = 0; if (A.x == 1 || A.y == 1 || A.x == n || A.y == m) --rest, mp[A.pos][make_pair(A.x, A.y)] = 1, Mp[make_pair(A.x, A.y)] = 1; Node B = get(A); if (A.x == B.x && A.y == B.y) A = B; ans = 1; for (i = 1; i <= m; ++i) { if (((1 + i) & 1) == ((A.x + A.y) & 1)) ++rest; if (((n + i) & 1) == ((A.x + A.y) & 1)) ++rest; } for (i = 2; i < n; ++i) { if (((1 + i) & 1) == ((A.x + A.y) & 1)) ++rest; if (((m + i) & 1) == ((A.x + A.y) & 1)) ++rest; } for (;;) { A = get(A); if (mp[A.pos][make_pair(A.x, A.y)]) { printf("-1\n"); return 0; } if (!Mp[make_pair(A.x, A.y)]) Mp[make_pair(A.x, A.y)] = 1, --rest; mp[A.pos][make_pair(A.x, A.y)] = 1; if (!rest) break; } 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; set<pair<int, int> > st; int n, m; pair<int, int> get_dir(char a[5]) { int x = 1; if (a[0] == 'U') { x = -1; } int y = 1; if (a[1] == 'L') y = -1; return make_pair(x, y); } pair<int, int> nxt_dir(pair<int, int> pos, pair<int, int> dir) { if (pos.first == 1 && dir.first == -1) dir.first *= -1; if (pos.first == n && dir.first == 1) dir.first *= -1; if (pos.second == 1 && dir.second == -1) dir.second *= -1; if (pos.second == m && dir.second == 1) dir.second *= -1; return dir; } long long ans = 0; pair<int, int> nxt_pos(pair<int, int> pos, pair<int, int> dir) { int ca, cb; if (dir.first == 1) ca = n - pos.first; else ca = pos.first - 1; if (dir.second == 1) cb = m - pos.second; else cb = pos.second - 1; int mov = min(ca, cb); ans += mov; return make_pair(pos.first + dir.first * mov, pos.second + dir.second * mov); } int main() { scanf("%d %d", &n, &m); if (n == 1 && m == 1) { cout << 0 << endl; return 0; } int a, b; scanf("%d %d", &a, &b); char dir[5]; int oa = a & 1, ob = b & 1; scanf("%s", dir); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j += m - 1) { if ((i & 1) == oa && (j & 1) == ob) { st.insert(make_pair(i, j)); } else if ((i & 1) == oa ^ 1 && (j & 1) == ob ^ 1) { st.insert(make_pair(i, j)); } } } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j += n - 1) { if ((i & 1) == oa && (j & 1) == ob) { st.insert(make_pair(j, i)); } else if ((i & 1) == oa ^ 1 && (j & 1) == ob ^ 1) { st.insert(make_pair(j, i)); } } } int sz = st.size() * 32; pair<int, int> now = make_pair(a, b); pair<int, int> di = get_dir(dir); st.erase(now); ans = 1; for (int t = 0; t < sz; t++) { now = nxt_pos(now, di); di = nxt_dir(now, di); st.erase(now); if (st.size() == 0) { cout << ans << endl; return 0; } } cout << -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; long long int res, n, m, x, y, dx = 1, dy = 1, X, Y, Dx, Dy, nx, ny, INF = 10000000000000; char in[5]; set<pair<long long int, long long int> > s; void Change_Direction() { if (x == n) dx = -1; else if (x == 1) dx = 1; if (y == m) dy = -1; else if (y == 1) dy = 1; } int main() { scanf("%I64d %I64d %I64d %I64d", &n, &m, &X, &Y); scanf("%s", in); x = X, y = Y; if (in[0] == 'U') dx = -1; if (in[1] == 'L') dy = -1; Change_Direction(); Dx = dx, Dy = dy; for (;;) { s.insert(make_pair(x, y)); long long int moves = INF; if (dx == 1) moves = min(moves, n - x); else moves = min(moves, x - 1); if (dy == 1) moves = min(moves, m - y); else moves = min(moves, y - 1); x += (moves * dx), y += (moves * dy); Change_Direction(); if (s.size() == n + m - 2) break; if (x == X && y == Y && dx == Dx && dy == Dy) break; res += moves; } if (s.size() == n + m - 2) printf("%I64d", res + 1); else printf("-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.*; import java.util.*; public class D { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; int n, m; long f(int x, int y) { return (long)x * m + y; } boolean test(int mask, int i) { return ((mask >> i) & 1) == 1; } int getD(int dx, int dy) { return (dx == -1 ? 2 : 0) + (dy == -1 ? 1 : 0); } int getMove(int cur, int delta, int size) { return delta == 1 ? (size - 1 - cur) : (cur); } void solve() throws IOException { n = nextInt(); m = nextInt(); int x0 = nextInt() - 1; int y0 = nextInt() - 1; int totalBorder = n + m - 2; HashMap<Long, Integer> mask = new HashMap<>(); long ans = 1; String dir = nextToken(); int dx = dir.charAt(0) == 'D' ? 1 : -1; int dy = dir.charAt(1) == 'R' ? 1 : -1; while (true) { if (x0 == 0 && dx == -1) dx = 1; if (x0 == n - 1 && dx == 1) dx = -1; if (y0 == 0 && dy == -1) dy = 1; if (y0 == m - 1 && dy == 1) dy = -1; long curCell = f(x0, y0); int curDir = getD(dx, dy); Integer tmp = mask.get(curCell); // out.println(x0 + " " + y0 + " " + dx + " " + dy + " " + tmp + " " + curDir); if (tmp == null) { tmp = 0; totalBorder--; if (totalBorder == 0) { break; } } if (test(tmp, curDir)) { out.println(-1); return; } tmp ^= (1 << curDir); mask.put(curCell, tmp); int moveX = getMove(x0, dx, n); int moveY = getMove(y0, dy, m); int move = Math.min(moveX, moveY); ans += move; x0 += move * dx; y0 += move * dy; } out.println(ans); } D() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new D(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
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, 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> int n, m, x, y; long long ans; char ord[10]; int vis[4][100100][4], cnt, r[4][100100]; int p, q, dd, xx, yy, nd, nx, ny; int min(int c1, int c2) { if (c1 < c2) return c1; return c2; } int main() { int s; scanf("%d%d%d%d%s", &n, &m, &x, &y, ord); if ((x & 1) ^ (y & 1)) { if (!(n & 1)) cnt = m; else cnt = (m >> 1) * 2; if (!(m & 1)) cnt += n; else cnt += (n >> 1) * 2; } else { if (!(n & 1)) cnt = m; else cnt = ((m + 1) >> 1) * 2; if (!(m & 1)) cnt += n; else cnt += ((n + 1) >> 1) * 2; } if (ord[0] == 'D') { if (ord[1] == 'R') dd = 3; else dd = 2; } else { if (ord[1] == 'R') dd = 0; else dd = 1; } xx = x; yy = y; while (cnt) { if (xx == 1) { q = yy; p = 0; if (!r[p][q]) { r[p][q] = 1; --cnt; } } if (yy == 1) { q = xx; p = 1; if (!r[p][q]) { r[p][q] = 1; --cnt; } } if (xx == n) { q = yy; p = 2; if (!r[p][q]) { r[p][q] = 1; --cnt; } } if (yy == m) { q = xx; p = 3; if (!r[p][q]) { r[p][q] = 1; --cnt; } } if (cnt == 0) break; if (!vis[p][q][dd]) vis[p][q][dd] = 1; else break; if (dd == 0) { s = min(m - yy, xx - 1); nx = xx - s; ny = yy + s; if (nx == 1 && ny == m) nd = 2; else if (nx == 1) nd = 3; else nd = 1; } if (dd == 1) { s = min(xx - 1, yy - 1); nx = xx - s; ny = yy - s; if (nx == 1 && ny == 1) nd = 3; else if (nx == 1) nd = 2; else nd = 0; } if (dd == 2) { s = min(n - xx, yy - 1); nx = xx + s; ny = yy - s; if (nx == n && ny == 1) nd = 0; else if (nx == n) nd = 1; else nd = 3; } if (dd == 3) { s = min(n - xx, m - yy); nx = xx + s; ny = yy + s; if (nx == n && ny == m) nd = 1; else if (nx == n) nd = 0; else nd = 2; } ans += s; dd = nd; xx = nx; yy = ny; } if (cnt) puts("-1"); else 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; int dx[] = {-1, 1, -1, 1}; int dy[] = {-1, -1, 1, 1}; int n, m, x, y, dir; char str[10]; int main() { while (scanf("%d%d", &n, &m) == 2) { scanf("%d%d", &x, &y); scanf("%s", str); dir = 0; if (str[0] == 'D') dir += 1; if (str[1] == 'R') dir += 2; int tot = 0; if ((x + y) % 2 == 0) tot += (n + 1) / 2 + m / 2 - 1; else tot += n / 2 + (m - 1) / 2; if ((x + y) % 2 == (m + 1) % 2) tot += (n + 1) / 2; else tot += n / 2; if ((x + y) % 2 == (2 + n) % 2) tot += (m - 1) / 2; else tot += (m - 2) / 2; set<pair<int, int> > st; long long ans = 1; for (int i = 0; i < (n + m) * 4; i++) { st.insert(make_pair(x, y)); if (st.size() == tot) { printf("%I64d\n", ans); break; } int l = 0, r = max(n, m) + 1; while (l + 1 < r) { int mid = (l + r) / 2; int xx = x + dx[dir] * mid; int yy = y + dy[dir] * mid; if (xx >= 1 && xx <= n && yy >= 1 && yy <= m) l = mid; else r = mid; } ans = ans + l; x = x + l * dx[dir]; y = y + l * dy[dir]; if (x == 1 || x == n) dir = dir ^ 1; if (y == 1 || y == m) dir = dir ^ 2; if (x == 1 && y == 1) dir = 3; if (x == 1 && y == m) dir = 1; if (x == n && y == 1) dir = 2; if (x == n && y == m) dir = 0; } if (st.size() != tot) 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; template <class T> inline void CLR(T& A) { A.clear(); } inline bool insize(int c, int l, int r) { if (c >= l && c <= r) return true; return false; } template <class T> inline void checkmin(T& a, T b) { if (a == -1 || a > b) a = b; } template <class T> inline void checkmax(T& a, T b) { if (a < b) a = b; } int dx[] = {0, 1, 0, -1, 1, 1, -1, -1}; int dy[] = {1, 0, -1, 0, 1, -1, 1, -1}; int sig(double x) { return fabs(x - 0) < 1e-8 ? 0 : x > 0 ? 1 : -1; } template <class T> inline void sf(T& x) { char c; int mul = 1; while ((c = getchar()) != EOF) { if (c == '-') mul = -1; if (c >= '0' && c <= '9') { x = c - '0'; break; } } if (c == EOF) { x = EOF; return; } while ((c = getchar())) { if (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + (c - '0'); } else break; } x *= mul; } template <class T0, class T1> inline void sf(T0& x, T1& y) { sf(x); sf(y); } template <class T0, class T1, class T2> inline void sf(T0& x, T1& y, T2& z) { sf(x); sf(y); sf(z); } const int N = 400005; const int E = 20055; const int INF = 0x3f3f3f3f; const long long LINF = 0x3F3F3F3F3F3F3F3FLL; int n, m, sx, sy, flag; long long ans; char op[5]; map<pair<int, int>, int> mp; void change(char* op) { if (op[0] == 'U' && sx == 1) op[0] = 'D'; if (op[0] == 'D' && sx == n) op[0] = 'U'; if (op[1] == 'L' && sy == 1) op[1] = 'R'; if (op[1] == 'R' && sy == m) op[1] = 'L'; } bool go() { pair<int, int> p = make_pair(sx, sy); if (sx == 1 || sx == n || sy == 1 || sy == m) { int c = ++mp[p]; if (c == 1) flag--; else if (c >= 4) { flag = -1; return 0; } if (!flag) return 1; } int s1 = op[0] == 'U' ? sx - 1 : n - sx; int s2 = op[1] == 'L' ? sy - 1 : m - sy; int s = min(s1, s2); ans += (long long)s; sx += op[0] == 'U' ? -s : s; sy += op[1] == 'L' ? -s : s; return 1; } long long Run() { while (flag > 0) { if (!go()) break; change(op); } if (!flag) return ans; return -1; } int main() { sf(n, m); sf(sx, sy); scanf("%s", op); ans = 1; flag = 0; CLR(mp); for (int(i) = (1); (i) <= (m); (i)++) { if ((i + 1) % 2 == 0) flag++; if ((i + n) % 2 == 0) flag++; } for (int(i) = (2); (i) <= (n - 1); (i)++) { if ((i + 1) % 2 == 0) flag++; if ((i + m) % 2 == 0) flag++; } cout << Run() << 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 N = 1e5 + 7; int n, m, sx, sy; char dir[4]; int main() { scanf("%d%d%d%d %s", &n, &m, &sx, &sy, dir); int dx = dir[0] == 'U' ? -1 : 1; int dy = dir[1] == 'L' ? -1 : 1; int remain = n + m - 2; set<pair<int, int> > Set; if (sx == 1 || sx == n || sy == 1 || sy == m) { remain--; Set.insert({sx, sy}); } long long ans = 0; for (int i = (0); i < (4 * N); ++i) { int step = (1ll << (30)); step = min(step, dx == 1 ? n - sx : sx - 1); step = min(step, dy == 1 ? m - sy : sy - 1); ans += step; sx += dx * step; sy += dy * step; if ((sx == 1 && dx == -1) || (sx == n && dx == 1)) dx *= -1; if ((sy == 1 && dy == -1) || (sy == m && dy == 1)) dy *= -1; if (Set.find({sx, sy}) == Set.end()) { if (!--remain) { printf("%lld\n", ans + 1); return 0; } Set.insert({sx, sy}); } } 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; map<pair<int, int>, int> vst; int tot, n, m, i, j, k, dx = 1, dy = 1; void go(int x, int y) { if (!vst[pair<int, int>(x, y)]) { vst[pair<int, int>(x, y)] = 1; tot++; } if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; if (y == m) dy = -1; } int main() { cin >> n >> m; int x, y, t, step = 2 * (n + m); char dr[10]; cin >> x >> y; scanf("%s", dr); if (dr[1] == 'L') dy = -1; if (dr[0] == 'U') dx = -1; long long ans = 1; go(x, y); while (step--) { if (tot == (n + m - 2)) { cout << ans << endl; return 0; } int t = min((dx == 1) ? n - x : x - 1, (dy == 1) ? m - y : y - 1); ans += t; x += t * dx, y += t * dy; go(x, y); } 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; bool edge[4][100005]; int x, y; int main() { int n, m; cin >> n >> m; string dir; cin >> x >> y >> dir; int dx = (dir[0] == 'D' ? 1 : -1); int dy = (dir[1] == 'R' ? 1 : -1); int tot = 0; long long ans = 1; for (int i = 1; i <= 2 * (n + m - 2); i++) { int a, b; if (x == 1) a = 0, b = y; else if (x == n) a = 1, b = y; else if (y == 1) a = 2, b = x; else a = 3, b = x; if (!edge[a][b]) edge[a][b] = 1, tot++; if (x == 1) dx = 1; if (x == n) dx = -1; if (y == 1) dy = 1; if (y == m) dy = -1; if (tot >= (n + m - 2)) { cout << ans << endl; return 0; } int w = min(dx > 0 ? n - x : x - 1, dy > 0 ? m - y : y - 1); ans += w; x += dx * w; y += dy * w; } 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, tot, a, b, w, f[4][100010], dx, dy; long long ans; char ch[10]; void doit(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 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%d%d%s", &n, &m, &x, &y, ch); ch[0] == 'D' ? dx = 1 : dx = -1; ch[1] == 'R' ? dy = 1 : dy = -1; ans = 1; for (int i = 1; i <= 2 * (n + m - 2); i++) { doit(x, y); if (tot >= n + m - 2) return printf("%I64d", ans), 0; w = min(dx > 0 ? n - x : x - 1, dy > 0 ? m - y : y - 1); ans += w; x += w * dx; y += dy * w; } return printf("-1"), 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<int, char> mp[100005]; int n, m; char getCode(char x) { return x == 'U' || x == 'L'; } int getDistance(int positive, int current, int mymax) { if (positive == 1) return current - 1; return mymax - current; } char invalid(int x, int mymax) { if (x < 1 || x > mymax) return 1; return 0; } int direction[4]; char str[4]; void modify(int currentx, int currenty) { if (invalid(currentx - direction[0], n)) direction[0] *= -1; if (invalid(currenty - direction[1], m)) direction[1] *= -1; } void out() { printf("-1\n"); exit(0); } void check(int v) { for (int j = 1; j <= m; j++) if ((j - 1) % 2 == v && mp[1][j] == 0) out(); for (int j = 1; j <= m; j++) if (abs(j - n) % 2 == v && mp[n][j] == 0) out(); for (int i = 1; i <= n; i++) if (abs(i - 1) % 2 == v && mp[i][1] == 0) out(); for (int i = 1; i <= n; i++) if (abs(i - m) % 2 == v && mp[i][m] == 0) out(); } int main() { int currentx, currenty, startx, starty; scanf("%d%d", &n, &m); scanf("%d%d", &currentx, &currenty); startx = currentx; starty = currenty; scanf("%s", str); for (int i = 0; i < 2; i++) if (str[i] == 'U' || str[i] == 'L') direction[i] = 1; else direction[i] = -1; modify(currentx, currenty); int dirx = direction[0]; int diry = direction[1]; long long sm = 1; int d; long long sv = 0; int z; while (!mp[currentx][currenty]) { z = 1; if (mp[currentx][currenty] == 0) sv = sm; mp[currentx][currenty] = 1; int h = getDistance(direction[0], currentx, n); int v = getDistance(direction[1], currenty, m); d = min(h, v); currentx = currentx - direction[0] * d; currenty = currenty - direction[1] * d; if (h <= v) direction[0] *= -1; if (v <= h) direction[1] *= -1; sm += d; } z = 0; long long sv2 = 0; sm = d; while (!mp[currentx][currenty] || z == 0) { if (currentx == startx && currenty == starty) z = 1; if (mp[currentx][currenty] == 0) sv2 = sm; mp[currentx][currenty] = 1; int h = getDistance(direction[0], currentx, n); int v = getDistance(direction[1], currenty, m); d = min(h, v); currentx = currentx - direction[0] * d; currenty = currenty - direction[1] * d; if (h <= v) direction[0] *= -1; if (v <= h) direction[1] *= -1; sm += d; } check(abs((startx - starty) % 2)); printf("%I64d\n", sv + sv2); }
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
__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 # visited_points[(n, i)] = 0 # if xs % 2 == 0: # for i in range (2, n + 1, 2): # visited_points[(i,1)] = 0 # visited_points[(i,m)] = 0 # else: # for i in range (1, n + 1, 2): # visited_points[(i,1)] = 0 # visited_points[(i,m)] = 0 # # if ys % 2 == 0: # for i in range (2, m + 1, 2): # visited_points[(1, i)] = 0 # visited_points[(n, i)] = 0 # else: # for i in range (1, m + 1, 2): # visited_points[(1, i)] = 0
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; int n, m, x, y, dx, dy; char s[10]; int togo(int x, int dx, int limit) { if (dx == 1) return limit - x; return x - 1; } const int M = 100001; int seenU[M]; int seenD[M]; int seenR[M]; int seenL[M]; int main() { scanf("%d %d", &n, &m); scanf("%d %d %s", &x, &y, s); dx = (s[0] == 'D') ? 1 : -1; dy = (s[1] == 'R') ? 1 : -1; if (!togo(x, dx, n)) dx = -dx; if (!togo(y, dy, m)) dy = -dy; long long res = 1; int left = 0; for (int i = 1; i <= n; i++) left += ((i + 1) % 2 == (x + y) % 2) + ((i + m) % 2 == (x + y) % 2); for (int i = 2; i < m; i++) left += ((i + 1) % 2 == (x + y) % 2) + ((i + n) % 2 == (x + y) % 2); while (1) { if (x == 1) { if (!seenU[y]) left--; seenU[y]++; if (seenU[y] > 2) { puts("-1"); return 0; } } else if (x == n) { if (!seenD[y]) left--; seenD[y]++; if (seenD[y] > 2) { puts("-1"); return 0; } } else if (y == 1) { if (!seenL[x]) left--; seenL[x]++; if (seenL[x] > 2) { puts("-1"); return 0; } } else if (y == m) { if (!seenR[x]) left--; seenR[x]++; if (seenR[x] > 2) { puts("-1"); return 0; } } if (!left) break; int todo = min(togo(x, dx, n), togo(y, dy, m)); res += todo; x += dx * todo; y += dy * todo; if (!togo(x, dx, n)) dx = -dx; if (!togo(y, dy, m)) dy = -dy; } cout << res << 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> 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) { printf("%I64d", 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 x, y, n, m, edge[10][100010], whe, wht, dir, edt = 0, times = 0; long long ans = 0; bool comp = false; char dirc[1]; int main() { cin >> n >> m >> x >> y >> dirc; if (dirc[0] == 'U' && dirc[1] == 'L') dir = 1; else if (dirc[0] == 'U' && dirc[1] == 'R') dir = 2; else if (dirc[0] == 'D' && dirc[1] == 'L') dir = 3; else if (dirc[0] == 'D' && dirc[1] == 'R') dir = 4; memset(edge, 0, sizeof edge); edge[0][0] = 1; ans = 1; while (1) { times++; if (times > 2333333) { comp = false; break; } if (x == 1 && y < m) whe = 1, wht = y; else if (y == m && x < n) whe = 2, wht = x; else if (x == n && y > 1) whe = 3, wht = y; else if (y == 1 && x > 1) whe = 4, wht = x; else whe = 0, wht = 0; if (edge[whe][wht] == 0) { edge[whe][wht] = 1; edt++; if (edt >= (m + n - 2)) { comp = true; break; } } int d; switch (dir) { case 1: d = min(x - 1, y - 1); ans += d; x -= d; y -= d; break; case 2: d = min(x - 1, m - y); ans += d; x -= d; y += d; break; case 3: d = min(n - x, y - 1); ans += d; x += d; y -= d; break; case 4: d = min(n - x, m - y); ans += d; x += d; y += d; break; } switch (whe) { case 1: if (y == 1) dir = 4; else if (dir == 1) dir = 3; else if (dir == 2) dir = 4; break; case 2: if (x == 1) dir = 3; else if (dir == 2) dir = 1; else if (dir == 4) dir = 3; break; case 3: if (y == m) dir = 1; else if (dir == 3) dir = 1; else if (dir == 4) dir = 2; break; case 4: if (x == n) dir = 2; else if (dir == 1) dir = 2; else if (dir == 3) dir = 4; break; } } if (comp == false) cout << -1 << endl; 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; set<pair<int, int> > ss; void lemon() { int n, m, xs, ys; char buf[10]; scanf("%d%d%d%d%s", &n, &m, &xs, &ys, buf); int di, dj, xe = xs, ye = ys; if (buf[0] == 'D') di = 1; else di = -1; if (buf[1] == 'R') dj = 1; else dj = -1; long long final = 0; int cnt = 0, wk = 0; if (xs == 1 || xs == n || ys == 1 || ys == m) cnt++, ss.insert(make_pair(xs, ys)); while (wk < 2000000) { if (xs == 1 && di == -1) di = 1; if (xs == n && di == 1) di = -1; if (ys == 1 && dj == -1) dj = 1; if (ys == m && dj == 1) dj = -1; int x; if (di == 1) x = n - xs; else x = xs - 1; int y; if (dj == 1) y = m - ys; else y = ys - 1; int s = min(x, y); xs += s * di; ys += s * dj; final += s; if (!ss.count(make_pair(xs, ys))) { ss.insert(make_pair(xs, ys)); cnt++; if (cnt == n + m - 2) { final++; cout << final << endl; return; } } wk++; } cout << -1 << endl; } int main() { ios::sync_with_stdio(true); lemon(); 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; unordered_map<int, int> mp[100010]; int n, m, x, y, dx, dy; string s; long long ans; int main() { scanf("%d%d%d%d", &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, cnt = 0; ans = 1; if (x == 1 || x == n || y == 1 || y == m) { tot--; mp[x][y] = 1; } while (1) { cnt++; if (cnt >= 500000) { puts("-1"); return 0; } int dis = 0x3f3f3f3f; 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) { printf("%lld\n", ans); 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; long long convertToNum(string s) { long long val = 0; for (int i = 0; i < (s.size()); i++) val = val * 10 + s[i] - '0'; return val; } char bu[50]; string convertToString(int a) { sprintf(bu, "%d", a); return string(bu); } long long GCD(long long x, long long y) { if (!x) return y; if (!y) return x; if (x == y) return x; if (x < y) return GCD(x, y % x); else return GCD(x % y, y); } long long POW(long long x, long long y, long long Base) { if (!y) return 1; long long u = POW(x, y / 2, Base); u = (u * u) % Base; if (y & 1) return (u * x) % Base; else return u; } void extended_euclid(long long A, long long B, long long &x, long long &y) { if (A == 1 && B == 0) { x = 1; y = 0; return; } if (A < B) extended_euclid(B, A, y, x); else { long long xx, yy; extended_euclid(A % B, B, xx, yy); x = xx; y = yy - (A / B) * xx; } } int m, n; int stx, sty, total, dir, cnt; const int dx[4] = {1, 1, -1, -1}; const int dy[4] = {1, -1, 1, -1}; long long res = 0; long long dd[100003 * 4]; vector<pair<int, int> > ds; int get_node(int u, int v) { return lower_bound(ds.begin(), ds.end(), make_pair(u, v)) - ds.begin(); } void bfs() { dd[get_node(stx, sty)]--; cnt = 1; res = 1; int u = stx, v = sty, newu, newv; while (true) { switch (dir) { case 0: newu = u + n - v; newv = n; if (1 <= newu && newu <= m) { res += n - v; dir = 1; break; } newu = m; newv = v + m - u; if (1 <= newv && newv <= n) { res += m - u; dir = 2; break; } break; case 1: newu = m; newv = v - (m - u); if (1 <= newv && newv <= n) { res += m - u; dir = 3; break; } newu = u + (v - 1); newv = 1; if (1 <= newu && newu <= m) { res += (v - 1); dir = 0; } break; case 2: newu = 1; newv = v + (u - 1); if (1 <= newv && newv <= n) { res += u - 1; dir = 0; break; } newu = u - (n - v); newv = n; if (1 <= newu && newu <= m) { res += (n - v); dir = 3; break; } break; case 3: newu = u - (v - 1); newv = 1; if (1 <= newu && newu <= m) { res += v - 1; dir = 2; break; } newu = 1; newv = v - (u - 1); if (1 <= newv && newv <= n) { res += (u - 1); dir = 1; break; } break; } int new_node = get_node(newu, newv); if (dd[new_node]) { dd[new_node]--; if (dd[new_node] == 2) cnt++; u = newu; v = newv; } else break; if (cnt == total) break; } if (total != cnt) cout << -1 << endl; else cout << res << endl; } int main() { scanf("%d%d", &m, &n); scanf("%d%d", &stx, &sty); string s; cin >> s; if (s == "UL") dir = 3; else if (s == "UR") dir = 2; else if (s == "DL") dir = 1; else if (s == "DR") dir = 0; for (int j = (1); j <= (n); j++) { ds.push_back(make_pair(1, j)); ds.push_back(make_pair(m, j)); } for (int i = (1); i <= (m); i++) { ds.push_back(make_pair(i, 1)); ds.push_back(make_pair(i, n)); } sort(ds.begin(), ds.end()); ds.resize(unique(ds.begin(), ds.end()) - ds.begin()); for (int i = 0; i < (ds.size()); i++) if ((ds[i].first + ds[i].second) % 2 == (stx + sty) % 2) total++; for (int i = 0; i < (ds.size()); i++) dd[i] = 3; bfs(); 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> int n, m, xs, ys; int edge[100002][4]; int totals[4]; int maxs[4]; char rd[6]; int check() { if (ys == 1) { edge[xs][0]++; if (edge[xs][0] == 1) totals[0]++; if (edge[xs][0] == 5) return 2; } if (xs == 1) { edge[ys][1]++; if (edge[ys][1] == 1) totals[1]++; if (edge[ys][1] == 5) return 2; } if (ys == m) { edge[xs][2]++; if (edge[xs][2] == 1) totals[2]++; if (edge[xs][2] == 5) return 2; } if (xs == n) { edge[ys][3]++; if (edge[ys][3] == 1) totals[3]++; if (edge[ys][3] == 5) return 2; } int flg = 1; for (int i = 0; i < 4; i++) if (totals[i] < maxs[i]) flg = 0; return flg; } int main() { scanf("%d%d%d%d", &n, &m, &xs, &ys); scanf("%s", rd); int dr = 0; if (rd[0] == 'D') dr += 2; if (dr == 2 && rd[1] == 'R') dr++; if (dr == 0 && rd[1] == 'L') dr++; dr++; dr %= 4; if ((xs + ys) % 2) { maxs[0] = n / 2; maxs[1] = m / 2; if ((m + n) % 2) { maxs[2] = (n + 1) / 2; maxs[3] = (m + 1) / 2; } else { maxs[2] = n / 2; maxs[3] = m / 2; } } else { maxs[0] = (n + 1) / 2; maxs[1] = (m + 1) / 2; if ((m + n) % 2) { maxs[2] = n / 2; maxs[3] = m / 2; } else { maxs[2] = (n + 1) / 2; maxs[3] = (m + 1) / 2; } } long long sol = 1; check(); while (1) { if (dr == 0) { if (ys + n - xs <= m) { sol += n - xs; ys += n - xs; xs = n; dr = 1; if (ys == m) dr = 2; } else { sol += m - ys; xs += m - ys; ys = m; dr = 3; } } else if (dr == 1) { if (ys + xs - 1 <= m) { sol += xs - 1; ys += xs - 1; xs = 1; dr = 0; if (ys == m) dr = 3; } else { sol += m - ys; xs -= m - ys; ys = m; dr = 2; } } else if (dr == 2) { if (ys - xs + 1 > 0) { sol += xs - 1; ys -= xs - 1; xs = 1; dr = 3; if (ys == 1) dr = 0; } else { sol += ys - 1; xs -= ys - 1; ys = 1; dr = 1; } } else { if (ys + xs - n > 0) { sol += n - xs; ys -= n - xs; xs = n; dr = 2; if (ys == 1) dr = 1; } else { sol += ys - 1; xs += ys - 1; ys = 1; dr = 0; } } int ret = check(); if (ret == 2) { printf("-1\n"); break; } if (ret == 1) { printf("%I64d\n", sol); break; } } 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<long long, pair<long long, long long> >, long long> mp; map<pair<long long, long long>, long long> mp2; long long MAX(long long a, long long b) { return a > b ? a : b; } long long MIN(long long a, long long b) { return a < b ? a : b; } int main() { long long n, m, x, y, sum = 0; cin >> n >> m >> x >> y; char a[3]; scanf("%s", &a); long long pos; if (a[0] == 'U' && a[1] == 'R') pos = 1; if (a[0] == 'U' && a[1] == 'L') pos = 2; if (a[0] == 'D' && a[1] == 'R') pos = 3; if (a[0] == 'D' && a[1] == 'L') pos = 4; mp[make_pair(pos, make_pair(x, y))] = 1; mp2[make_pair(x, y)] = 1; while (1) { long long change; if (pos == 1) { change = min(m - y, x - 1); x -= change; y += change; sum += change; if (x == 1) pos = 3; else pos = 2; } else if (pos == 2) { change = min(y - 1, x - 1); x -= change; y -= change; sum += change; if (x == 1) pos = 4; else pos = 1; } else if (pos == 3) { change = min(n - x, m - y); x += change; y += change; sum += change; if (x == n) pos = 1; else pos = 4; } else if (pos == 4) { change = min(y - 1, n - x); x += change; y -= change; sum += change; if (x == n) pos = 2; else pos = 3; } if (mp[make_pair(pos, make_pair(x, y))] == 1) { cout << -1 << endl; return 0; } mp[make_pair(pos, make_pair(x, y))] = 1; mp2[make_pair(x, y)] = 1; if (mp2.size() == n + m - 2) { cout << sum + 1 << 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; long long n, m, x, y, sum = 1; long long dx = 1, dy = 1; char a, b; long long sum1 = 0; set<pair<long long, long long> > s; void operation() { long long k = 0; while (1) { s.insert(pair<long long, long long>(x, y)); k++; if (s.size() == n + m - 2) { printf("%I64d", sum); exit(0); } long long stepa, stepb; if (dx == -1) { stepa = x - 1; } else stepa = n - x; if (dy == -1) { stepb = y - 1; } else stepb = m - y; long long temp = sum; sum += min(stepa, stepb); if (temp == sum) { sum1++; if (sum1 > (long long)1e6) { printf("-1"); exit(0); } } else sum1 = 0; if (k > (long long)1e6) { printf("-1"); exit(0); } x += dx * (sum - temp); y += dy * (sum - temp); if (x * -dx == 1 || x * dx == n) { dx = -1 * dx; } if (y * -dy == 1 || y * dy == m) { dy = -1 * dy; } } } int main() { scanf("%lld%lld%lld%lld", &n, &m, &x, &y); cin >> a >> b; if (a == 'U') dx = -1; if (b == 'L') dy = -1; operation(); }
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; char s[6]; map<pair<int, int>, bool> vis; map<pair<pair<int, int>, pair<int, int> >, bool> ss; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } bool solve() { vis.clear(); ss.clear(); int sum = 0; for (int i = (1); i < (n + 1); i++) { if ((i + 1) % 2 == (x + y) % 2) ++sum; if ((i + m) % 2 == (x + y) % 2) ++sum; } for (int j = (2); j < (m); j++) { if ((1 + j) % 2 == (x + y) % 2) ++sum; if ((n + j) % 2 == (x + y) % 2) ++sum; } int cnt = 1; long long ans = 1; vis[make_pair(x, y)] = 1; ss[make_pair(make_pair(x, y), make_pair(dx, dy))] = 1; for (;;) { int tx, ty; if (dx > 0) { tx = n - x; } else { tx = x - 1; } if (dy > 0) { ty = m - y; } else { ty = y - 1; } int t = min(tx, ty); x += t * dx; y += t * dy; if (tx < ty) { dx = -dx; } else if (tx == ty) { dx = -dx; dy = -dy; } else { dy = -dy; } ans += t; if (!vis[make_pair(x, y)]) { ++cnt; vis[make_pair(x, y)] = 1; if (cnt >= sum) break; } if (ss[make_pair(make_pair(x, y), make_pair(dx, dy))]) { return 0; } else { ss[make_pair(make_pair(x, y), make_pair(dx, dy))] = 1; } } printf("%lld\n", ans); return 1; } int main() { while (~scanf("%d%d%d%d%s", &n, &m, &x, &y, s)) { int a = n, b = m; if (s[0] == 'U') { a = x; dx = -1; } else { a = n - x + 1; dx = 1; } if (s[1] == 'L') { b = y; dy = -1; } else { b = m - y + 1; dy = 1; } if (!solve()) 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; map<long long, long long> mp[100005]; long long n, m; string s; long long x, y; long long dx, dy; signed main() { scanf("%lld%lld%lld%lld", &n, &m, &x, &y); cin >> s; if (s[0] == 'U') dx = -1; else dx = 1; if (s[1] == 'L') dy = -1; else dy = 1; long long tot = n + m - 2; long long cnt = 0; long long ans = 1; if (x == 1 || x == n || y == 1 || y == m) { tot--; mp[x][y] = 1; } while (1) { cnt++; if (cnt >= 5e5) { puts("-1"); return 0; } long long dis = 1e18; 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) { printf("%lld", ans); 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; const int xt[4] = {1, 1, -1, -1}; const int yt[4] = {1, -1, -1, 1}; struct rec { int x, y, k; } v; int n, m, ans, p1[110000], p2[110000], p3[110000], p4[110000]; long long sum = 0; int f1() { char str[5]; scanf("%s", str); if (str[0] == 'D' && str[1] == 'L') return 1; if (str[0] == 'D' && str[1] == 'R') return 0; if (str[0] == 'U' && str[1] == 'L') return 2; return 3; } rec change(rec v) { if (v.k == 0) { int t = min(n - v.x, m - v.y); v.x += t, v.y += t; sum += t; return v; } if (v.k == 1) { int t = min(n - v.x, v.y - 1); v.x += t; v.y -= t; sum += t; return v; } if (v.k == 2) { int t = min(v.x - 1, v.y - 1); v.x -= t; v.y -= t; sum += t; return v; } int t = min(v.x - 1, m - v.y); v.x -= t; v.y += t; sum += t; return v; } bool work(rec &v) { if (v.x == 1) { p1[v.y]++; if (p1[v.y] == 1) ans--; v.k = 3 - v.k; if (p1[v.y] > 3) return 1; } if (v.x == n) { p2[v.y]++; if (p2[v.y] == 1) ans--; v.k = 3 - v.k; if (p2[v.y] > 3) return 1; } if (v.y == 1) { p3[v.x]++; if (p3[v.x] == 1) ans--; v.k ^= 1; if (p3[v.x] > 3) return 1; } if (v.y == m) { p4[v.x]++; if (p4[v.x] == 1) ans--; v.k ^= 1; if (p4[v.x] > 3) return 1; } return 0; } int main() { scanf("%d%d", &n, &m); scanf("%d%d", &v.x, &v.y); v.k = f1(); if (v.x == 1 && v.y == 1) v.k = 0; if (v.x == n && v.y == 1) v.k = 3; if (v.x == 1 && v.y == m) v.k = 1; if (v.x == n && v.y == m) v.k = 2; for (int i = 1; i <= m; i++) { if ((v.x + v.y) % 2 == (1 + i) % 2) ans++; if ((v.x + v.y) % 2 == (n + i) % 2) ans++; } for (int i = 1; i <= n; i++) { if ((v.x + v.y) % 2 == (1 + i) % 2) ans++; if ((v.x + v.y) % 2 == (m + i) % 2) ans++; } if (v.x == 1) p1[v.y]++, ans--; if (v.x == n) p2[v.y]++, ans--; if (v.y == 1) p3[v.x]++, ans--; if (v.y == m) p4[v.x]++, ans--; while (1) { v = change(v); if (work(v)) break; if (!ans) { cout << sum + 1 << 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; 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() { 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> const long long MAXN = 1e5 + 5; const long long dx[4] = {-1, -1, 1, 1}; const long long dy[4] = {1, -1, -1, 1}; bool vis[5][MAXN], used[5][MAXN][5]; long long n, m, sx, sy; long long zt, cnt, ans; char str[1231]; inline long long getk(long long x, long long y, long long zt) { long long res = INT_MAX; if (zt == 0) res = std::min(x - 1, m - y); if (zt == 1) res = std::min(x - 1, y - 1); if (zt == 2) res = std::min(n - x, y - 1); if (zt == 3) res = std::min(n - x, m - y); return res; } inline bool pd(long long x, long long y) { return (x == 1 && y == 1) || (x == 1 && y == m) || (x == n && y == 1) || (x == n && y == m); } inline bool pdans(long long x) { return x == n + m - 2; return false; } inline long long getqiang(long long x, long long y) { if (x == 1) return 0; if (y == 1) return 1; if (x == n) return 2; if (y == m) return 3; } inline long long chzt(long long x, long long qiang) { if (qiang == 0) { if (x == 0) return 3; if (x == 1) return 2; } if (qiang == 1) { if (x == 1) return 0; if (x == 2) return 3; } if (qiang == 2) { if (x == 3) return 0; if (x == 2) return 1; } if (qiang == 3) { if (x == 0) return 1; if (x == 3) return 2; } } inline long long chzt2(long long x, long long y) { if (x == 1 && y == 1) return 3; if (x == 1 && y == m) return 2; if (x == n && y == 1) return 0; if (x == n && y == m) return 1; } inline void work() { long long ts = 0; long long x = sx, y = sy; long long ans = 1; if (pd(x, y)) { if (x == 1 && y == 1 && !vis[0][1] && !vis[1][1]) vis[0][1] = vis[1][1] = true, cnt += 1; if (x == 1 && y == m && !vis[0][m] && !vis[3][1]) vis[0][m] = vis[3][1] = true, cnt += 1; if (x == n && y == 1 && !vis[1][n] && !vis[2][1]) vis[1][n] = vis[2][1] = true, cnt += 1; if (x == n && y == m && !vis[2][m] && !vis[3][n]) vis[2][m] = vis[3][n] = true, cnt += 1; } else { long long q = getqiang(x, y); if (q == 0 || q == 2) if (!vis[q][y]) vis[q][y] = true, cnt++; if (q == 1 || q == 3) if (!vis[q][x]) vis[q][x] = true, cnt++; } while (true) { long long k = getk(x, y, zt); long long xx = x + dx[zt] * k, yy = y + dy[zt] * k; ans += k; ts++; long long q = getqiang(xx, yy); if (pd(xx, yy)) { zt = chzt2(xx, yy); if (ts == 1 && k == 0) { continue; } bool flag = false, flag2 = false; if (xx == 1 && yy == 1 && vis[0][1] && vis[1][1]) flag2 = true; if (xx == 1 && yy == m && vis[0][m] && vis[3][1]) flag2 = true; if (xx == n && yy == 1 && vis[1][n] && vis[2][1]) flag2 = true; if (xx == n && yy == m && vis[2][m] && vis[3][n]) flag2 = true; if (xx == 1 && yy == 1 && !vis[0][1] && !vis[1][1]) vis[0][1] = vis[1][1] = true, cnt += 1; if (xx == 1 && yy == m && !vis[0][m] && !vis[3][1]) vis[0][m] = vis[3][1] = true, cnt += 1; if (xx == n && yy == 1 && !vis[1][n] && !vis[2][1]) vis[1][n] = vis[2][1] = true, cnt += 1; if (xx == n && yy == m && !vis[2][m] && !vis[3][n]) vis[2][m] = vis[3][n] = true, cnt += 1; if (xx == 1 && yy == 1 && vis[0][2] && vis[1][2]) flag = true; if (xx == 1 && yy == m && vis[0][m - 1] && vis[3][2]) flag = true; if (xx == n && yy == 1 && vis[1][n - 1] && vis[2][2]) flag = true; if (xx == n && yy == m && vis[2][m - 1] && vis[3][n - 1]) flag = true; if (flag) { puts("-1"); exit(0); } if (pdans(cnt)) { printf("%lld\n", ans); exit(0); } if (flag2) { puts("-1"); exit(0); } } else { long long t = zt; zt = chzt(zt, q); assert(zt <= 3); assert(q <= 3); if (ts == 1 && k == 0) { continue; } bool flag = false; if (q == 0 || q == 2) { if (!vis[q][yy]) { vis[q][yy] = true; cnt++; } if (!used[q][yy][t]) used[q][yy][t] = true; else { flag = true; } } if (q == 1 || q == 3) { if (!vis[q][xx]) { vis[q][xx] = true, cnt++; } if (!used[q][xx][t]) used[q][xx][t] = true; else { flag = true; } } if (pdans(cnt)) { printf("%lld\n", ans); exit(0); } if (flag) { puts("-1"); exit(0); } } x = xx; y = yy; } } signed main() { scanf("%lld%lld%lld%lld", &n, &m, &sx, &sy); scanf("%s", str + 1); if (str[1] == 'U' && str[2] == 'L') zt = 1; if (str[1] == 'D' && str[2] == 'L') zt = 2; if (str[1] == 'D' && str[2] == 'R') zt = 3; if (str[1] == 'U' && str[2] == 'R') zt = 0; work(); printf("%lld\n", ans); return 0; }
CPP