input
stringlengths
29
13k
output
stringlengths
9
73.4k
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm. .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# .#.#.#.#. .#.#.#.#.# Note that the top left corner should be drawn by '#'. Constraints * 1 ≤ H ≤ 300 * 1...
while True: a,b = map(int, input().split()) if a==b == 0: break for i in range(a): s = "" for j in range(b): s += "#" if (i+j) % 2 == 0 else "." print(s) print("")
There are N+1 lights. Lights are placed at (0, 0), (1, 0), (2, 0) ... (N, 0). Initially all the lights are on. You want to turn off all of them one after one. You want to follow a special pattern in turning off the lights. You will start at (0, 0). First, you walk to the right most light that is on, turn it off. Th...
# cook your code here T = int(raw_input()) while T: n = int(raw_input()) print (n*(n+1)/2)+n T = T - 1
Chef has a an array A consisting of N elements. He wants to add some elements into the array as per the below mentioned process. After each minute, Chef iterates over the array in order from left to right, and takes every two neighbouring pair of elements, say x and y, he adds a new element x + y in the middle of eleme...
p=10**9+7; def modpow(x,n): if(n==0): return 1; elif(n%2==0): m=modpow(x,n/2); return (m*m)%p; else: m=modpow(x,n/2); return (m*m*x)%p; def modinv(x): return modpow(x,p-2); inv2=modinv(2); mods=[1]*31; mod2s=[1]*31; for i in range(1,31): mods[i]=(mods[i-1]*3)%p; mod2s[i]=(mod2s[i-1]*2); #A:0 in...
Middle Strings Miss Roma has got a new job in a computer agency. To test her skills the manager has appointed her with a small project. She will get a string of any length but of ODD length and what she has to do is finding a center string of length 3 in the original string. For Example: She gets a string 'CANDY' the...
x=raw_input() l=len(x) if l>=3: l=l/2 print x[l-1:l+2] else: print "0"
You might have heard about our new goodie distribution program aka the "Laddu Accrual System". This problem is designed to give you a glimpse of its rules. You can read the page once before attempting the problem if you wish, nonetheless we will be providing all the information needed here itself. Laddu Accrual Syste...
# @author Kilari Teja # LADDU for Inx in xrange(0, int(raw_input().strip())): initParams = raw_input().strip().split(" ") TotalActions = int(initParams[0]) Indian = True if initParams[1] == "INDIAN" else False Points = 0 for ActionIndx in xrange(0, TotalActions): Actions = raw_input().strip().split(" ") Got...
George is getting tired of the decimal number system. He intends to switch and use the septenary (base 7) number system for his future needs. Write a program to help George start his transformation into the septenary number system by taking in a list of decimal numbers and print out the corresponding septenary number...
import sys def numberToBase(n, b): temp='' while n: temp+=str(n % b) n /= b return temp a=map(int,sys.stdin.readline().split()) i=0 while a[i]!=-1: s=numberToBase(a[i],7) s=s[::-1] sys.stdout.write(s+" ") i+=1
The bustling town of Siruseri has just one sports stadium. There are a number of schools, colleges, sports associations, etc. that use this stadium as the venue for their sports events. Anyone interested in using the stadium has to apply to the Manager of the stadium indicating both the starting date (a positive inte...
#Manage maximum events given start date and duration for a case def main(): #f = open('C:\\Users\\GLCR3257\\Desktop\\pyLogics\\test.txt','r') N=int(raw_input()) #print N E=[] for i in range(N): start,duration=map(int,raw_input().split()) E.append([start+duration,start]) E.sort() #print E x=E[0][0] #print...
In a simplified version of a "Mini Metro" game, there is only one subway line, and all the trains go in the same direction. There are n stations on the line, a_i people are waiting for the train at the i-th station at the beginning of the game. The game starts at the beginning of the 0-th hour. At the end of each hour ...
#include <bits/stdc++.h> using namespace std; const int N = 201; const int T = 201; int n, t; long long z; long long a[N], b[N], c[N]; long long pa[N], pb[N]; bool cl1[N][T], cl2[N][T]; long long mr1[N][T], mr2[N][T]; long long dp1[N][T], dp2[N][T]; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >...
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 10...
#include <bits/stdc++.h> const double eps = (1e-9); using namespace std; int dcmp(long double a, long double b) { return fabsl(a - b) <= eps ? 0 : (a > b) ? 1 : -1; } int getBit(int num, int idx) { return ((num >> idx) & 1) == 1; } int setBit1(int num, int idx) { return num | (1 << idx); } long long setBit0(long long...
There is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i. You would like to put together some boxes. Putting together boxes with indices in the segment [l, r...
#include <bits/stdc++.h> using namespace std; int n, q; int nn; int *arra, *arrw; long long int *suml, *sumr, *sum; long long int mod = 1E9 + 7; int mx; long sm; bool TEST = 0; void read() { cin >> n >> q; nn = ceil(log2(n)) * n - 1; if (nn < 5) nn = 5; arra = new int[n]; arrw = new int[n]; suml = new long ...
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected su...
#include <bits/stdc++.h> using namespace std; using namespace std; void enumerateSubmasks(long long m) { for (long long s = m;; s = (s - 1) & m) { if (s == 0) { break; } } } long long mpow(long long a, long long b, long long m) { if (b == 0) return 1; long long x = mpow(a, b / 2, m); x = (x * x)...
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are p players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability. They have just finished the...
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 7, M = 998244353, N = 1e5 + 7; int f[N], inv[N], fi[N]; int INV(int i) { if (i == 1) return 1; return M - (long long)M / i * INV(M % i) % M; } int C(int n, int k) { return (long long)f[n] * fi[k] % M * fi[n - k] % M; } int H(int n, int k) { if (n...
You are given a string of length n. Each character is one of the first p lowercase Latin letters. You are also given a matrix A with binary values of size p × p. This matrix is symmetric (A_{ij} = A_{ji}). A_{ij} = 1 means that the string can have the i-th and j-th letters of Latin alphabet adjacent. Let's call the s...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 7; const int mod = 1e9 + 7; const int maxn = 1e5 + 7; const int maxmsk = (1 << 17) + 7; int n, p, num[maxn], ok[27][27]; int bad[maxmsk], met[27], sum[27]; bool hve[27]; string s; void init() { scanf("%d%d", &n, &p); cin >> s; for (int i = 0; i <...
Polycarp has an array a consisting of n integers. He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains n-1 elements). For each of the next moves he chooses any element with the only restriction: its...
import java.util.ArrayList; import java.util.Scanner; import java.util.Collections; import java.util.Comparator; public class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); int a[] = new int[n]; ...
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
n,x,y = map(int,input().split()) s = input()[-x:] if(y == 0): num = s[:-(y+1)].count('1') else: num = s[:-(y+1)].count('1') + s[-y:].count('1') if(s[-(y+1)] == "0"): num = num + 1 print(num)
The rebels have saved enough gold to launch a full-scale attack. Now the situation is flipped, the rebels will send out the spaceships to attack the Empire bases! The galaxy can be represented as an undirected graph with n planets (nodes) and m wormholes (edges), each connecting two planets. A total of s rebel spaces...
#include <bits/stdc++.h> using namespace std; const int N = 1e2 + 10; const int maxs = 1e5 + 10; const int maxn = 2e3 + 10; const int maxm = 6e3 + 10; const long long INF = 1e14 + 10; const long long INF_CAP = INF; struct spaceship { int x, a, f, p; } sp[maxs]; struct base { int d, g; bool operator<(const base& b...
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: * 'W' — move one cell up; * 'S' — move one cell down; * 'A' — move one cell left; * 'D' — move one cell right. Let Grid(s) be the grid of minimum possibl...
#include <bits/stdc++.h> using namespace std; const int maxs = 200000; const char dbuf[] = "DWAS"; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; char s[maxs + 1]; int xv[maxs + 1]; int yv[maxs + 1]; int lprv[maxs + 1]; int bprv[maxs + 1]; int rprv[maxs + 1]; int tprv[maxs + 1]; int lnxt[maxs + 1]; int...
We are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text. First, let us define several things. We define function F on the array A such that F(i, 1) = A[i] and F(i, m) = A[F(i, m - 1)] for...
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N = 200200; int n, m; int ANS[N]; int g[N]; vector<int> G[N]; int deg[N]; int q[N]; int topQ; int id[N]; vector<int> a[N]; vector<pair<long long, int> > Q[N]; vector<pair<int, int> > b[N]; vector...
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in ...
import sys from sys import argv def extendedEuclideanAlgorithm(old_r, r): negative = False s, old_t = 0, 0 old_s, t = 1, 1 if (r < 0): r = abs(r) negative = True while r > 0: q = old_r // r #MCD: r, old_r = old_r - q * r, r #Coeficiente s: ...
So the Beautiful Regional Contest (BeRC) has come to an end! n students took part in the contest. The final standings are already known: the participant in the i-th place solved p_i problems. Since the participants are primarily sorted by the number of solved problems, then p_1 ≥ p_2 ≥ ... ≥ p_n. Help the jury distrib...
import java.util.*; import java.io.*; public class bfs { static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader...
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers. LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6. O...
#include <bits/stdc++.h> using namespace std; vector<long long> factors; void trial(long long n) { int count; long long ini = n; for (long long d = 2; d * d <= n; d++) { if (n % d == 0) { ini = n; while (n % d == 0) { n /= d; } long long s = ini / n; factors.push_back(s);...
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree? Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wan...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; inline long long add(long long a, long long b) { a += b; if (a >= mod) a -= mod; return a; } inline long long sub(long long a, long long b) { a -= b; if (a < 0) a += mod; return a; } inline long long mul(long long a, long long b) { ret...
You are given the array a consisting of n elements and the integer k ≤ n. You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: * Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ...
#include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; const unsigned long long nmax = 200002; unsigned long long n, k, a[nmax], s[nmax], t[nmax], c[nmax], r = UINT64_MAX, A, B; int main() { scanf("%llu%llu", &n, &k); for (unsigned ...
Phoenix is trying to take a photo of his n friends with labels 1, 2, ..., n who are lined up in a row in a special order. But before he can take the photo, his friends get distracted by a duck and mess up their order. Now, Phoenix must restore the order but he doesn't remember completely! He only remembers that the i-...
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; long long n, m, t, k; int pos[200005], tmp[200005]; pair<pair<int, int>, int> a[200005]; class dsu { public: int fa[200005]; void init(int n) { for (int i = 0; i <= n; i++) { fa[i] = i; } } int find(int u) { while (u != fa[...
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes... Let's define a Rooted Dead Bush (RDB) of level n ...
import java.util.*; import java.io.*; public class CP{ public static OutputStream out=new BufferedOutputStream(System.out); static Scanner sc=new Scanner(System.in); static long mod=1000000007l; //nl-->neew line; //l-->line; //arp-->array print; //arpnl-->array print new line public static void nl(Object ...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Consider a permutation p of length ...
import java.util.*; import java.math.*; public class Sample { static long m = (long)Math.pow(10,9)+7; static long f(long x) { if(x==0) return 1; if(x<3) return x; long a = 2; for(long i=3; i<=x; i++) { a*=i; a%=m; } return a; } static long p(long x) { long a = 1; for(int i=1; i<x; i+...
In the Land of Fire there are n villages and n-1 bidirectional road, and there is a path between any pair of villages by roads. There are only two types of roads: stone ones and sand ones. Since the Land of Fire is constantly renovating, every morning workers choose a single road and flip its type (so it becomes a ston...
#include <bits/stdc++.h> using namespace std; int n, m, nex[2000000], hea[2000000], wen[2000000], val[2000000], aid[2000000], root2, root1, len, maxx; struct segment_tree { int a[2000000][2], lazy[2000000], fa[1000000], dep[1000000], in[1000000], out[1000000], m; void pushdown(int k) { if (!lazy[k]) r...
You are given a string s consisting of n characters. These characters are among the first k lowercase letters of the Latin alphabet. You have to perform n operations with the string. During the i-th operation, you take the character that initially occupied the i-th position, and perform one of the following actions wi...
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "e:/Codes/lib/prettyprint.hpp" #else #define debug(...) #endif int32_t main() { ios::sync_with_stdio(0); cout.tie(0); cin.tie(0); int tc; cin >> tc; while (tc--) { int n, k; string s; cin >> n >> k >> s; vector<string...
A smile house is created to raise the mood. It has n rooms. Some of the rooms are connected by doors. For each two rooms (number i and j), which are connected by a door, Petya knows their value cij — the value which is being added to his mood when he moves from room i to room j. Petya wondered whether he can raise his...
#include <bits/stdc++.h> using namespace std; int gi() { int w = 0; bool q = 1; char c = getchar(); while ((c < '0' || c > '9') && c != '-') c = getchar(); if (c == '-') q = 0, c = getchar(); while (c >= '0' && c <= '9') w = w * 10 + c - '0', c = getchar(); return q ? w : -w; } const int N = 510; long lon...
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r ...
# include <bits/stdc++.h> using namespace std; pair<int, int> a[200010]; int calc(int l, int r, int x, int y) { if (x == l && y == r) { return 0; } int t = ((x + y) % 2) ? 0 : 1; if(x - l == y - r){ return t * (x - l); } else { if((l + r) % 2 == 0){ return (x...
Vasya has a very beautiful country garden that can be represented as an n × m rectangular field divided into n·m squares. One beautiful day Vasya remembered that he needs to pave roads between k important squares that contain buildings. To pave a road, he can cover some squares of his garden with concrete. For each ga...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; const long long MOD = 1000000007; const long long INF = 0x3f3f3f3f; int val[111][111]; int n, m, k; vector<pair<int, int> > pos; int ddist[111][111], way[10][10], dist[211][10]; int used[111][111]; pair<int, int> pre[211][1 << 8]; int dp[211][1 << 8...
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheape...
import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.util.*; public class B { Scanner sc = new Scanner(System.in); void run() { int n = sc.nextInt(), k = sc.nextInt(); int[] cs = new int[n], ts = new int[n]; for (int i = 0; i < n; i++) { cs[i] = sc.nextInt() * 2...
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner. Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class D { final int MOD = 1000000007; final double eps = 1e-12; public D () throws IOException { char [] S = sc.nextChars(); char [] T = sc.nextChars(); start(); int [] C = ne...
Valera came to Japan and bought many robots for his research. He's already at the airport, the plane will fly very soon and Valera urgently needs to bring all robots to the luggage compartment. The robots are self-propelled (they can potentially move on their own), some of them even have compartments to carry other ro...
#include <bits/stdc++.h> using namespace std; #pragma comment(linker, "/STACK:200000000") const double EPS = 1E-9; const int INF = 1000000000; const long long INF64 = (long long)1E18; const double PI = 3.1415926535897932384626433832795; struct robot { int c, f, l; }; int d; inline bool operator<(const robot &a, const...
The court wizard Zigzag wants to become a famous mathematician. For that, he needs his own theorem, like the Cauchy theorem, or his sum, like the Minkowski sum. But most of all he wants to have his sequence, like the Fibonacci sequence, and his function, like the Euler's totient function. The Zigag's sequence with the...
#include <bits/stdc++.h> using namespace std; void swap(int &x, int &y) { int t = x; x = y; y = t; } int max(int x, int y) { return x > y ? x : y; } int min(int x, int y) { return x < y ? x : y; } const int inf = 0x3F3F3F3F; const int M = 100000 + 5; int T, cas; int n, m; long long a, sum[M << 2][5][11], s[5][M];...
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct po...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid l...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:32000000") using namespace std; const int MAX = 200000; const int INF = 100000000; const int MOD = 1000000007; const double EPS = 1E-7; const int IT = 10024; map<int, vector<pair<int, int> > > r; map<int, vector<pair<int, int> > > c; map<int, int> R; map<int, int...
Friends Alex and Bob live in Bertown. In this town there are n crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number n. One day Alex and Bob had a big quarrel, and they refused to see each other. It occ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 500 + 17, inf = 1e9 + 17; int n, m, dp[MAXN][MAXN]; pair<int, int> par[MAXN][MAXN]; vector<int> adj[MAXN], ans1, ans2; void bfs() { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) dp[i][j] = inf; dp[1][n] = 0; queue<pair<int, int> > q; ...
You are given two permutations p and q, consisting of n elements, and m queries of the form: l1, r1, l2, r2 (l1 ≤ r1; l2 ≤ r2). The response for the query is the number of such integers from 1 to n, that their position in the first permutation is in segment [l1, r1] (borders included), and position in the second permut...
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; struct tnode { int sum; tnode *lson, *rson; tnode(int x = 0) { sum = x; lson = rson = NULL; } }; void pushup(tnode* cur) { cur->sum = (cur->lson == NULL ? 0 : cur->lson->sum) + (cur->rson == NULL ? 0 : cur->rson->sum...
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ...
# mafia N=int(input()) a=list(map(int,input().split())) def isok(X): sums=0 for num in a: if X<num: return False sums+=max(0,X-num) if sums>=X: return True return False l=0 r=10**12 #l -- case_impossible #r --case_possible while r-l>1: m=(l+r)//2 ...
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox...
#include <bits/stdc++.h> using namespace std; bool isPrime(long long int n) { if (n <= 1) return 0; if (n <= 3) return 1; if (n % 2 == 0 || n % 3 == 0) return 0; for (long long int i = 5; i * i <= n; i += 6) if (n % i == 0 || n % (i + 2) == 0) return 0; return 1; } long long int gcd(long long int a, long ...
There are three arrays a, b and c. Each of them consists of n integers. SmallY wants to find three integers u, v, w (0 ≤ u, v, w ≤ n) such that the following condition holds: each number that appears in the union of a, b and c, appears either in the first u elements of a, or in the first v elements of b, or in the firs...
#include <bits/stdc++.h> using namespace std; struct Tnode { int x, y, z; } doing[1000050]; struct Type { int pos, val, size; Type *father, *son[2]; Type() {} Type(Type *f, int p, int v, int s) { pos = p; val = v; size = s; father = f; son[0] = son[1] = 0; } } memory[1000050], *root; str...
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog...
#include <bits/stdc++.h> using namespace std; int xx[4] = {0, 0, 1, -1}; int yy[4] = {1, -1, 0, 0}; int n, m; int a[int(1048576 + 2000)], b[int(1048576 + 2000)]; long long f[30][2]; long long res = 0; void build(int l, int r, int h) { if (l == r) return; int mid = (l + r) / 2; build(l, mid, h + 1); build(mid + ...
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have a...
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; /** * * @author sousnake */ public class E { static int max = 50...
Roma found a new character in the game "World of Darkraft - 2". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters. The character can equip himself with k distinct types of items. Power of each item depends on its level (positive integer number). In...
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; const int maxk = 105; vector<pair<int, long double> > f, tmp; long double g[maxn], t[maxn]; long double ans; int n, k; int main() { scanf("%d%d", &n, &k); f.push_back(make_pair(1, 1.0)); for (int i = 0; i < n; ++i) { tmp.clear(); for (...
A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF). During the battle, every second the monster's HP decrease by max(0, ATKY - DEFM), while Yang's HP decreases by max(0,...
# HEY STALKER hp_y, at_y, df_y = map(int, input().split()) hp_m, at_m, df_m = map(int, input().split()) cst_hp, cst_at, cst_df = map(int, input().split()) ans = 2e18 for ati in range(201): for dfi in range(201): if ati + at_y > df_m: k = hp_m // ((at_y + ati) - df_m) if hp_m % ((at_y...
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0. There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After app...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:256000000") using namespace std; const int N = 305; int c[N], l[N]; int gcd(int a, int b) { while (b) { a %= b; swap(a, b); } return a; } long long rrand() { long long a = rand(); long long b = rand(); return a + (b >> 16); } int main() { in...
Tavas is a cheerleader in the new sports competition named "Pashmaks". <image> This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (the...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 100; struct Point { long long x, y; bool operator<(const Point &p) const { if (x != p.x) return x > p.x; else return y > p.y; } } pt[maxn]; int stk[maxn], stnum; set<pair<long long, long long> > has; bool check(Point a, Point...
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: 1. They are equal. 2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2...
def equals(a, b): if (a == b): return True len_a, len_b = len(a), len(b) if (len_a & 1 or len_b & 1): return False if (len_a == 1): return False as1 = a[0:len_a//2] as2 = a[len_a//2:(len_a//2)*2] bs1 = b[:len_b//2] bs2 = b[len_b//2:(len_b//2)*2] return (equals(as1, bs2) and equals...
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions. The attitude of each of the companions to the hero is an integer. Initially, the attitude of each o...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:134217728") using namespace std; const long long MOD = 1000000000 + 7; const long long MAXN = 100000 + 100; const long long MAGIC = 123123123; const double PI = 4 * atan(1.); const double EPS = 1E-7; struct cmp_for_set { bool operator()(const int& a, const int&...
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres. In the bookshop, Jack decides to buy two books of different genres. Based on the genre of books on sale in the shop, find the nu...
import fileinput from collections import Counter def get_input(): inp = fileinput.input() n, m = map(lambda a: int(a), inp.readline().strip().split()) c = Counter(inp.readline().strip().split()) return n, m, c def main(): n, m, c = get_input() vals = c.values() s = 0 for i in xrange(0...
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
#for fun #print int(pow(5,input(),100)) cin = input() print 25
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them. Input The first line of the input contains a single integer N (3 ≤ N ≤ 10). Th...
#include <bits/stdc++.h> using namespace std; int main() { int maxn = 999999999; int m[105][105]; int n; cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) m[i][j] = maxn; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> m[i][j]; for (int k = 0; k < n; k++) for (in...
In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away fro...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); const double eps = 1e-6; struct pos { double x, y; }; struct vec { double x, y; }; struct seg { pos a, b; }; long long sign(double x) { return x < -eps ? -1 : x > eps ? 1 : 0; } double dot(vec a, vec b) { return a.x * b.x + a.y * b.y; } d...
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1. Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights o...
#include <bits/stdc++.h> using namespace std; long long n, k; long long a[100010]; long long b[100010]; long long BZ[100010][40]; long long Min[100010][40]; long long Sum[100010][40]; int main() { scanf("%lld%lld", &n, &k); for (long long i = 0; i < n; ++i) scanf("%lld", &BZ[i][0]); for (long long i = 0; i < n; +...
A tree is a connected graph without cycles. Two trees, consisting of n vertices each, are called isomorphic if there exists a permutation p: {1, ..., n} → {1, ..., n} such that the edge (u, v) is present in the first tree if and only if the edge (pu, pv) is present in the second tree. Vertex of the tree is called int...
#include <bits/stdc++.h> using namespace std; int fac[1010], inv[1010], mod; int ksm(int a, int b = mod - 2) { int r = 1; for (; b; b >>= 1) { if (b & 1) r = 1ll * r * a % mod; a = 1ll * a * a % mod; } return r; } int C(int a, int b) { int r = inv[b]; for (b--; b >= 0; b--) r = 1ll * r * (a - b) % m...
Sasha reaches the work by car. It takes exactly k minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the i-th song Sasha gets a pleasure which equals ai. The i-th song lasts for ti minutes. Before the beginning of his way Sasha turns on some song x and then he listens...
#include <bits/stdc++.h> using namespace std; const int N = 400000; int a[N], t[N], type[N], us[N]; int main() { ios::sync_with_stdio(0); int n, w, k; cin >> n >> w >> k; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> t[i]; } int r = -1; int curr_time = 0; ...
Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and ther...
#include <bits/stdc++.h> using namespace std; int n, m; int data[2][100010], t[100010], num[100010]; queue<pair<int, int> > que; int dis(int x, int y) { return abs(data[0][x] - data[1][y]); } int main() { scanf("%d%d%*d%*d", &n, &m); for (int i = 0; i < n; i++) scanf("%d", &data[0][i]); for (int i = 0; i < m; i++...
After hard work Igor decided to have some rest. He decided to have a snail. He bought an aquarium with a slippery tree trunk in the center, and put a snail named Julia into the aquarium. Igor noticed that sometimes Julia wants to climb onto the trunk, but can't do it because the trunk is too slippery. To help the sna...
#include <bits/stdc++.h> using namespace std; const int MAXN = 111111; const int SQ = 200; int n, m; vector<int> go[MAXN]; vector<pair<int, int> > qq[MAXN], gg[MAXN]; int ans[MAXN], a[MAXN]; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { int l, r; scanf("%d%d", &l, &r); --l; --r; ...
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it! Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from le...
#include <bits/stdc++.h> using namespace std; const int N = 1500 + 10; char s[N]; int n, q, a[N]; int memo[N][30]; int solve(int x, int c) { int j = 0, miss = 0, ret = 0; for (int i = 1; i <= n; i++) { if (a[i] != c && j < i) miss++, j = i; while (j + 1 <= n && (a[j + 1] == c || miss + 1 <= x)) { j++;...
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle n × m in size divi...
#include <bits/stdc++.h> using namespace std; const int maxn = 55; int n, m, k; set<set<int> > ha[maxn][maxn]; string mat[maxn]; int stran[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; int br, bc; int er, ec; int dis(int r1, int c1, int r2, int c2) { return abs(r1 - r2) + abs(c1 - c2); } struct node { int r, c; string s; i...
In one well-known algorithm of finding the k-th order statistics we should divide all elements into groups of five consecutive elements and find the median of each five. A median is called the middle element of a sorted array (it's the third largest element for a group of five). To increase the algorithm's performance ...
#include <bits/stdc++.h> using namespace std; struct Node { int cnt = 1, key, prior; long long sum[5] = {}; Node *left = NULL, *right = NULL; }; typedef Node *PNode; Node nodes[111111]; int pri[111111]; int nodeCount = 0; inline int cnt(PNode &v) { return v ? v->cnt : 0; } inline void update(PNode &v) { if (v) ...
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
#include <bits/stdc++.h> using namespace std; char str[100010]; bool line[27][27]; bool p[27], vis[27]; int in[27], out[27]; string ans; bool dfs(int value); int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%s", str); int len = strlen(str); for (int i = 0; i < len - 1; i++) { ...
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right. You perform a sequence of operations on this set of p...
import java.io.* ; import java.util.* ; import java.text.* ; import java.math.* ; import static java.lang.Math.min ; import static java.lang.Math.max ; public class Codeshefcode{ public static void main(String[] args) throws IOException{ Solver Machine = new Solver() ; Machine.Solve() ; Machine.Finish() ; // n...
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f...
#include <bits/stdc++.h> using namespace std; int a, b, temp, ans; int main() { cin >> a >> b; temp = abs(b - a); if (temp % 2 == 0) { for (int i = 1; i <= temp / 2; i++) ans += i; cout << ans * 2; } else { for (int i = 1; i <= temp / 2 + 1; i++) { ans += i; } ans *= 2; ans -= temp...
Princess Heidi decided to give orders to all her K Rebel ship commanders in person. Unfortunately, she is currently travelling through hyperspace, and will leave it only at N specific moments t1, t2, ..., tN. The meetings with commanders must therefore start and stop at those times. Namely, each commander will board he...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; i...
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>. In one step you can mov...
import re import math import decimal import bisect def read(): return input().strip() n = int(read()) ps = [0 for i in range(1, n+1)] nadd = 10 for x in sorted([int(_) for _ in read().split()]): ps[x-1] = nadd nadd += 10 nadd = 15 for i, p in enumerate(ps): if p == 0: ps[i] = nadd nadd += 10 # print(ps) swap...
Garfield the cat likes candies A LOT. He always keeps a huge stock of it at his home. Today John, his owner, brought home three types of candies. He brought A pieces of Red candy, B pieces of Green candy and C pieces of Blue candy. Garfield is really happy. But the problem is that John won’t allow him to eat all of it ...
t = int(raw_input()) for _ in range(t): n, a, b, c = map(int, raw_input().split()) ways = 0 for i in range(a + 1): for j in range(min(n - i, b) + 1): if(n - i - j < 0): break else: ways += min(n - i - j, c) + 1 print(ways)
Bob is travelling from one city to another. In his way, he sees many other cities pass by. What he does instead of learning the full names of the cities, he learns just the first character of the cities. For example, if he passes by "bhopal", he will just remember the 'b'. Given the list of N cities that come in h...
def fun(): n=input() l=[] for i in range(n): z=raw_input() l.append(z[0]) if len(l)==len(set(l)): return("YES") else: return("NO") a=input() for i in range(a): print(fun())
Chandan gave his son a cube with side N. The N X N X N cube is made up of small 1 X 1 X 1 cubes. Chandan's son is extremely notorious just like him. So he dropped the cube inside a tank filled with Coke. The cube got totally immersed in that tank. His son was somehow able to take out the cube from the tank. But soone...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t=input(); while t > 0 : c=input() if c!=1: print (c*c*c)-(c-2)*(c-2)*(c-2) t=t-1 else: print 1 t=t-1
Leonard has decided to quit living with Dr. Sheldon Cooper and has started to live with Penny. Yes, you read it right. (And you read it here for the first time!) He is fed up of Sheldon, after all. Since, Sheldon no more has Leonard to drive him all around the city for various things, he's feeling a lot uneasy so he de...
t = int(raw_input()) for i in range(t): a, b = map(int, raw_input().split()) for j in range(b): m, n = map(int, raw_input().split()) print(a-1)
There is a frog known as "CHAMELEON" because he has a special feature to change its body's color similar to stone's color on which he sits. There are N colorful stones lying in a row, but of only 1 to 100 different colors. Frog can hopp on another stone if the stone has same color as its body or (i-1)th stone if it is ...
from collections import deque class Frog(): def __init__(self,n,stones): self.colors=[[] for _ in xrange(101)] self.N = n self.stones = stones for i,c in enumerate(stones): self.colors[c].append(i) self.l=[0]*self.N def bfsThrough(self,S,M,E): s1 = self.bfs(S,M) if s1==-1: return s1 ...
Sherlock Holmes loves mind palaces! We all know that. A mind palace, according to Mr. Holmes is something that lets him retrieve a given memory in the least time posible. For this, he structures his mind palace in a very special way. Let a NxM Matrix denote the mind palace of Mr. Holmes. For fast retrieval he keeps ea...
N, M = map(int, raw_input().split()) memory = {} for i in range(N): x = map(int, raw_input().split()) for index, elem in enumerate(x): memory[elem] = str(i) + ' ' + str(index) Q = int(raw_input()) for k in range(Q): q = int(raw_input()) if q in memory: print memory[q] else: print '-1 -1'
Panda has a thing for palindromes. Hence he was a given a problem by his master. The master will give Panda an array of strings S having N strings. Now Panda has to select the Palin Pairs from the given strings . A Palin Pair is defined as : (i,j) is a Palin Pair if Si = reverse(Sj) and i < j Panda wants to k...
from sys import stdin t = stdin.readline() di = {} a = stdin.readlines() ans = 0 for i in a: cur = i.strip() x=cur cur = list(cur) cur.reverse() cur = ''.join(cur) ans+=di.get(cur,0) di[x] = di.get(x,0)+1 print ans
Given a string, S, we define some operations on the string as follows: a. reverse(S) denotes the string obtained by reversing string S. E.g.: reverse("abc") = "cba" b. shuffle(S) denotes any string that's a permutation of string S. E.g.: shuffle("god") ∈ ['god', 'gdo', 'ogd', 'odg', 'dgo', 'dog'] c. merge(S1,S2) den...
from collections import defaultdict def solve(S): # Reverse S S = S[::-1] # Count each character in S. count = defaultdict(int) for c in S: count[c] += 1 need = {} for c in count: need[c] = count[c] / 2 solution = [] i = 0 while len(solution) < len(S) / 2: ...
You are given a square matrix of size n (it will be an odd integer). Rows are indexed 0 to n-1 from top to bottom and columns are indexed 0 to n-1 form left to right. Matrix consists of only '*' and '.'. '*' appears only once in the matrix while all other positions are occupied by '.' Your task is to convert this matr...
t=int(input()) while t: t-=1 o=n=int(input()) i=i1=j=-1 while n: n-=1 i1+=1 s=raw_input() if j==-1 and '*' in s: j=s.index('*') i=i1 print abs((o/2)-i)+abs((o/2)-j)
Given integer n, find length of n! (which is factorial of n) excluding trailing zeros. Input The first line of the standard input contains one integer t (t<10001) which is the number of test cases. In each of the next t lines there is number n (0 ≤ n ≤ 5*10^9). Output For each test, print the length of n! (which i...
import math for _ in xrange(int(raw_input())): n = int(raw_input()) #m = int(math.log10((n/math.exp(1.0))**n*math.sqrt(2*math.pi*n)*math.exp(1/12.0/n))) m = int(n*math.log10(n/math.e) + 0.5*(math.log10(2*math.pi*n))) a = n/5 z = n//5 i=2 while a > 1: a = n/(5**i) z += n//(5**i) i += 1 print m-z+1
We have N integers. The i-th number is A_i. \\{A_i\\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N. \\{A_i\\} is said to be setwise coprime when \\{A_i\\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1. Determine if \\{A_i\\} is pairwise coprime, setw...
N = int(input()) A = list(map(int,input().split())) A = sorted(A,reverse = True) prime = [0] * (10**6+1) eratos = [True] * (A[0] + 1) D = [0] * (A[0]+1) D[1] = 1 for i in range(2,A[0] + 1): if not eratos[i]: continue else: for j in range(i,A[0] + 1,i): if not D[j]: D[j] = i if j!=i: ...
Print the circumference of a circle of radius R. Constraints * 1 \leq R \leq 100 * All values in input are integers. Input Input is given from Standard Input in the following format: R Output Print the circumference of the circle. Your output is considered correct if and only if its absolute or relative error ...
R=int(input()) print(R*6.2831853)
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vert...
#include <bits/stdc++.h> using namespace std; int n, u, v; int dist[2][100000]; vector<vector<int> > g; void dfs(int v, int prev, int d, int f) { dist[f][v] = d; for (auto e : g[v]) if (e != prev) dfs(e, v, d + 1, f); } int main() { cin >> n >> u >> v; --u, --v; g.resize(n); for (int i = 1; i < n; ++i) { ...
You are given a sequence of length N: A_1, A_2, ..., A_N. For each integer i between 1 and N (inclusive), answer the following question: * Find the maximum value among the N-1 elements other than A_i in the sequence. Constraints * 2 \leq N \leq 200000 * 1 \leq A_i \leq 200000 * All values in input are integers. Inp...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int max = 0; int max_num =0; int max2 = 0; int n = sc.nextInt(); for(int i=0; i<n; i++) { int a = sc.nextInt(); if(a>max) { max = a; ...
There are N cubes stacked vertically on a desk. You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is `0`, and blue if that character is `1`. You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent...
#include <bits/stdc++.h> using namespace std; int main() { string S; cin >> S; int c0,c1 =0; for(char i: S) { if(i == '0') ++c0; else ++c1; } cout << 2 * min(c0,c1) << endl; }
There are N children, numbered 1, 2, ..., N. Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets. For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy ...
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int x = scanner.nextInt(); List<Integer> lis...
An elementary school student Takahashi has come to a variety store. He has two coins, A-yen and B-yen coins (yen is the currency of Japan), and wants to buy a toy that costs C yen. Can he buy it? Note that he lives in Takahashi Kingdom, and may have coins that do not exist in Japan. Constraints * All input values a...
import java.util.Scanner; public class Main { public static void main(String[] args) { final Scanner sc = new Scanner(System.in); int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt(); if(a+b < c) { System.out.println("No"); } else { System.out.println("Yes"); } } }
We have a string s consisting of lowercase English letters. Snuke is partitioning s into some number of non-empty substrings. Let the subtrings obtained be s_1, s_2, ..., s_N from left to right. (Here, s = s_1 + s_2 + ... + s_N holds.) Snuke wants to satisfy the following condition: * For each i (1 \leq i \leq N), it ...
#include <bits/stdc++.h> using namespace std; char ax[200005]; int dp[200005]; int len; map<int,int> m; int main() { scanf("%s",ax); int i,j,a,b,now=0; len = strlen(ax); m[0]=len; for(i=len-1;i>=0;i--){ now ^= (1<<(ax[i]-'a')); dp[i]=len-i; if(m.count(now))dp[i]=min(dp[i],dp...
Takahashi is locked within a building. This building consists of H×W rooms, arranged in H rows and W columns. We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= `#`, the room is locked and cannot be entered; if A_{i,j}= `.`, the r...
from collections import deque h,w,k = map(int,input().split()) a = [] for i in range(h): b = input() tmp = [] for j in range(w): tmp.append(b[j]) if b[j] == "S": sx = i sy = j a.append(tmp) ma = [[0]*w for i in range(h)] def dfs(x,y,z): if ma[x][y] == 1: return if z>k: return m...
You are given a string S consisting of letters `b`, `d`, `p` and `q`. Determine whether S is a mirror string. Here, a mirror string is a string S such that the following sequence of operations on S results in the same string S: 1. Reverse the order of the characters in S. 2. Replace each occurrence of `b` by `d`, `d...
#include<iostream> #include<string> using namespace std; char ch[256]; int main() { ch['b']='d'; ch['d']='b'; ch['q']='p'; ch['p']='q'; string s; cin>>s; int i; for(i=0;i<s.size();i++) { if(ch[s[i]]!=s[s.size()-1-i]) goto br; } printf("Yes\n"); return 0; br:; printf("No\n"); return 0; }
Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light. Three mirrors of length N are set so that they form an equilateral triangle. Let the vertices of the triangle be a, b and c. Inside the triangle, the rifle is placed at the point p on segment ab such that ap ...
"""B - Mysterious Light""" N,X=(int(i) for i in input().split()) def MysteriousLight(tmp,rem): while rem: tmp, rem= rem,tmp%rem return tmp print(3*(N-MysteriousLight(N,X)))
One day, Taro received a strange email with only the number "519345213244" in the text. The email was from my cousin, who was 10 years older than me, so when I called and asked, "Oh, I sent it with a pocket bell because I was in a hurry. It's convenient. Nice to meet you!" I got it. You know this cousin, who is always ...
#include <iostream> #include <string> using namespace std; int main(){ string str; char code[6][5] = {{'a', 'b', 'c', 'd', 'e'}, {'f', 'g', 'h', 'i', 'j'}, {'k', 'l', 'm', 'n', 'o'}, {'p', 'q', 'r', 's', 't'}, {'u', 'v', 'w', 'x',...
There was a large mansion surrounded by high walls. The owner of the mansion loved cats so much that he always prepared delicious food for the occasional cats. The hungry cats jumped over the high walls and rushed straight to the rice that was everywhere in the mansion. One day the husband found some cats lying down i...
#include<bits/stdc++.h> #define EQ(a,b) (abs((a)-(b)) < EPS) #define rep(i,n) for(int i=0;i<(int)(n);i++) #define fs first #define sc second #define pb push_back #define sz size() #define all(a) (a).begin(),(a).end() using namespace std; typedef long double D; typedef complex<D> P; typedef pair<P,P> L; typedef vector<...
problem You are looking for a constellation in a picture of the starry sky. The photo always contains exactly one figure with the same shape, orientation, and size as the constellation you are looking for. However, there is a possibility that extra stars are shown in the photograph other than the stars that make up th...
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> P; P f(P a, P b) { return make_pair(b.first - a.first, b.second - a.second); } int main() { int m, n; while (true) { cin >> m; if (m == 0) break; vector<P> seiza(m); for (int i = 0; i < m; ++i) cin >> seiza[i].first >> seiza[i].secon...
Long long ago, there was a thief. Looking for treasures, he was running about all over the world. One day, he heard a rumor that there were islands that had large amount of treasures, so he decided to head for there. Finally he found n islands that had treasures and one island that had nothing. Most of islands had sea...
#include <iostream> //“üo—Í #include <string> //•¶Žš—ñ #include <vector> //“®“I”z—ñ #include <sstream> //•¶Žš—ñƒtƒH[ƒ}ƒbƒg using namespace std; int main(){ int n, num; cin >> n; while(1){ if(n == 0){ break; } vector<int> vec1, vec2; for(int i=0;i<n;i++){ cin >> num; vec1.push_back(num); cin >...
Once upon a time, there was a king who loved beautiful costumes very much. The king had a special cocoon bed to make excellent cloth of silk. The cocoon bed had 16 small square rooms, forming a 4 × 4 lattice, for 16 silkworms. The cocoon bed can be depicted as follows: <image> The cocoon bed can be divided into 10 re...
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cstring> using namespace std; int lat[5][5]; vector<vector<int>> bx = { {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}, {0, 0, 0, 0, 0}, {1, 1, 1, 1, 1}, {2, 2, 2...
Let us consider sets of positive integers less than or equal to n. Note that all elements of a set are different. Also note that the order of elements doesn't matter, that is, both {3, 5, 9} and {5, 9, 3} mean the same set. Specifying the number of set elements and their sum to be k and s, respectively, sets satisfyin...
#include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<n;i++) using namespace std; int dp[30][20][200]; int main() { int N, K, S; while (scanf("%d%d%d", &N, &K, &S), N) { memset(dp, 0, sizeof(dp)); for (int i = 0; i <= N; i++)dp[i][0][0] = 1; for (int i = 1; i <= N; i++) { for (int j = 1; j <= K; j++) { ...
Background The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves money as much as programming. Yu-kun visited the island where treasures sleep to make money today. Yu-kun has obtained a map of the treasure in advanc...
#include <bits/stdc++.h> #define INF 1000000007 using namespace std; typedef long long ll; typedef pair<int,int> P; struct uftree{ int par[25]; int rank[25]; uftree(){ } void init(int n){ for(int i=0;i<n;i++){ par[i]=i; rank[i]=0; } } int find(int x){ if(par[x]==x)return x; return par[x]=find(par[...
Sarah is a girl who likes reading books. One day, she wondered about the relationship of a family in a mystery novel. The story said, * B is A’s father’s brother’s son, and * C is B’s aunt. Then she asked herself, “So how many degrees of kinship are there between A and C?” There are two possible relationships bet...
#include <algorithm> #include <cassert> #include <climits> #include <iostream> #include <string> #include <vector> using namespace std; using namespace std::placeholders; enum Relation { FATHER, MOTHER, SON, DAUGHTER, HUSBAND, WIFE, BROTHER, SISTER, GRANDFATHER, GRANDMOTHER, GRANDSON, GRANDDAUGHTER, UNCLE, AUNT, N...
Differential pulse code modulation is one of the compression methods mainly used when compressing audio signals. The audio signal is treated as an integer sequence (impulse sequence) on the computer. The integer sequence is a sample of the input signal at regular time intervals and the amplitude recorded. In general, ...
#include <iostream> #include <vector> #include <algorithm> #define IF 1300500010 #define lengthof(x) (sizeof(x) / sizeof(*(x))) using namespace std; int main(int argc, char const *argv[]) { int n,m; long long dp[1<<8][2]; long long min_; while(1){ cin>>n>>m; if(n+m==0) break; vector<long long> cb(m); v...
Time Limit: 8 sec / Memory Limit: 64 MB Example Input 5 3 2 aaaaa aaa aab Output 1 6
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const dou...
Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary ...
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) using namespace std; typedef pair<int,int> ii; vector<int> G[510]; vector<string> arr; vector<ii> edges; bool found[510]; bool used[510]; bool cycle; bool inValid(string a,string b) { if( a == b ) return false; int dif...
Example Input 2 -3 4 L 2 5 ? 3 5 Output 2 L 4 L 3
// // Problem: Kimagagure Cleaner // Solution by: MORI Shingo // O(n*2^(n3/8)) // // implement1 & debug1 214min // implement2 86min // debug2 122min // #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <stri...