input
stringlengths
29
13k
output
stringlengths
9
73.4k
Mr. F has n positive integers, a_1, a_2, โ€ฆ, a_n. He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers. But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward. ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.TreeMap; import java.util.TreeSet; ...
Berland has n cities, some of which are connected by roads. Each road is bidirectional, connects two distinct cities and for each two cities there's at most one road connecting them. The president of Berland decided to split country into r states in such a way that each city will belong to exactly one of these r state...
#include <bits/stdc++.h> using namespace std; const int N = 2020; namespace Gause { static const int N = ::N; int equ, var; bitset<N> a[N]; int x[N]; int free_x[N]; int free_num; int l[N]; void ini(int n) { for (int i = (0); i < (n); ++i) x[i] = 0; for (int i = (0); i < (n); ++i) a[i].reset(); } int Gauss() { int...
Mishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice). Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls M...
""" โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ•โ•โ• โ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ•šโ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ•โ•โ• โ•šโ•โ•โ•โ•โ•โ• โ•šโ•โ• โ•šโ•โ•โ•โ•โ• โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ...
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in...
n,v=[int(x) for x in input().split()] if n<=v+1: print(n-1) else: print(v+(n-v-1)*(n-v-2)//2+(n-v-1)*2)
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot...
#Bhargey Mehta (Sophomore) #DA-IICT, Gandhinagar import sys, math, queue sys.setrecursionlimit(1000000) #sys.stdin = open("input.txt", "r") n = int(input()) l = list(input()) r = list(input()) ls = {chr(i):[] for i in range(97, 97+26)} rs = {chr(i):[] for i in range(97, 97+26)} lc = [] rc = [] for i in range(n): if l...
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n ร— m square cells. In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: <image> Each pipe segment has two ends, illustrated ...
#include <bits/stdc++.h> double const PI = 4 * atan(1); using namespace std; int n, m, py[511111][2], px[511111][2]; int main() { scanf("%d %d", &n, &m); char s[n + 1][m + 1]; memset(py, 0, sizeof(py)); memset(px, 0, sizeof(px)); for (int i = 0; i < n; i++) scanf("%s", s[i]); for (int i = 0; i < n; i++) ...
You are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible. Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beau...
import java.util.*; import java.lang.*; import java.io.*; public class lyrics { public static void main(String[] Args){ FastReader scan=new FastReader(); int n=scan.nextInt(); String[] arr=new String[n]; Map<Integer,ArrayList<Integer>> m=new HashMap<>(); char[] last=new char...
You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2 ร— 2. We are only interested in two types of squares: 1. squares with each side parallel to a side of the matrix; 2. squares with each sid...
#include <bits/stdc++.h> using namespace std; const int inf = 0x7fffffff; const long long Linf = (1uLL << 63) - 1; const double EPS = 1e-10; namespace IOSpace { void get_int(int &x) { char t = getchar(); bool neg = false; x = 0; for (; (t > '9' || t < '0') && t != '-'; t = getchar()) ; if (t == '-') neg =...
You are given an undirected graph with n vertices numbered from 1 to n. Initially there are no edges. You are asked to perform some queries on the graph. Let last be the answer to the latest query of the second type, it is set to 0 before the first such query. Then the queries are the following: * 1~x~y (1 โ‰ค x, y โ‰ค...
#include <bits/stdc++.h> using namespace std; const int N = 200005; const int SIZE = 500; set<pair<int, int> > now, pre; struct Node { int u, v, fa, dep; }; stack<Node> s; int n, m; int op[N], x[N], y[N]; struct DSU { int fa[N], dep[N]; void init(int n) { for (int i = 1; i <= n; i++) fa[i] = i, dep[i] = 1; ...
You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.nio.charset.C...
You are playing a computer game, where you lead a party of m soldiers. Each soldier is characterised by his agility a_i. The level you are trying to get through can be represented as a straight line segment from point 0 (where you and your squad is initially located) to point n + 1 (where the boss is located). The le...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; /* 5 6 4 14 1 2 3 4 5 1 5 2 1 2 5 2 3 5 3 5 3 5 6 4 14 1 2 3 4 5 1 5 2 2 2 5 2 3 5 1 5 3 */ public class D...
This is an interactive problem. After completing the last level of the enchanted temple, you received a powerful artifact of the 255th level. Do not rush to celebrate, because this artifact has a powerful rune that can be destroyed with a single spell s, which you are going to find. We define the spell as some non-e...
#include <bits/stdc++.h> using namespace std; int ask(string foo) { cout << foo << endl; fflush(stdout); int t; cin >> t; if (t == 0) exit(0); return t; } int main() { int n1 = 300 - ask(string(300, 'a')); int n2 = 300 - ask(string(300, 'b')); int n = n1 + n2; if (n1 == n) { ask(string(n, 'a'));...
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task. You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol...
# -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a...
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care. There is an nร— m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowe...
#include <bits/stdc++.h> using namespace std; char mat[1005][1005]; int op[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; int m, n; int checkrow(int i) { int flag = 0; for (int j = 1; j <= m; j++) { if (flag == 0) { if (mat[i][j] == '#') flag++; } else if (flag == 1) { if (mat[i][j] == '.') flag++; } e...
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ...
import java.util.Scanner; public class SocialDistance { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int Cases = sc.nextInt(); for (int i=0;i<Cases;i++){ Findtable(sc); } } private static void Findtable(Scanner sc) { int n...
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index. There are n cities and nโˆ’1 undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities a...
#include <bits/stdc++.h> using namespace std; const long long int N = 200010; vector<long long int> adj[N]; long long int n, m; vector<long long int> ar, hr, size, g, b; bool ans; void dfs(long long int v, long long int p) { size[v] = ar[v]; long long int gu = 0, bu = 0; for (auto u : adj[v]) { if (u == p) { ...
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k โˆˆ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
import math t=int(input()) while(t>0): l=(input().split()) a=int(l[0]) b=int(l[1]) mov=math.ceil(math.fabs(b-a)/10) print(mov) t=t-1
Having learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers. The rules of the game are as f...
#include <bits/stdc++.h> using namespace std; char buff[123]; bool wing, winr; int n, m, k, diff[123], s[10]; bool been[123][123]; bool cache[123][123]; bool trial() { for (int i = 0; i < 123; i++) { for (int j = 0; j < 10; j++) { s[j] += diff[i] % 2; diff[i] /= 2; } } bool ret = false; for ...
Gildong's town has a train system that has 100 trains that travel from the bottom end to the top end and 100 trains that travel from the left end to the right end. The trains starting from each side are numbered from 1 to 100, respectively, and all trains have the same speed. Let's take a look at the picture below. <i...
t=int(input()) while t: n,m=map(int,(input().split())) a=set(map(int,input().split())) b=set(map(int,input().split())) print(len(a&b)) t=t-1
There are n lanterns in a row. The lantern i is placed in position i and has power equal to p_i. Each lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the i-th lantern is turned to the left, it illuminates all such lanterns j that j โˆˆ [i - p_i, i - 1]. Similarly,...
#include<bits/stdc++.h> using namespace std; const int N=3e5+5;char ans[N]; int st[20][N],p[N],n,lg[N],pw[20],mx=1,f[N],g[N]; inline void up(int t) { if(t<mx)return; for(int i=mx+1;i<=t;++i)lg[i]=lg[i>>1]+1; for(int i=lg[mx]+1;i<=lg[t];++i)pw[i]=pw[i-1]<<1; mx=t; } inline void pre() { for(int i=1;i<=n;++i)st[0][i]...
There are n cities numbered from 1 to n, and city i has beauty a_i. A salesman wants to start at city 1, visit every city exactly once, and return to city 1. For all iโ‰  j, a flight from city i to city j costs max(c_i,a_j-a_i) dollars, where c_i is the price floor enforced by city i. Note that there is no absolute val...
import java.util.Map; import java.util.TreeMap; public class Main { public static void main(String[] args) { new Main(); } public Main() { FastScanner fs = new FastScanner(); java.io.PrintWriter out = new java.io.PrintWriter(System.out); solve(fs, out); out.flush(); } public void solve(FastScanner fs...
Given an integer n, find the maximum value of integer k such that the following condition holds: n & (n-1) & (n-2) & (n-3) & ... (k) = 0 where & denotes the [bitwise AND operation.](https://en.wikipedia.org/wiki/Bitwise_operation#AND) Input The first line contains a single integer t (1 โ‰ค t โ‰ค 3 โ‹… 10^4). Then t test...
from math import log from math import floor t = int(input()) for i in range(t): n = int(input()) #print(n) k = 2**(floor(log(n,2)))-1 print(k)
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very importa...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:256000000") using namespace std; int inf = 100000; int main() { int n, k; cin >> n >> k; vector<pair<int, int> > t(n); for (int i = 0; i < n; i++) cin >> t[i].first >> t[i].second; n++; t.push_back(make_pair(86401, 1)); int K = n - k; vector<int> ...
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants. The magic square is a matrix of size n ร— n. The elements of this matrix are integers....
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java....
Any resemblance to any real championship and sport is accidental. The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship: * the team that kicked most balls in the enemy's goal area wins the game; * the victor...
#include <bits/stdc++.h> using namespace std; const int NN = 56; map<string, int> zade, emtiaz, abraj; void fun(int x, int y, string a, string b) { zade[a] += x; zade[b] += y; abraj[a] += x; abraj[b] += y; abraj[a] -= y; abraj[b] -= x; if (x > y) { emtiaz[a] += 3; } else if (x < y) emtiaz[b] += ...
Numbers k-bonacci (k is integer, k > 1) are a generalization of Fibonacci numbers and are determined as follows: * F(k, n) = 0, for integer n, 1 โ‰ค n < k; * F(k, k) = 1; * F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k), for integer n, n > k. Note that we determine the k-bonacci numbers, F(k, n), on...
import java.io.*; import java.util.*; import java.math.*; import java.awt.geom.*; import static java.lang.Math.*; public class Solution implements Runnable { public void solve () throws Exception { long s = nextLong(); int k = nextInt(); ArrayList<Long> fib = new ArrayList<>(); fib.add(1L); for (int i =...
A Russian space traveller Alisa Selezneva, like any other schoolgirl of the late 21 century, is interested in science. She has recently visited the MIT (Moscow Institute of Time), where its chairman and the co-inventor of the time machine academician Petrov told her about the construction of a time machine. During the...
#include <bits/stdc++.h> using namespace std; long long tmp[10]; struct Bigint { const static int maxn = 10; const static int Base = (int)1e5; int a[maxn]; int n; Bigint(long long x = 0) { n = 0; for (; x; x /= Base) a[n++] = x % Base; } void operator+=(const Bigint &b) { for (; n < b.n; a[n++...
A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = xยทk. You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); long long int n, k; cin >> n >> k; if (k == 1) { cout << n; return 0; } if (n == 1) { cout << 1; return 0; } set<long long int> s; for (long long int i = 0; i < n; ...
Polar bears like unique arrays โ€” that is, arrays without repeated elements. You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, w...
#include <bits/stdc++.h> using namespace std; struct Data { int Value, Number; }; bool operator<(Data A, Data B) { return A.Value < B.Value; } int Get() { char c; while (c = getchar(), c < '0' || c > '9') ; int X = 0; while (c >= '0' && c <= '9') { X = X * 10 + c - 48; c = getchar(); } return ...
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not. You're given a number. Determine if it is a magic number or not. Input The first line of input contains ...
a=input() result=1 if a[0]!='1': print('NO') result=0 else: for i in range(len(a)): if a[i]!='1' and a[i]!='4': print('NO') result=0 break if result==1: length=len(a) for i in range(length-2): if a[i]=='4' and a[i+1]=='4' and a[i+2]...
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: 1. Find any continuous subsequence (substring) of three characters of string q, which does...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class SerejaAndAlgorithm { public static void main(String[] args) { MyScanner sc = new MyScanner(); String S = sc.next(); int M = sc.nextInt(); ...
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix". Inna sees an n ร— m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix ar...
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileReader; import java.util.ArrayList; import java.awt.Point; import java.io.BufferedReader; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import...
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string con...
#include <bits/stdc++.h> using namespace std; string s[100005]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; ++i) { cin >> s[i]; } int len = s[1].length(); for (int i = 0; i < len; ++i) { set<char> st; for (int j = 1; j <= n; ++j) { if (s[j][i] >= 'a' && s[j][i] <= 'z') { ...
Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each f...
#include <bits/stdc++.h> using namespace std; const int INF = (int)1e9 + 7; const int MXN = (int)1e5 + 7; int n, k, t; int fac[MXN], rev[MXN], m[MXN]; int binpow(int x, int y) { int res = 1; while (y) { if (y & 1) res = (1LL * res * x) % INF; y >>= 1; x = (1LL * x * x) % INF; } return res; } int c(i...
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 โ‰ค k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree...
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7, N_MAX = 1e5; int n; vector<int> gr[N_MAX + 2]; bool col[N_MAX + 2]; int dp[N_MAX + 2][2]; void dfs(int arg) { dp[arg][0] = !col[arg]; dp[arg][1] = col[arg]; for (auto it : gr[arg]) { dfs(it); int aux0 = dp[arg][0], aux1 = dp[arg][1]; ...
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce <image> (remainder after dividing x by m) more details. Unfortunately, no c...
#include <bits/stdc++.h> using namespace std; int main() { int a, m; cin >> a >> m; for (int i = 0; i <= m; i++) { a += (a % m); a %= m; if (a == 0) { printf("Yes\n"); return 0; } } printf("No\n"); }
An n ร— n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
n = int(input()) list1 = [] list2 = [1 for i in range(n)] list3 = [1] + [0 for i in range(n-1)] list1.append(list2) for i in range(n-1): list1.append(list3) for i in range(1,n): for j in range(1,n): list1[i][j] = list1[i-1][j] + list1[i][j-1] list4 = [] for i in range(n): list4.append(max(list1[i]))...
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: ...
#include <bits/stdc++.h> using namespace std; const long long A = 100000000000000LL, N = 10000; long long x[2], y[2], o[2], i, j, n, m; int main() { cin >> x[0] >> y[0] >> x[1] >> y[1]; o[0] = x[0] + y[0], o[1] = max(x[1], y[1]); if (o[0] <= o[1]) cout << "Polycarp\n"; else if (x[0] <= x[1] && y[0] <= y[1])...
Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller. Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegme...
import java.util.Scanner; public class B { public static void main(String args[]){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int b[][] = new int[1000001][3]; int max = 0 , l = 0 , r = 0; for(int i = 0 ; i < n ; i++){ int t = in.nextInt(); ...
You are given an infinite periodic array a0, a1, ..., an - 1, ... with the period of length n. Formally, <image>. A periodic subarray (l, s) (0 โ‰ค l < n, 1 โ‰ค s < n) of array a is an infinite periodic array with a period of length s that is a subsegment of array a, starting with position l. A periodic subarray (l, s) is...
#include <bits/stdc++.h> using namespace std; int d[200010]; int a[200010]; int ok[400010]; long long freq[200010]; long long acc[200010]; int cop[200010]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } if (n == 1) { printf("0\n"); return 0; } vector<i...
The scientists have recently discovered wormholes โ€” objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you ...
#include <bits/stdc++.h> const int N = 1000 + 7; int n; double p[N][N], f[N], g[N], h[N][N]; int vis[N], top[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) scanf("%lf", p[i] + j), p[i][j] /= 100; vis[top[1] = n] = 1; for (int j = 1; j <= n; ++j) h[j][1] = 1 - p[j...
A remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island con...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; int n, S, T, a[maxn], b[maxn], cir[maxn], cnt; int fa[maxn], dep[maxn], head[maxn], to[maxn << 1], nxt[maxn << 1], tot; bool inc[maxn], vis[maxn]; inline bool judge(int x) { return a[x] == b[x]; } inline void add_edge(int x, int y) { to[++tot] = ...
The 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple. Gabriel is interested when the caterpill...
#include <bits/stdc++.h> using namespace std; int main() { int h1, h2, a, b; cin >> h1 >> h2; cin >> a >> b; h1 += 8 * a; if (h1 >= h2) { cout << 0; return 0; } if (b >= a) { cout << -1; return 0; } int ans = 0; while (1) { ans++; h1 -= 12 * b; h1 += 12 * a; if (h1 >=...
Vanya is in the palace that can be represented as a grid n ร— m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x โ‰ค p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exa...
import java.io.*; import java.util.*; public class D { @SuppressWarnings("unchecked") public static void solution(BufferedReader reader, PrintWriter out) throws IOException { In in = new In(reader); int n = in.nextInt(), m = in.nextInt(), p = in.nextInt(); ArrayList<Cell>[] ...
This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced. Polycarp likes to play computer role-playing game ยซLizards and Basementsยป. At the moment he is playing it as a magician. At one of the las...
import java.util.Scanner; public class Main { private static final int MAX = 20; static class Value { int totalHits; int currentHits; int bestNext2 = MAX - 1; int bestNext3 = MAX - 1; public Value(int totalHits) { this.totalHits = totalHits; } ...
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59. You are given a time in format HH:MM that is currently displayed on the broken ...
import java.util.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main { public static void main(String[] args) throws Exception{ InputReader in = new InputRead...
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer f...
#include <bits/stdc++.h> using namespace std; long long int curr[200005], mx[200005], arr[200005], n, inf = -9999999999, m = -9999999999; vector<long long int> v[200005]; long long int dfs(long long int a, long long int p) { curr[a] = arr[a]; for (auto it : v[...
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be ...
n = int(input()) s = list(map(int, input().split())) e1 = [] e2 = set() f = '\n' r = '' for i in s: '''e1.append(i) while n in e1: print(n, end=' ') n -= 1 print()''' e2.add(i) while n in e2: print(n, end=' ') n -= 1 print()
They've screwed something up yet again... In one nuclear reactor of a research station an uncontrolled reaction is in progress and explosion which will destroy the whole station will happen soon. The station is represented by a square n ร— n divided into 1 ร— 1 blocks. Each block is either a reactor or a laboratory. The...
import java.io.*; import java.math.BigInteger; import java.util.*; /* procrastinating */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 2e9; static final long OO = (long) 4e18; static final int MOD = 998244353; ...
Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P = [p1, p2, ..., pn], where pi denotes the number of page that should be read i-th in turn. Sometimes Vladikโ€™s mom so...
#include <bits/stdc++.h> const double pi = acos(-1.0); const int INF = 0x7FFFFFFF; using namespace std; const int maxn = 10010; int p[maxn]; bool sorting(int l, int r, int index) { int low = 0; for (int i = l - 1; i < r; i++) if (p[i] < p[index - 1]) low++; if (l + low == index) return 1; return 0; } int ma...
Let's call the roundness of the number the number of zeros to which it ends. You have an array of n numbers. You need to choose a subset of exactly k numbers so that the roundness of the product of the selected numbers will be maximum possible. Input The first line contains two integer numbers n and k (1 โ‰ค n โ‰ค 200, ...
#include <bits/stdc++.h> const long long mod = 1e9 + 7; const long long MAX = INT_MAX; const long long inf = 1e18 + 5; const double pi = 3.14159265358979323846; long long dirX[] = {1, -1, 0, 0}; long long dirY[] = {0, 0, 1, -1}; using namespace std; int32_t main() { long long n; cin >> n; long long k; cin >> k;...
Vasya and Petya are playing an online game. As most online games, it has hero progress system that allows players to gain experience that make their heroes stronger. Of course, Vasya would like to get as many experience points as possible. After careful study of experience points allocation, he found out that if he pla...
#include <bits/stdc++.h> using namespace std; const int N = 800050; const long long inf = 9e18; mt19937 rng(time(0)); int ls[N], rs[N], tsz, root, pri[N]; long long x[N], y[N], lzy_x[N], lzy_y[N], my[N], ms[N], ss[N], se[N]; void pull(int c) { ss[c] = se[c] = x[c]; if (ls[c]) ss[c] = ss[ls[c]]; if (rs[c]) se[c] =...
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet. For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name. The second ambiguity is about the Berland s...
#include <bits/stdc++.h> using namespace std; set<string> SE; int main() { string a[500]; int N; scanf("%d", &N); for (int k = 0; k < N; k++) { string s; cin >> s; for (int i = s.size() - 1; i >= 0; i--) { if (i >= 1 && s[i] == 'h' && s[i - 1] == 'k') s[i - 1] = 'h'; else if (s[i...
A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg...
sizes=[int(x) for x in str(input()).split(" ")] l=(sizes[0],2*sizes[0]) m=(max(2*sizes[3]+1,sizes[1]),2*sizes[1]) s=(max(sizes[2],sizes[3]),min(2*sizes[2],2*sizes[3])) if m[1]>=m[0] and s[1]>=s[0]: print(l[1]) print(max(m[0],s[0])+1) print(s[0]) else: print(-1)
Arkady decided to buy roses for his girlfriend. A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the...
#include <bits/stdc++.h> using namespace std; class Global { public: int n, i, k, ot = -1; vector<int> v, w, r, o; char ch; void pref(vector<int>& v) { int x; for (i = x = 0; i < v.size(); ++i) { x += v[i]; v[i] = x; } } void start() { cin >> n >> k; v.resize(n); for (i ...
You're given a tree with n vertices rooted at 1. We say that there's a k-ary heap of depth m located at u if the following holds: * For m = 1 u itself is a k-ary heap of depth 1. * For m > 1 vertex u is a k-ary heap of depth m if at least k of its children are k-ary heaps of depth at least m - 1. Denote dpk(...
#include <bits/stdc++.h> using namespace std; vector<bool> visited; vector<vector<int>> edges; long long ans; int n; int magic = 550; int maxk = 2; vector<vector<int>> depth, children; void solve(int u) { int d = children[u].size(); vector<vector<int>> values(d + 2); for (int i = 0; i < d; ++i) for (int j = 1...
You are given a tree of n vertices. You are to select k (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the ...
#include <bits/stdc++.h> using namespace std; using cat = long long; unsigned long long MOD = 998244353LL; unsigned long long pw(unsigned long long a, unsigned long long e) { if (e <= 0) return 1; unsigned long long x = pw(a, e / 2); x = (x * x) % MOD; if (e % 2 != 0) x = (x * a) % MOD; return x; } unsigned l...
Agent 47 attacks OO7 during the mission and uses Beretta M9 pistol (Semi Automatic). The pistol uses a 1mm bullet. The pistol bullet keeps changing the caliber after each consecutive fire. As the 1st round is fired, caliber of bullet triples and during 2nd round it's caliber increases by 2mm and then the trend repeats....
test=long(raw_input()); while(test!=0): n=long(raw_input()); if(n>120): print "UNABLE TO FIRE" else: flag=1 ans=1; while(n!=0): if (flag==1): ans*=3 else: ans+=2 flag^=1 n=n-1 print ans test-=1
Billi was on date with his girlfriend Ketty. They had the following conversation Ketty :- "Billi, How much do u love me?" Billi :- "Ummm...." Ketty :- "Come on.... Do you love me or not? :'( " Billi :- "Umm.....yes, I love you A^B units." Ketty :- "Ohh really....that's such a huge amount!! " Now you're task is to ...
def main(): for _ in xrange(input()): A,B,K=map(int,raw_input().split()) string=str(pow(A,B,10**K)) lis=[int(i) for i in string] print sum(lis) if __name__=="__main__": main()
Navi is a counter strike pro. He always say how good he is at counter strike. After being tired of Navi, his friends decided to test his skills at shooting. They put M targets on a X-Y plane, each target is denoted by (X, Y) where X is x-coordinate and Y is y-coordinate. His friends also gave him N locations on X-Y pl...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=raw_input() t=int(t) while (t>0): var=raw_input() mylist=var.split(" ") n=int(mylist[0]) m=int(mylist[1]) d=int(mylist[2]) count=0 ans=0 arr=Matrix = [[0...
Today is Tom's Birthday. His Mom gifted him two sets of integers to play with, set Q and set R. R is the transformation of set Q. Both Q and R contains same frequency of numbers. While playing, he accidently drops few of integers of set Q. You have to help him find the numbers that he has dropped in ascending order a...
mdict = {} num1 = input() marr1 = map(int, raw_input().split()) num2 = input() marr2 = map(int, raw_input().split()) for val in marr1: if mdict.get(val, 'not') == 'not': mdict[val] = 1 else: mdict[val] += 1 for val in marr2: if mdict.get(val, 'not') == 'not': mdict[val] = -1 else: mdict[val] -= 1 for ky in ...
Given an array A of N integers. Find total number of pairs such that i < j and A[i] > A[j]. Constraints 1 โ‰ค N โ‰ค 2*10^3 1 โ‰ค Ai โ‰ค 10^9 SAMPLE INPUT 5 5 1 2 4 3 SAMPLE OUTPUT 5
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' n=input() c=0 l=[int(i) for i in raw_input().split()] for i in range(n-1): for j in range(i+1,n): if l[i]>l[j]: c+=1 print c
After developing SPOJ-Toolkit manku thinks he is a FAAD coder now . He keeps bragging about himself so his friend KK decides to teach him a lesson . He gave him a simple problem to solve. Given an array of N integers he has to find the maximum sum that can be obtained from elements of array such that adjacent element...
T = input() while T > 0: T -= 1 N = input() a = [0] + map(int, raw_input().split()) # f = [0, a[1]] for i in range(2, N + 1): a[i] = max(a[i] + a[i - 2], a[i - 1]) print a[N]
You have an m x n grid, with m and n both even. Each cell has a tile. The tile has two faces - one is black, and one is white. These tiles may be flipped. However, if you flip a tile, all other tiles in its row and column also get flipped. You start of with an initial configuration of black and white tiles. Your goal i...
m, n = map(int, raw_input().split()) y_cnt = [0] * m x_cnt = [0] * n black = set() for y in xrange(m): s = raw_input() for x, c in enumerate(s): if c == "B": x_cnt[x] += 1 y_cnt[y] += 1 black.add((x, y)) ans = 0 for y in xrange(m): for x in xrange(n): ans += (x_cnt[x] + y_cnt[y] + ((x, y) in black)) & ...
Ranjan came to know about competitive programming today and created an account on Hackerearth. With his full determination he started to solve his first problem. He saw a question stated as. Calculate the sum of numbers from 1 to N as: for ( i=1;i โ‰ค N;i++ ) sum += i % MOD; He wrote the code for it but could no...
for _ in xrange(input()): n, mod = map(long, raw_input().split()) print (n/mod)*((mod-1)*mod/2) + (n%mod)*(n%mod+1)/2
You have a one-dimensional array of N pixels. Each pixel has a value, represented by a number between 0 and 255, inclusive. The distance between two pixels is the absolute difference of their numbers. You can perform each of the following operations zero or more times: With cost D, delete any pixel, so its original n...
def cost(k, v): if (k, v) not in c: if k < 0: c[(k, v)] = 0 else: t = d + cost(k-1, v) o = abs(s[k] - v) if m > 0: for u in range(256): if t <= o: break t = min(t, cost...
King Tle4Ever of Time Limit Exceeded is really fascinated about Tic Tac Toe. He organizes a national level contest for Tic Tac Toe every year in Time Limit Exceeded. (Though I agree you need to be really stupid to loose a game of Tic Tac Toe but for the sake of question assume playing Tic Tac Toe for them is same as pl...
t = input() mod = 1000000007 while t!=0: n = input() n %= mod maxx = ((2*n-1)*(n-1)*n)/6 maxx %= mod m = ((n-1)*n)/2 minwins = m/n carry = m%n; minn = (n-carry)*minwins*minwins minn %= mod minwins += 1 minn += carry*minwins*minwins minn %= mod print str(minn) + " " + str(maxx) t -= 1
Given are two sequences A and B, both of length N. A and B are each sorted in the ascending order. Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it. Constraints * 1\leq N \leq 2 \times 10^5 *...
from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify from math import gcd import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, ...
N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town. There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}. Takahashi will walk around this town and make mischief on the Snukes who have no s...
#include <bits/stdc++.h> using namespace std; int main(void){ int n,k; cin>>n>>k; map<int,bool> m; for(int i=1;i<=k;i++){ int d; cin>>d; for(int j=1;j<=d;j++){ int c; cin>>c; if(!m[c]) n--,m[c]=true; } } cout<<n<<endl; return 0; }
Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string. Constraints * S and T are strings consisting of lowercase English letters. * The lengths of S and T are between 1 and 100 (inclusive). Input Input is gi...
import java.util.*; class Main { public static void main(String[] args){ Scanner c=new Scanner(System.in); String s=c.next(); String t=c.next(); System.out.println(t+s); } }
There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i. For each square, you will perform either of the following operations once: * Decrease the height of the square by 1. * Do nothing. Determine if it is possible to perform the operations so that the heights ...
import decimal decimal.getcontext().prec = 100 def sum1(pre,l,r): l=max(l,0) if(l==0): return pre[r] return pre[r] - pre[l - 1] x=int(raw_input()) arr=map(int,raw_input().split()) b=[arr[0]-1] mi=b[0] for i in range(1,len(arr)): if(arr[i]-1>=mi): b.append(arr[i]-1) else: b.a...
Snuke has an empty sequence a. He will perform N operations on this sequence. In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1). You are given a sequence b of length N. Determine if it is possible that a is equal to b after N oper...
#include<cstdio> #include<algorithm> int main(){ int n,b[100],a[100]; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d",&b[i]); if(b[i]>=i+2){ printf("-1"); return 0; } } //b[i]==iใชใ‚‹ๆœ€ใ‚‚ๅคงใใ„iใ‚’้ธใ‚“ใงๅ–ใ‚Š้™คใ //ใจใ„ใ†ๆ“ไฝœใง้ธใ‚“ใ ๆ•ฐๅˆ—ใฎreverse for(int ia=n-1;ia>=0;ia--){ int ib=ia; while(b[ib]<ib+1)...
There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them. Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are...
using namespace std; #include <cstdio> #include <cstring> #include <algorithm> #define N 610 #define ll long long #define mo 1000000007 int n,K; int to[N],c[N]; bool bz[N][N]; int f[N][N],g[N]; int main(){ scanf("%d%d",&n,&K); for (int i=1;i<=K;++i){ int a,b; scanf("%d%d",&a,&b); if (a>b) swap(a,b); to[a]=b,t...
You are given a string S of length 3 consisting of `a`, `b` and `c`. Determine if S can be obtained by permuting `abc`. Constraints * |S|=3 * S consists of `a`, `b` and `c`. Input Input is given from Standard Input in the following format: S Output If S can be obtained by permuting `abc`, print `Yes`; otherwis...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); if(s.matches("^(?=.*a)(?=.*b)(?=.*c).*")) { System.out.println("Yes"); } else { System.out.println("No"); } } }
Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is `YES` or `NO`. When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases. Then, he rewrote the code to correctly solve each of th...
N,M = map(int,input().split()) print(int(((N-M)*100+M*1900)/(0.5**M)))
Snuke has N integers. Among them, the smallest is A, and the largest is B. We are interested in the sum of those N integers. How many different possible sums there are? Constraints * 1 โ‰ค N,A,B โ‰ค 10^9 * A and B are integers. Input Input is given from Standard Input in the following format: N A B Output Print th...
#include<cstdio> int main(){ int n,a,b; scanf("%d%d%d",&n,&a,&b); if(a>b||(n==1&&a!=b))printf("0\n"); else if(a==b)printf("1\n"); else printf("%lld\n",(1ll*b*(n-1)+a)-(1ll*a*(n-1)+b)+1); return 0; }
Snuke is going to open a contest named "AtCoder s Contest". Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters. Snuke has decided to abbreviate the name of the contest as "AxC". Here, x is the uppe...
import java.util.Scanner; public class Main { @SuppressWarnings("resource") public static void main(String args[]) { Scanner scanner = new Scanner(System.in); String w = scanner.next(); String h = scanner.next(); String n = scanner.next(); System.out.println("A" + h.charAt(0) + "C"); } }
Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both `voodoo` and `melee` are unbalanced, while neither `noon` nor `a` is. You are given a string s consisting of lowercase letters. Determine if there exists a (...
#include<bits/stdc++.h> using namespace std; int main(){ string s; cin>>s; int len=s.length(); for(int i=0;i<len-1;i++){ if(s.at(i)==s.at(i+1)){ cout<<i+1<<" "<<i+2<<endl; return 0; } } for(int i=0;i<len-2;i++){ if(s.at(i)==s.at(i+2)){ cout<<i+1<<" "<<i+3<<endl; return 0...
Your task is to write a program which reads an expression and evaluates it. * The expression consists of numerical values, operators and parentheses, and the ends with '='. * The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division. * Precedence of the operat...
#include <string> #include <iostream> using namespace std; /* <expr> ::= <term> [ ('+'|'-') <term> ]* <term> ::= <factor> [ ('*'|'/') <factor> ]* <factor> ::= <number> | '(' <expr> ')' <number> :== 1?????\????????ยฐ??? */ int expr(string& s, int& i); int term(string& s, int& i); int factor(string& s, int& ...
The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them. The requirements for this software (game) are as follows....
#include<iostream> #include<queue> using namespace std; struct Puzzle { char p[10][10]; }; queue<pair<Puzzle, int>>Q; queue<pair<int, int> >Q2; int blute_force(int h, int w, Puzzle x) { while (!Q.empty())Q.pop(); Q.push(make_pair(x, 0)); while (true) { Puzzle y = Q.front().first; int V = Q.front().second; Q.pop();...
Create a program that converts data based on the given conversion table. The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table. The conversion table has two characters (not a string), one be...
#include<bits/stdc++.h> using namespace std; int main(){ int n,m; cin >> n; while(n != 0){ char a[n+1],b[n+1]; for(int i = 0;i < n;i++) cin >> a[i] >> b[i]; cin >> m; char ans[m+1]; for(int i = 0;i < m;i++){ cin >> ans[i]; for(int j = 0;j < n;j++){ if(ans[i] == a[j]...
Dr. Asimov, a robotics researcher, has succeeded in developing a new robot. The robot can move freely along a special wire stretched around the floor. The robot always moves forward in a direction parallel to the current wire. The good news is that this robot doesn't consume energy to move on the wire, regardless of i...
#include<bits/stdc++.h> using namespace std; const double EPS = 1e-8, PI = acos(-1), INF = 1e9; inline bool eq(double a, double b) { return abs(b - a) < EPS; } struct Point { double x, y; Point() {}; Point(double x, double y) : x(x), y(y) {}; Point operator+(const Point &b) const { return Point(x + b.x...
Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1. <image> Figure D-1: A sample railway network Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortes...
#include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <algorithm> #include <utility> #include <functional> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <ctime> #include <c...
Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day. But last week, you overheard a magic spell that ...
#include <iostream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include <utility> #include <set> #include <map> #include <deque> #include <queue> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <stdio.h> using namespace std; #define fo(i,n) for(int i=0;...
Hint In solving this problem, the following may be referred to. Shows how to convert an integer value to a string. Assign value as a string to str. For C include <stdio.h> int main () { int value = 123; // Convert this value to a string char str [6]; // This variable contains a string of value sprintf (str, "% d",...
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(int)(n);++i) #define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i) #define ALL(c) (c).begin(), (c).end() #define valid(y,x,h,w) (0<=y&&y<h&&0<=x&&x<w) #define tpl(...) make_tuple(__VA_ARGS__) const int INF = 0x3f3f3f3f; co...
Nathan O. Davis is taking a class of signal processing as a student in engineering. Todayโ€™s topic of the class was autocorrelation. It is a mathematical tool for analysis of signals represented by functions or series of values. Autocorrelation gives correlation of a signal with itself. For a continuous real function f(...
#include <iostream> #include <vector> #include <algorithm> #include <complex> #include <cmath> #include <cstring> using namespace std; const double EPS=(1e-10); bool EQ(double a,double b){ return abs(a-b)<EPS; } typedef complex<double> P; typedef pair<double,double> pdd; double calc(double a1,double b1,double a...
You built an apartment. The apartment has a water tank with a capacity of L in order to store water for the residents. The tank works as a buffer between the water company and the residents. It is required to keep the tank "not empty" at least during use of water. A pump is used to provide water into the tank. From th...
#include <iostream> #include <vector> #include <cmath> using namespace std; using P = pair<double,double>; int N; double L; vector<P> V; bool eval(double u){ double l=L; for(auto v:V){ l+=v.first*(u-v.second); l=min(L,l); if(l<=0) return false; } double l1=l; for(auto v:V){...
Problem statement There are two integers $ A $ and $ B $. The process of finding $ A --B $ by writing in decimal is shown below. 1. Express $ A $ and $ B $ in decimal. Subscripts are $ 0,1,2, ..., n-1 $ in order from the bottom, $ A = A_ {n-1} A_ {n-2} ... A_ {0} $, $ B = B_ { n-1} B_ {n-2} ... B_ {0} $. $ n $ is the...
#include<iostream> #include<algorithm> using namespace std; #define MAX_N 20 long long a, b, k; long long c[MAX_N + 1], d[MAX_N + 1], e[MAX_N + 1], bor[MAX_N + 1]; long long p[MAX_N]; long long maxn = 0; int main() { cin >> a >> b >> k; p[0] = 1; for (int i = 1; i < MAX_N - 1; i++) { p[i] = p[i - 1] * 10; } f...
Problem Statement Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and does not have much money. Therefore, he is trying to save money by using the Seishun 18 Ticket. With only one 18 ticket, you can ride a local train all day long, and you can enter and exit the ticket gates f...
//include //------------------------------------------ #include <bits/stdc++.h> // only for GCC using namespace std; //typedef //------------------------------------------ typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef vector<bool> vb; typedef vector<vb> vvb; typedef pair<int, int>...
H: Typing Game / Typing Game story From here, it's time to train your typing skills. Can you type quickly and accurately? Let โ€™s enjoy Typing Game! problem As a typing game game system, create a program that operates interactively with respect to the AI โ€‹โ€‹output prepared by the judge. AI plays a game of typing N s...
#include <iostream> #include <cstdio> #include <string> #include <vector> using namespace std; typedef pair<string, int> P; void solve() { int N, H; cin >> N >> H; vector<P> input(N); for (int i = 0; i < N; ++i) { cin >> input[i].first >> input[i].second; } int mistake = 0; int count = 0; int word = 0; in...
problem There is a simple concatenated undirected graph with $ N $ vertices and $ M $ edges. The vertices are numbered $ 1, 2, \ dots, N $. The edges are numbered $ 1, 2, \ dots, M $, and the edge $ i $ connects the vertices $ a_i $ and $ b_i $. Also, the edge $ i $ disappears at time $ t_i $. It takes a unit time to ...
#include<bits/stdc++.h> using namespace std; typedef long long int64; const int64 INF = 1LL << 55; int N, M, T; int x[200000], y[200000], z[200000]; vector< pair< int, int > > g[200000]; int64 v[200000]; struct UnionFind { vector< int64 > data, time, score; UnionFind(int sz) { data.assign(sz, -1LL); ...
A: Hokkaido University Easy Note Please note that the problem settings are the same as problem B, except for the constraints. story Homura-chan, who passed Hokkaido University and is excited about the beginning of a new life. But in front of her, a huge campus awaits ... "Eh ... I'm not in time for the next class ...
#include <bits/stdc++.h> using namespace std; using lint = long long; template<class T = int> using V = vector<T>; template<class T = int> using VV = V< V<T> >; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int h, w; cin >> h >> w; V<string> s(h); for (auto&& e : s) cin >> e; int res = 0; for (...
Zero AND Subsets Given a multiset of nonnegative integers a_1, a_2, .., a_N. How many non-empty subsets of this set have a value bitwiseAND of 0? Find the remainder of the answer divided by 10 ^ 9 + 7. input N a_1 a_2 ... a_N output Divide the answer by 10 ^ 9 + 7 and output the remainder. Constraint * 1 \ l...
#include <bits/stdc++.h> using namespace std; const int64_t MOD = 1e9+7; void add(int64_t& a, int64_t b){ a = (a+b) % MOD; } void mul(int64_t& a, int64_t b){ a = a*b % MOD; } vector<int64_t> fact, seq_inv, fact_inv; void create_fact_mod(int num){ fact[0] = fact[1] = 1; for(int i=2; i<=num; i++) fact[...
Write a program which manipulates a sequence A = {a0, a1, . . . , anโˆ’1} with the following operations: * update(s, t, x): change as, as+1, ..., at to x. * find(i): output the value of ai. Note that the initial values of ai (i = 0, 1, . . . , nโˆ’1) are 231-1. Constraints * 1 โ‰ค n โ‰ค 100000 * 1 โ‰ค q โ‰ค 100000 * 0 โ‰ค s โ‰ค ...
#include <iostream> #define INF (1 << 31) - 1 using namespace std; typedef pair<int,int> P; int n,q,cnt = 1; P dat[300000]; void init(){ int nn = 1; while(nn < n) nn *= 2; n = nn; for(int i = 0;i < n * 2 - 1;i++){ dat[i] = P(INF,0); } } void update(int a,int b,int x,int k,int l,int r){ if(r <= a || b <= l) ...
The Head Chef is receiving a lot of orders for cooking the best of the problems lately. For this, he organized an hiring event to hire some talented Chefs. He gave the following problem to test the skills of the participating Chefs. Can you solve this problem and be eligible for getting hired by Head Chef. A non-nega...
t=int(raw_input()) for i in range(t): n=int(raw_input())-1 st='' while(n>=5): st=str(n%5)+st n=n//5 st=str(n)+st print(2*int(st))
As you have probably realized up to now that Devu is not a normal guy, he is a very weird and abnormal guy. Normally people have two hands, but Devu has three of them. So he wears three wrist watches on his hands. Devu loves to write name of his friends on his wrist watches. So he want to attach a string correspondin...
def power(a,b): x=1 while(b): if(b&1): x=(x*a)%m a=(a*a)%m b>>=1 return x m=10**9+7 t=int(raw_input()) while t>0: t-=1 n,k=map(int,raw_input().split()) if k==1: print 0 continue inv=power(k-1,m-2) inv=power(inv,3) inv=(k*inv)%m ...
Chef was feeling bored so he decided to create a pattern to play with. His pattern always has 1 as its first element. Then he chooses a number K as the second element. After selecting K as his second number he creates next element in the pattern by multiplying all previously existing elements of the pattern. Now he a...
mod=int(10**9+7) t=int(input()) while t>0: t-=1 b,a=map(int,raw_input().split()) if a==1: print 1 elif a==2: print b else: c=pow(2,a-3,mod-1) print pow(b,c,mod)
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 22344. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 774410 we shall call a positive integer that is neither increasing nor decreasing ...
T=input() while T: T-=1 inv=0 N=list(str(input())) length=len(N) for i in range(0,length): N[i]=int(N[i]) i=0 while i<length-1 and N[i+1]==N[i]: i+=1 if i==length-1: print 'valid' continue if N[i+1]>N[i]: while i<length-1 and N[i+1]>=N[i]: ...
Problem description. Tic-tac-toe is the third most popular activity to kill a lazy afternoon in Ardenia.Arthum and Breece are not fans of this game, but their mother told them to play, so they sit at a 5 x 5 board. Both have a large pile of marbles: marbles of Arthum have an A written on them and that of Breece have a ...
import sys; aw=False; bw=False; def main(): tc=int(raw_input().strip()); for x in range(tc): global aw; global bw; aw=False; bw=False; board=[]; for y in range(5): board.append(raw_input().strip()); checkHorizontal(board); checkVertical(board); checkDiagonal(board); global aw; global bw; i...
You have an array of integers A1, A2, ..., AN. The function F(P), where P is a subset of A, is defined as the XOR (represented by the symbol โŠ•) of all the integers present in the subset. If P is empty, then F(P) Given an integer K, what is the maximum value of K โŠ• F(P), over all possible subsets P of A? Input The firs...
def ContainsBit(mask, i): return mask & (1 << i) > 0 def GaussianElimination(values, n): values.sort(reverse=True) bit = max(i if ContainsBit(values[0], i) else 0 for i in xrange(11)) start = 0 for b in xrange(bit, -1, -1): j = -1 for i in xrange(start, n): if ContainsBit(values[i], b): ...