input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are given an array a consisting of n positive integers. Initially, you have an integer x = 0. During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1). ...
from collections import Counter as Cnt for _ in range(int(input())): n, k = map(int, input().split()) a = [(int(x) % k) for x in input().split() if int(x) % k != 0] if not a: print(0) else: c = Cnt(a) print(max(1 - x + k * c[x] for x in c))
Ziota found a video game called "Monster Invaders". Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns. For the sake of simplicity, we only consider two different types of monsters and three different types of guns. Namely, the two types of monsters are: *...
#include <bits/stdc++.h> using namespace std; int read() { int x = 0, c = getchar(); for (; !(c > 47 && c < 58); c = getchar()) ; for (; (c > 47 && c < 58); c = getchar()) x = x * 10 + c - 48; return x; } void upd(long long &a, long long b) { a = (a < b) ? a : b; } const int N = 1e6 + 5; long long f[N][2]; ...
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers a and b and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of (a ⊕ x) + (b ⊕ x) for any given x, where ⊕ denotes the [bitwise XOR operation](http...
import math t = int(input()) for _ in range(t): a,b = [int(x) for x in input().split()] x = 1 ans = 0 while(x<=a or x<=b): if (x&a!=x&b): ans+=x x*=2 print(ans)
Let's consider a (10^9+1) × (10^9+1) field. The rows are numbered with integers from 0 to 10^9 and the columns are numbered with integers from 0 to 10^9. Let's define as (x, y) the cell located in the x-th row and y-th column. Let's call a cell (x, y) good if x \& y = 0, there \& is the [bitwise and](https://en.wikipe...
#include <bits/stdc++.h> using namespace std; template <typename T> struct outputer; struct outputable {}; template <typename T> inline auto sqr(T x) -> decltype(x * x) { return x * x; } template <typename T1, typename T2> inline bool umx(T1& a, T2 b) { if (a < b) { a = b; return 1; } return 0; } templa...
Only a few know that Pan and Apollo weren't only battling for the title of the GOAT musician. A few millenniums later, they also challenged each other in math (or rather in fast calculations). The task they got to solve is the following: Let x_1, x_2, …, x_n be the sequence of n non-negative integers. Find this value:...
import sys testing = len(sys.argv) == 4 and sys.argv[3] == "myTest" if testing: cmd = sys.stdout from time import time start_time = int(round(time() * 1000)) input = open(sys.argv[1], 'r').readline sys.stdout = open(sys.argv[2], 'w') else: input = sys.stdin.readline mod = 10**9+7 # from math im...
Polycarp was gifted an array a of length n. Polycarp considers an array beautiful if there exists a number C, such that each number in the array occurs either zero or C times. Polycarp wants to remove some elements from the array a to make it beautiful. For example, if n=6 and a = [1, 3, 2, 1, 4, 2], then the followin...
#include <iostream> #include <algorithm> using namespace std; #ifndef ONLINE_JUDGE #include <fstream> #define cin fin #define cout fout ifstream fin ("test.in"); ofstream fout ("test.out"); #endif int t, n, a[200001], f[200001], nra, p[100001], k; int rasp (int mij) { int r = 0; for (int i = 1; i <= k...
A sequence of n non-negative integers (n ≥ 2) a_1, a_2, ..., a_n is called good if for all i from 1 to n-1 the following condition holds true: $$$a_1 \: \& \: a_2 \: \& \: ... \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: ... \: \& \: a_n, where \&$$$ denotes the [bitwise AND operation](https://en.wikipedia.org/wiki...
import java.io.*; import java.util.*; public class Main { static long mod=1_000_000_000+7; static long[] facts=new long[3_000_00]; static long mul(long a, long b) { return a*b%mod; } static long add(long a, long b) { return (a+b)%mod; } static void precomp() { facts[0]=1; for (int i=1; i<facts.length...
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one. Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree. After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked no...
#include <iostream> #include <vector> #define ll long long #define pb push_back using namespace std; int const N=210,mod=1e9+7; int n; int inv[N],dp[N][N],lca[N][N],dep[N]; vector<int> g[N],s[N]; void dfs(int cur,int fa){//cur=current, fa=father(don't go to fa) s[cur]={cur};dep[cur]=(fa>=0)?dep[fa]+1:1; for(int child...
In some country live wizards. They like to make weird bets. Two wizards draw an acyclic directed graph with n vertices and m edges (the graph's vertices are numbered from 1 to n). A source is a vertex with no incoming edges, and a sink is the vertex with no outgoing edges. Note that a vertex could be the sink and the ...
#include <bits/stdc++.h> using namespace std; const long long MAXN = 100005; long long read() { long long x = 0, flag = 1; char c; while ((c = getchar()) < '0' || c > '9') if (c == '-') flag = -1; while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); return x * flag; } long l...
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of ...
s = raw_input() while s.find("//") != -1: s = s.replace("//", "/") if s[-1] == "/" and len(s)>1: s = s[0:-1] print s
Some days ago, WJMZBMR learned how to answer the query "how many times does a string x occur in a string s" quickly by preprocessing the string s. But now he wants to make it harder. So he wants to ask "how many consecutive substrings of s are cyclical isomorphic to a given string x". You are given string s and n stri...
#include <bits/stdc++.h> using namespace std; void io() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(15); } const int inf = 1e9; const int maxn = 4 * 1e6 + 5; char s[maxn]; unordered_map<int, int> to[maxn]; int len[maxn], fipos[maxn], link[maxn]; int depth[maxn]; int node, pos; in...
Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by...
import java.util.Scanner; public class Adding_Digits { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); int n = scan.nextInt(); int ans = a; for (int i = 0 ; i < 10 ; i++) { if (Integer.parseInt("" + a + i) % b == 0) { a...
The cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 ≤ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given ...
#include <bits/stdc++.h> using namespace std; int main() { int p; cin >> p; int t; int flag = 0; int ans = 0; for (int i = 1; i < p; i++) { t = i; for (int j = 1; j <= p - 2; j++) { if ((t - 1) % p != 0) { t = (t % p) * i; } else { flag = 1; break; } } ...
People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium ca...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 7; int data[N << 1]; int main() { int n, L, t; scanf("%d%d%d", &n, &L, &t); t <<= 1; for (int i = (0); i < (n); ++i) scanf("%d", &data[i]); double ans = 0; for (int l = 0, r = n, i = 0; i < n; i++, l++, r++) { ans += 0.5 * (t / L) * (n - ...
Everybody knows that we have been living in the Matrix for a long time. And in the new seventh Matrix the world is ruled by beavers. So let's take beaver Neo. Neo has so-called "deja vu" outbursts when he gets visions of events in some places he's been at or is going to be at. Let's examine the phenomenon in more deta...
#include <bits/stdc++.h> using namespace std; const int mo = 1000000007; const int N = 52; int g[2][2][N][N][N * 2]; int f[N * 2][N][2]; int n, m, st[N * N], ed[N * N]; vector<int> seq[N * N]; int e[N][N]; pair<int, int> walk(vector<int> &tp, int x, bool fl) { int now = 0; for (; now + 1 <= tp.size();) { int y ...
Vasya and Petya are using an interesting data storing structure: a pyramid. The pyramid consists of n rows, the i-th row contains i cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to <image> as shown on the picture below. An example of a pyram...
#include <bits/stdc++.h> using namespace std; bool debug = false; int n, m, k; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; long long ln, lk, lm; vector<int> sc[100005]; long long dp[2][100005]; long long sss(int c, int num) { if (sc[c].empty()) return 0; return upper_bound(sc[c].begin(), sc[c].end(), num) - s...
Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analys...
#include <bits/stdc++.h> using namespace std; template <class T> void mini(T& a, T b) { a = min(a, b); } template <class T> void maxi(T& a, T b) { a = max(a, b); } template <class T1, class T2> ostream& operator<<(ostream& out, pair<T1, T2> a) { return out << a.first << " " << a.second; } template <class T> ostre...
Petya wrote a programme on C++ that calculated a very interesting function f(n). Petya ran the program with a certain value of n and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had th...
#!/usr/bin/python import re, sys n = int (sys.stdin.readline ()) class MyInt (object): def __init__ (self, a): if isinstance (a, MyInt): self.v = a.v else: self.v = int (a) def val (self): return self.v def __add__ (self, a): return MyInt ((self.val () + a.val ()) & 32767) def __sub__ (self, a): ret...
Sereja has two sequences a1, a2, ..., an and b1, b2, ..., bm, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions: 1. Choose several (at least one) first elements...
#include <bits/stdc++.h> using namespace std; const int INF = 1E9 + 7; template <class C> void mini(C& a4, C b4) { a4 = in(a4, b4); } set<int> gdzie[2][100005]; int t[2][100005]; int best[100005][305]; int main() { ios_base::sync_with_stdio(false); int n, m, s, e; cin >> n >> m >> s >> e; for (int i = (1); i ...
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked....
# -*- coding: utf-8 -*- import sys if __name__ == '__main__': num = map(int,sys.stdin.readline().split()) lit=[] for v in range(num[0]): str = sys.stdin.readline() if str not in lit: lit.append(str) print len(lit)
Malek is a rich man. He also is very generous. That's why he decided to split his money between poor people. A charity institute knows n poor people numbered from 1 to n. The institute gave Malek q recommendations. A recommendation is a segment of people like [l, r] which means the institute recommended that Malek give...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int N = 1e5 + 5; const int M = 5005; int read() { int s = 0, f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { s = s * 10 + c - '0'; c = g...
A and B are preparing themselves for programming contests. To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger. For each chess piece we know its weight: * the queen's weight is 9, * the rook's weight is 5, * the ...
# -*- coding: utf-8 -*- """ Created on Thu Nov 8 10:34:19 2018 @author: Quaint Sun """ line=[] t=0 while t<8: line=line+list(input()) t=t+1 white=line.count('Q')*9+line.count('R')*5+line.count('B')*3+line.count('N')*3+line.count('P') black=line.count('q')*9+line.count('r')*5+line.count('b')*3+line.count...
Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance: We will define the distance between two strings s and t of the same length consisting of digits zero and one as the num...
#include <bits/stdc++.h> using namespace std; long long k, ans; string s, s1; int main() { cin >> s >> s1; for (int i = 0; i < s.size(); i++) if (s[i] == s1[i]) ans++; if ((s.size() - ans) % 2 == 1) { cout << "impossible"; return 0; } for (int i = 0; i < s.size(); i++) { if (s[i] == s1[i]) cou...
Oscolcovo city has a campus consisting of n student dormitories, n universities and n military offices. Initially, the i-th dormitory belongs to the i-th university and is assigned to the i-th military office. Life goes on and the campus is continuously going through some changes. The changes can be of four types: ...
#include <bits/stdc++.h> using namespace std; const int TR = (1 << 21) + 3; const int N = 5e5 + 3; const int oo = 1e9; int stp[N], st[N], lv[N], lu[N], pv[N], pu[N], a[N][2], ST, tr_mx[TR], sz; char s[N]; long long tr[TR]; vector<int> g[N]; pair<int, int> c[N]; long long get(int i, int l, int r, int lt, int rt) { if ...
The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = ki·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines,...
def equation(k, x, b): return k * x + b num = int(input()) ans = [] x1, x2 = map(int, input().split()) for i in range(0,num): k, b = map(int, input().split()) ans.append((equation(k, x1, b), equation(k, x2, b))) ans.sort() for i in range(1, num): if (ans[i][0] > ans[i - 1][0] and ans[i][1] ...
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). ...
#include <bits/stdc++.h> using namespace std; int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } int main() { int n; cin >> n; vector<int> p; for (int i = 0; i < n; i++) { int x; cin >> x; p.push_back(x); } int m = p[0]; for (int i = 0; i < n; i++) { m = gcd(m, p[i])...
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)? Input The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012), the sum and bitwise xor of the pair of positive integers, respectively. Output Print a s...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:640000000") using namespace std; const double eps = 1e-9; const double pi = acos(-1.0); int s[44], x[44]; long long dp[44][2][2][2]; long long dfs(int pos, int tmp, int wasa, int wasb) { if (pos < 0) return tmp == 0 && wasa == 0 && wasb == 0; long long &res =...
Consider a regular Codeforces round consisting of three problems that uses dynamic scoring. You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack i...
#include <bits/stdc++.h> using namespace std; const int N = 5005; const int MAX_SCORE[] = {500, 1000, 1500, 2000, 2500, 3000}; const int COEFF[] = {2, 4, 8, 16, 32, 5000}; int maxPeople[6], minPeople[6]; int solved[3]; int n; queue<int> tab[5][5]; int points[3][N]; int t[N]; bool wasHacked[N]; int ableToHack[3]; pair<i...
Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya. Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Ar...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C687 { static boolean dp[][][] = new boolean[555][555][555]; public static void main(String[] args)throws IOException { BufferedReader br = new BufferedReader(new InputStreamRe...
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split! Fangy did not like ...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class BetaRound64_B implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws IOException { i...
There are n students at Berland State University. Every student has two skills, each measured as a number: ai — the programming skill and bi — the sports skill. It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in...
#include <bits/stdc++.h> using namespace std; const int N = 3e3 + 5; const int INF = ~0x3f3f3f3f; struct Player { int p, s, id; }; Player a[N]; int dp[N][N]; pair<int, int> bk[N][N], bkk[N][N]; void update(int i, int j, int v, pair<int, int> b, pair<int, int> k) { if (dp[i][j] < v) { dp[i][j] = v; bk[i][j] ...
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ...
#include <bits/stdc++.h> using namespace std; long long int a, b, c, d, n, m, k, l, g; long long int an = -1, san, ean; bool mrk = 0; set<pair<int, int> > s, e; vector<pair<int, int> > nums; int st[300005], en[300005]; set<pair<int, int> > ans; int main() { cin >> n >> k; for (int i = 0; i < n; i++) { scanf("%d...
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards. As before, th...
import java.util.*; public class Problem7a{ public static int countCols(char[][] sq){ int cols = 0; for(int c = 0; c < sq[0].length; c++){ if(sq[0][c] == 'B'){ for(int r = 1; r < sq.length; r++){ if((r == sq.length - 1) && (sq[r][c] == 'B')){ cols++; } else if(sq[r][c] != 'B'){ ...
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens. All characters in this game are lowercase English letters. There are two players: Mister B and his competitor. Initially the players have a string s consisting of the...
#include <bits/stdc++.h> using namespace std; long long a, b, l, r; bool can(long long x) { if (x * (a + b) < l) return 1; return 0; } int get() { long long L = 0, R = (long long)(1e9 + 7), mid; while (R - L > 5) { mid = (L + R) / 2; if (can(mid)) L = mid; else R = mid - 1; } for (lo...
Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are alread...
#include <bits/stdc++.h> using namespace std; using tint = long long; using ld = long double; using vi = vector<tint>; using pi = pair<tint, tint>; const tint MOD = 1e9 + 7; const int MX = 1e5 + 5; const tint INF = 1e18; const ld PI = acos((ld)(-1)); const double EPS = 1e-9; void NACHO(string name = "balompie") { ios...
Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string...
#include <bits/stdc++.h> using namespace std; int main() { string s = ""; cin >> s; if (s == "f1e") cout << "NO" << endl; else if (s == "0f1e") cout << "00f1" << endl; else if (s == "12d2c") cout << "00314" << endl; else if (s == "00000000000001") cout << "NO" << endl; else if (s == "00000...
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it. Now he tries to solve a quest. The task is to come to a settlement named Ove...
n, m = map(int, input().split()) c = [0] + list(map(int, input().split())) parent = [i for i in range(n + 1)] def find(i): while i != parent[i]: parent[i] = parent[parent[i]] i = parent[i] return i for i in range(m): a, b = map(lambda x: find(int(x)), input().split()) if c[a] < c[b]...
Ember and Storm play a game. First, Ember picks a labelled tree T of n vertices, such that the degree of every vertex is at most d. Then, Storm picks two distinct vertices u and v in this tree and writes down the labels of the vertices in the path from u to v in a sequence a1, a2... ak. Finally, Ember picks any index i...
#include <bits/stdc++.h> using namespace std; long long read() { long long x; scanf("%lld", &x); return x; } unsigned m; unsigned add(unsigned a, unsigned b) { return a + b < m ? a + b : a + b - m; } void dadd(unsigned &a, unsigned b) { a = add(a, b); } unsigned sub(unsigned a, unsigned b) { return a >= b ? a - b...
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec...
n = int(input()) s = input() s2 = s[0] for i in range(1,n): if(ord(s[i]) == ord("a") or ord(s[i]) == ord("e") or ord(s[i]) == ord("i") or ord(s[i]) == ord("o") or ord(s[i]) == ord("u") or ord(s[i]) == ord("y")) and (ord(s[i - 1]) == ord("a") or ord(s[i - 1]) == ord("e") or ord(s[i - 1]) == ord("i") or ord(s[i - 1])...
You are given two integers a and b. Moreover, you are given a sequence s_0, s_1, ..., s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k ≤ i ≤ n it's satisfied that s_{i} = s_{i - k}. Find out the non-negative remainder of division of ∑ _{i...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 9; const int MAXN = 1e5 + 5; long long n, a, b, k, res, ans; char s[MAXN]; long long qpow(long long a, long long p) { long long res = 1; while (p) { if (p & 1) res = res * a % MOD; a = a * a % MOD; p >>= 1; ...
Given three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes. In an undirected graph loops (edges fro...
#include <bits/stdc++.h> using namespace std; const long long INF = 1LL << 62; const int MAX = 1e3 + 3; int grid[MAX][MAX]; void solve() { memset(grid, 0, sizeof(grid)); int n, a, b; cin >> n >> a >> b; if (a > 1 && b > 1) { cout << "NO" << endl; return; } if (a == 1 && b == 1 && (n == 3 || n == 2))...
Rahul's Dad is the CEO of one of the leading companies. Every time somebody seeks for an appointment he calls up his secretary and asks her whether the day is a Sunday or not. He has to keep his caller on hold and is unhappy about it. Knowing that his son Mayank knows a bit of programming he asks him to make a program...
t = int(raw_input()) def anchor_day(year): centurie = year[0] + year[1] centurie = int(centurie) if centurie % 4 == 1: return 6 elif centurie % 4 == 2: return 4 elif centurie % 4 == 3: return 2 elif centurie % 4 == 0: return 1 def doomsday_num(year, month): ...
Chandu's girlfriend loves arrays that are sorted in non-increasing order. Today is her birthday. Chandu wants to give her some sorted arrays on her birthday. But the shop has only unsorted arrays. So, Chandu bought T unsorted arrays and is trying to sort them. But, he doesn't have much time to sort the arrays manually...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' def solve(n, array): tmp = sorted(array)[::-1] for i in xrange(n): tmp[i] = str(tmp[i]) return ' '.join(tmp) def sort_array(): T = int(raw_input()) for _ in xrange(T): n = int...
Lexicographical order is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters. An example of lexicographical arrangement is a dictionary or a contact directory. You are given some names, and your task is to arrange these names in lexicographical orde...
import re romanNumeralMap = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX',...
It is lunch time at the Vibrant Gujarat Summit and all the investors are called for the executive lunch. When Bruce reached the lunch area, he found that the waiter was taking out bowls from a big box containing some amount of golden bowls and other bronze bowls. The bowls were taken out at random. Each dish contains e...
import math x=int(raw_input()) c=math.sqrt(1.+2.*x*(x-1.)) n=(c+1.)/2. print int(n)
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. SAMPLE INPUT 1 2 88 42 99 SAMPL...
t =1 while (t==1): x = int(raw_input()) if (x == 42 ): t =0 else: print x
Monk visits Biksy, the largest trading market in the land. Biksy has traders from all over the world. There are a total of N items indexed from 1 to N, that are traded in the market by a total of M dealers. Each trader is characterized by three integers, say i, j, C , meaning that the trader will take i'th item from yo...
from collections import defaultdict import sys T = int(raw_input()) inf = sys.maxint for test in range(T): N,M = [int(x) for x in raw_input().split()] D = [[inf]*(N+1) for x in range(N+1) ] dicti = defaultdict(lambda :-1*inf) for l in range(M): i,j,c = [int(x) for x in raw_input().split()] ...
Sherlock and Watson are close friends. One day, they finally got bored of playing normal games. So, they came up with a new idea of playing with numbers. Since they are good at number theory, they know the fact that a decimal number "A" can be represented as sum of 2's powers. For example: 22 = 16 + 4 + 2 = 2^4...
t = int(raw_input()) r = "Sherlock" q = "Watson" for i in range(t): n = int(raw_input()) count = 1 count = bin(n).count('1') if count%2==0: print(q) j=r r=q q=j else: print(r)
Definition: Roy's boolean function (RBF) is True, if number of the positive integers less than or equal to N that are relatively prime to N, is prime; else False. In other words, let Z be the number of integers K in the range 1 ≤ K ≤ N for which the greatest common divisor gcd(N, K) = 1. If Z is prime then RBF is True ...
import math T=int(raw_input()) def prime(num): if num==1:return 0 s=int(round(math.sqrt(num)))+1 for i in range(2,s): if num%i==0: return False return True def gcd(p,q): while(q!=0): temp=q q=p%q p=temp return p for t in range(T): m=1 N=int(raw_input()) for j in range(2,N): if gcd(N,j)==1: ...
Problem: You are given n natural numbers a1,a2,a3…… an. Let SOD of a number be defined as the Sum of Digits of that number. Compute the value of { [ SOD(a1) + SOD(a2) + …….. SOD(an) ] % 9 } – { [ SOD( a1 + a2 + ….. an ) ] % 9 } Input: The first line consists of the value of n. Next n lines are such that the i th li...
#a= int(raw_input()) #while a>0: #a-= 1 #b =(raw_input()) print 0
With the T20 world cup going on, a list of batsmen was prepared with their country code and their T20I career runs. The list contains data of N batsmen (country-code and runs). Number of countries may range from 1 to N and each country has its unique code. The list is pretty unorganized. Virat and Maxwell do not ...
playerCount = int(raw_input()) def outlist(data): runMap = {} for entry in data: cCode, run = int(entry[0]), int(entry[1]) if(runMap.has_key(cCode) == False): runMap[cCode] = [run] else: runMap[cCode].append(run) sortedCCode = sorted(runMap.keys()) for cCode in sortedCCode: runList = reversed(s...
We will buy a product for N yen (the currency of Japan) at a shop. If we use only 1000-yen bills to pay the price, how much change will we receive? Assume we use the minimum number of bills required. Constraints * 1 \leq N \leq 10000 * N is an integer. Input Input is given from Standard Input in the following for...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int ans = 0; ans = n % 1000; if(ans != 0) { ans = 1000 - ans; } System.out.println(ans); } }
Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold? Constraints * 1 \leq a, b, c \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: a \ b \ c Output If \sqrt{a} + \sqrt{b} < \sqrt{c}, print `Yes`; otherwise, print `No`. Examples Input 2 3 9 Output No I...
#include<bits/stdc++.h> using namespace std; int main() { long double a,b,c; cin>>a>>b>>c; long long int d=c-a-b; if(d*d> 4*a*b&&d>0) cout<<"Yes"; else cout<<"No"; }
We have two indistinguishable pieces placed on a number line. Both pieces are initially at coordinate 0. (They can occupy the same position.) We can do the following two kinds of operations: * Choose a piece and move it to the right (the positive direction) by 1. * Move the piece with the smaller coordinate to the po...
#include<bits/stdc++.h> #define int long long #define fr(i,a,b) for(int i(a),end##i(b);i<=end##i;i++) #define fd(i,a,b) for(int i(a),end##i(b);i>=end##i;i--) using namespace std; const int mod=998244353; const int maxn=4e7+5; int ksm(int x,int k){ int ans=1; while(k){ if(k&1)ans=ans*x%mod; x=x*x%mod; k>>=1; } ...
We have N weights indexed 1 to N. The mass of the weight indexed i is W_i. We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be th...
#include <bits/stdc++.h> using namespace std; int main(){ int N; cin >> N; int W[110] = {}; int S[110] = {}; for(int i = 1; i <= N; i++){ cin >> W[i]; S[i] = S[i-1] + W[i]; } int ans = 1145141919; for(int i = 1; i <= N; i++){ ans = min(ans, abs(S[N] - 2 * S[i])); } cout << ans << endl; }
Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates. Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions: * The largest among the values in the i-th row (1 \leq i \leq N) is A_i. * The largest among the value...
MOD = int(1e9) + 7 def binsearch(num, ary): left = 0 right = len(ary) while left < right: center = (left + right) // 2 if num <= ary[center]: left = center + 1 else: right = center return left def main(): N, M = map(int, input().split()) A = li...
Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000. Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i. If two slimes of the same color are adjacent, they ...
#include <bits/stdc++.h> using namespace std; typedef long long LL; int main(){ int n; cin >> n; LL a[n]; LL ans = 0; for(int i = 0; i < n; i++){ cin >> a[i]; if(i > 0 && a[i] == a[i-1]){ ans++; a[i] = -1000; } } cout << ans << endl; }
For a positive integer n, let us define f(n) as the number of digits in base 10. You are given an integer S. Count the number of the pairs of positive integers (l, r) (l \leq r) such that f(l) + f(l + 1) + ... + f(r) = S, and find the count modulo 10^9 + 7. Constraints * 1 \leq S \leq 10^8 Input Input is given fro...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #defi...
You are given N points (x_i,y_i) located on a two-dimensional plane. Consider a subset S of the N points that forms a convex polygon. Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polyg...
#include<bits/stdc++.h> using namespace std; const int mod = 998244353; const int N = 11111; void add(int &x, int y) { x += y; if (x >= mod) x -= mod; } int pw(int a, int b) { int an = 1; for (; b; b >>= 1) { if (b & 1) an = 1ll * an * a % mod; a = 1ll * a * a % mod; } return an; } int ans, x[N], y[N], n; int...
Dolphin loves programming contests. Today, he will take part in a contest in AtCoder. In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock". The current time is A o'clock, and a contest will begin in exactly B hours. When will the contest begin? Answer in 24-hour time. Constrain...
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO 自動生成されたメソッド・スタブ Scanner sc = new Scanner(System.in); // 整数の入力 int A = sc.nextInt(); int B = sc.nextInt(); int C = A + B; if (C >= 24) { C = C - 24; } // 出力 System.out.println(C); } }
Shik's job is very boring. At day 0, his boss gives him a string S_0 of length N which consists of only lowercase English letters. In the i-th day after day 0, Shik's job is to copy the string S_{i-1} to a string S_i. We denote the j-th letter of S_i as S_i[j]. Shik is inexperienced in this job. In each day, when he i...
#include<iostream> #include<cstdio> #include<algorithm> #include<deque> using namespace std; int n,ans; char s[1000010],t[1000010]; deque<int> q; int main(){ scanf("%d%s%s",&n,s+1,t+1); q.push_back(n+1); for(int i=n,j=n+1,tmp=0,pre;i;i--){ for(pre=j;j&&(i<j||s[j]!=t[i]);j--); if(!j){ ...
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure. <image> Trains depart from both terminal stations on this line at the same time and r...
public class Main{ public void run(java.io.InputStream in, java.io.PrintStream out){ java.util.Scanner sc = new java.util.Scanner(in); /*answer*/ int[] l, v; int i, j, k, sum; String str; char[] ch; double d; l = new int[10]; v = new int[2]; for(;sc.hasNext();){ str = sc.next();...
Create a program that inputs the vertex information of two polygons inscribed in one circle and outputs the magnitude relationship of their areas. Assume that each vertex of the X-side is numbered counterclockwise from 1 to X (the figure shows an example when X = 4). However, the given polygon assumes that the center ...
# Area of Polygon from math import sin from math import radians while True: m = int(raw_input()) if m == 0: break a1, v, vv = (0.0, 0, 0) for i in range(m): if i < m - 1: v = int(raw_input()) vv += v else: v = 360 - vv a1 += sin(radi...
Addition is easy to calculate by hand, but if some numbers are missing, is it easy to fill in the missing numbers? For example, in the following long division, if there is a condition that the numbers 1 to 9 appear only once, how many numbers will fit in the C and E squares? In this case, 8 is correct for C and 5 is co...
#include<bits/stdc++.h> using namespace std; int a[10]; int num[10]; int cnt; bool flag(){ for(int i=0;i<9;i++){ if(a[i]==-1) return false; } return true; } void dfs(int k){ for(int i=k;i<9;i++){ if(a[i]==-1){ for(int j=1;j<10;j++){ if(num[j]==0){ a[i]=j; num[j]=1; dfs(i); num[j]=0; ...
problem The JOI building is a combination of regular hexagons with a side of 1 meter as shown in the figure. As Christmas is approaching, JOI decided to decorate the walls of the building with illuminations. However, since it is useless to illuminate the parts that cannot be seen from the outside, we decided to decora...
#include<stdio.h> #include<algorithm> #include<queue> using namespace std; int dat[501][501]; int dx[]={0,0,1,1,-1,-1}; int dy[]={1,-1,-1,0,0,+1}; int bfs[501][501]; int main(){ int a,b; scanf("%d%d",&b,&a); for(int i=0;i<a;i++){ for(int j=0;j<b;j++){ if(j+1+a-(i+1)/2<0)printf("dededon\n"); scanf("%d",&dat[i...
Problem KND is a student programmer at the University of Aizu. He is known to be a sweet tooth. He will be staying in a city for a year and wants to visit all N sweets shops in the city during that time. So I think the best place to live for the past year is the best place to go around the sweets shop. As his neighbor...
#include<cmath> #include<cstdio> #include<vector> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; const double EPS=1e-8; template<class T> struct point{ T x,y; point operator+(const point &a)const{ return (point){x+a.x,y+a.y}; } point operator-(const point &a)const{ return (point){x-a.x,y-a.y}; } };...
Yoko’s math homework today was to calculate areas of polygons in the xy-plane. Vertices are all aligned to grid points (i.e. they have integer coordinates). Your job is to help Yoko, not good either at math or at computer programming, get her home- work done. A polygon is given by listing the coordinates of its vertic...
#include <algorithm> #include <climits> #include <cmath> #include <cstdlib> #include <iostream> #include <numeric> #include <vector> using namespace std; #define REP(i, a, b) for(int i = (a); i < int(b); ++i) #define rep(i, n) REP(i, 0, n) #define ALL(x) begin(x), end(x) constexpr double EPS = 1e-5; struct point { d...
Example Input 6 2 3 1 1 4 2 Output Yes Yes Yes No Yes No
#include<iostream> #include<algorithm> #include<cstdio> using namespace std; long long n,a,b[1000000],c,p; int main(){ cin>>n; for(int i=0;i<n;i++){ scanf("%d",&a);if(b[0]==1 || c>a){printf("No\n");continue;} if(c==a && p!=a){printf("No\n");continue;}p++; if(a>=1000000){printf("Yes\n");continue;} b[a]++;while...
Entrance Examination The International Competitive Programming College (ICPC) is famous for its research on competitive programming. Applicants to the college are required to take its entrance examination. The successful applicants of the examination are chosen as follows. * The score of any successful applicant is ...
#include <iostream> using namespace std; int main() { int m,min,max,ten[200],gap=10001,sa; cin>>m>>min>>max; while(1){ if(m==0 && min==0 && max==0){ break; } for(int i=1;i<=m;i++){ cin>>ten[i]; } for(int i=min;i<=max;i++){ if(gap>=ten[i+1]-ten[i]){ gap=ten[i+1]-ten[i]; ...
Franklin Jenkins is a programmer, but he isn’t good at typing keyboards. So he always uses only ‘f’ and ‘j’ (keys on the home positions of index fingers) for variable names. He insists two characters are enough to write programs, but naturally his friends don’t agree with him: they say it makes programs too long. He a...
#include <iostream> #include <string> #include <cstdio> #include <vector> #include <algorithm> #include <numeric> #include <cctype> #include <map> #include <functional> using namespace std; typedef vector<int> vint; int ans; const char *ptr; char buf[256]; map<string,int> mp; size_t cmp(const vint &v1, const vint &v...
N circles are drawn on the paper. The rabbit has k-colored paint and paints the paper according to the following rules. * Paint each area with one color of paint or nothing. Here, the "area" refers to the part with a finite area surrounded by a set of arcs. * Two adjacent areas cannot be painted with the same color. H...
#include<stdio.h> #include<algorithm> #include<vector> #include<math.h> #include<queue> using namespace std; const int D_MAX_V=20002; const int D_v_size=20002; struct D_wolf{ int t,c,r; D_wolf(){t=c=r=0;} D_wolf(int t1,int c1,int r1){ t=t1;c=c1;r=r1; } }; vector<D_wolf>D_G[D_MAX_V]; int D_level[D_MAX_V]; int D_it...
G: Code Art Online Code Art Online (CAO) is an online RPG that advances adventures by solving various problems by programming. Since CAO was the world's first game that realized a virtual reality space, it was sold out while it was very popular, and users who purchased the game should enjoy this world. However, player...
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define EPS (1e-8) #define equals(a,b) (fabs((a)-(b))<EPS) using namespace std; static const int COUNTER_CLOCKWISE = 1; static const int CLOCKWISE = -1; static const int ONLINE_BACK = 2; static const int ONLINE_FRONT = -2; st...
G --Derangement / Derangement Story Person D is doing research on permutations. At one point, D found a permutation class called "Derangement". "It's cool to have a perfect permutation !!! And it starts with D !!!", the person of D who had a crush on Chunibyo decided to rewrite all the permutations given to him. Pro...
#include <bits/stdc++.h> #define INF 1e9 using namespace std; int n,arr[101]; int cal(int a,int b){return (arr[a]+arr[b])*(abs(a-b));} void Min(int &a,int b){a=min(a,b);} int mem[3][101][101][101]; int dfs(int f,int num,int l,int r){ if(l>r)return 0; if(l==r)return (arr[l]==l+1) ? INF:0; if(r-l==1)return (arr[l]...
Example Input 3 2 3 1 3 1 2 2 1 2 3 1 2 Output 6.0000000
#include <stdio.h> #include <algorithm> #include <vector> #include <queue> using namespace std; const int non = 10000000; struct edge { int x, y, f, c, r; }; vector<edge> E[202]; void add(int x, int y, int f, int c) { int p = E[x].size(), q = E[y].size(); E[x].push_back({ x, y, f, c, q }); E[y].push_back({ y, x,...
G: 検閲により置換 (Censored String) Problem Statement You are given the string S, and the set of strings \mathcal P whose size is N. Now we consider applying the following operation to S: * Choose exactly one character in S, and replace it with '*'. Let s_i be a i-th character of S, S_{ij} be a consecutive substring in ...
#include<bits/stdc++.h> using namespace std; struct Node { int nxt[28]; int exist; // 子ども以下に存在する文字列の数の合計 vector< int > accept; // その文字列id Node() : exist(0) { memset(nxt, -1, sizeof(nxt)); } }; struct Trie { vector< Node > nodes; int root; Trie() : root(0) { nodes.push_back(Node()); } ...
Problem Today, the high-class restaurant "Maizu Restaurant", which is completely invited, has finally opened. Only members of this restaurant have the right to invite new members, initially only the owner of the restaurant with membership number 0. Due to its luxury, the Maze Restaurant is only open for $ N $ days fr...
#include<bits/stdc++.h> #define rep(i,a,b) for(int i=a;i<b;i++) #define rrep(i,a,b) for(int i=a;i>=b;i--) #define fore(i,a) for(auto &i:a) #pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } //--------------------------------------------------...
Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode: BubbleSort(A) 1 for i = 0 to A.length-1 2 for j = A.length-1 downto i+1 3 if A[j] < A[j-1] 4 swap A[j] and A[j-1] Note that, indices for array ...
#include<iostream> using namespace std; int main(){ int n,tmp,c=0; bool flag=true; cin>>n; int A[n]; for(int i=0;i<n;i++){ cin>>A[i]; } while(flag){ flag=false; for(int j=n-1;j>0;j--){ if(A[j]<A[j-1]){ tmp=A[j]; A[j]=A[j-1]; A[j-1]=tmp; flag=true; c++; } } } for(int i=0;i...
Write a program which reads a sequence and prints it in the reverse order. Note 解説 Constraints * n ≤ 100 * 0 ≤ ai < 1000 Input The input is given in the following format: n a1 a2 . . . an n is the size of the sequence and ai is the ith element of the sequence. Output Print the reversed sequence in a line. P...
#include<iostream> using namespace std; int main(void){ int n,a[100]; cin>>n; for(int i=0;i<n;i++)cin>>a[i]; for(int i=n-1;i>=0;i--){ cout<<a[i]; if(i!=0)cout<<" "; else cout<<endl; } }
Tanish loves alphabets. He loves alphabets so much that he ignores all other characters. Also, whenever he is given an alphabet he gives the next alphabet in alphabetical order in same case. For example, for a-b,for d-e,for z-a. Given a string guess what would be Tanish's answer. Input The first line of the input co...
#V 1.01. Forgot to account for uppercase alphabets earlier -_- T = (int)(raw_input()) while T: res = "" s = raw_input() for i in range(0, len(s)): if s[i].isalpha(): if ord(s[i])+1==123: res = res + 'a' elif ord(s[i])+1==91: res = res + 'A' else: res=res+(chr(ord(s[i]...
Chef spent N days working really hard! He planned loads of tasks: as many as Ai tasks to do on the ith day! Chef's work was brutal, so he only managed to finish Bi tasks on the ith day. The good news is that Chef has a Time Machine! The Time Machine has K white buttons and M black buttons. Each button has a positive i...
for t in xrange(int(raw_input())): n, k, m = map(int,raw_input().split()) a = map(int,raw_input().split()) b = map(int,raw_input().split()) y = sorted(map(int,(raw_input()+" "+raw_input()).split()), reverse = True) x = [] for i in xrange(n): x.append(a[i]-b[i]) x = sorted(x, reverse = True) left = sum(x) i =...
Problem Michal Scofield and Lincon burrow are two brothers. By a murder allegation Lincon Burrow was sentenced to jail. Michal Scofield some how came to know that his brother is not guilty and he don’t have time to file case against the allegations as his brother is going to sit on death chair soon enough. So he ma...
import sys; def main(): tc=int(raw_input()); for x in range(tc): noc=int(raw_input()); stinp=str(raw_input()); newst=str(); nor=len(stinp) / noc; for y in range(nor): if y%2!=0: for c in range(noc-1,-1,-1): ind=y*noc+c; char=stinp[ind]; newst=newst+char; else: for c in range(no...
You need to shuffle a series of numbers from 1 To T, inclusive. The numbers are in ascending order, you have to shuffle them using bubble sort algorithm, that is swap every time a number is greater than another in the given list in the input. A number is greater than another in the list if the number appears later than...
for _ in range(input()): n=input() a=map(int,raw_input().split()) c=0 for i in range(n): for j in range(n-i-1): if a[j]>a[j+1]: a[j],a[j+1]=a[j+1],a[j] #print a[j],a[j+1] c+=1 #print c print c
Little Egor likes to play with positive integers and their divisors. Bigger the number to play with, more the fun! The boy asked you to come up with an algorithm, that could play the following game: Let's define f(n) as the sum of all odd divisors of n. I.e. f(10) = 1 + 5 = 6 and f(21) = 1 + 3 + 7 + 21 = 32. The game ...
cases = int(raw_input()) while(cases): l,r = map(int,raw_input().split()) ans = 0 j = 1 while(j <= r): #print j ans += ((r/j)-((l)/j))*j if(l%j==0): ans+=j j+=2 print ans cases-=1
Professor Snape has lots of potions. Bottles containing all types of potions are stacked on shelves which cover the entire wall from floor to ceiling. Professor Snape has broken his bones several times while climbing the top shelf for retrieving a potion. He decided to get a ladder for him. But he has no time to visit ...
for i in range(int(raw_input())): a=map(int,raw_input().split()) print '%g' %(a[1]*a[1]-a[0]*a[0])**0.5, print '%g' %(a[1]*a[1]+a[0]*a[0])**0.5
You are given two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty. For example: * by applying a move to the string "where", the result is the s...
a = str(input()) b = str(input()) a = a[::-1] b = b[::-1] na = len(a) nb = len(b) d = abs(na-nb) l = min(na,nb) k = 0 for i in range(0,l): if a[i] != b[i]: k = (l - i)*2 break print(d+k)
We call an array b_1, b_2, …, b_m good, if there exist two indices i < j such that b_i ⋅ b_j is a [perfect square](https://en.wikipedia.org/wiki/Square_number). Given an array b_1, b_2, …, b_m, in one action you can perform one of the following: * multiply any element b_i by any prime p; * divide any element b_...
#include <bits/stdc++.h> using namespace std; const int MAX_N = 200000; const int MAX_K = 6000000; const int MAX_Q = 1100000; const int MAX_T = 10; const int INF = 1e8; int N, Q; int arr[MAX_N + 1]; vector<pair<int, int> > gp[MAX_N + 1]; vector<int> vt[MAX_N + 1]; int idx[MAX_T + 1][MAX_K + 1]; int use, now = 1; void m...
Little C loves number «3» very much. He loves all things about it. Now he is playing a game on a chessboard of size n × m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between ...
#include <bits/stdc++.h> using namespace std; long long N, M; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> N >> M; if (N > M) swap(N, M); long long Ans = 0; if (N == 1) { Ans = (M / 6) * 6 + ((M % 6 == 4) ? 2 : (M % 6 == 5) ? 4 : 0); } else if (N == 2) { Ans = (M == 2) ? 0 : (M == ...
Once upon a time Algoland and Berland were a single country, but those times are long gone. Now they are two different countries, but their cities are scattered on a common territory. All cities are represented as points on the Cartesian plane. Algoland consists of a cities numbered from 1 to a. The coordinates of the...
#include <bits/stdc++.h> using namespace std; inline int read() { int n = 0, f = 1; char c; for (c = getchar(); c != '-' && (c < '0' || c > '9'); c = getchar()) ; if (c == '-') c = getchar(), f = -1; for (; c >= '0' && c <= '9'; c = getchar()) n = n * 10 + c - 48; return n * f; } struct ar { int x, y,...
You are given a string s consisting only of lowercase Latin letters. You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it. Let's call a string good if it is not a palindrome. Palindrome is...
def good_string(string): if string[::-1] != string: return string else: string = string[-1] + string[:-1] try: return good_string(string) except: return -1 if __name__ == "__main__": queries = int(input()) for _ in range(queries): string = input() print(good_string(string))
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i. This year 2D decided to cultivate a new culture, but what exactly he d...
#include <bits/stdc++.h> using namespace std; int main() { long int n; cin >> n; long int a[n]; long int sum = 0; for (long int i = 0; i < n; i++) { cin >> a[i]; sum += a[i]; } sort(a, a + n); long int maxres = 0; unordered_map<int, int> mp; for (long int i = 1; i < n; i++) { int f = 2, ...
A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n minutes. After a round ends, the next round starts immediately. This is repeated over and over again. Each round has the same scenario. It is described by a sequence of n numbers: d_1, d_2, ..., d_n (-10^6 ≤ d_i ≤ 10^6). Th...
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll oo = 0x3f3f3f3f3f3f3f3fLL; int main() { ios::sync_with_stdio(false); cin.tie(0); ll H, n; cin >> H >> n; vector<ll> d(n); for (auto &a : d) cin >> a; vector<ll> p(n + 1); for (ll i = 1; i <= n; i++) p[i] = d[i - 1] + p[i - 1]; ...
Let's define an unambiguous arithmetic expression (UAE) as follows. * All non-negative integers are UAE's. Integers may have leading zeroes (for example, 0000 and 0010 are considered valid integers). * If X and Y are two UAE's, then "(X) + (Y)", "(X) - (Y)", "(X) * (Y)", and "(X) / (Y)" (all without the double q...
#include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") const int MAXN = 2048; const int MOD = 1e6 + 3; char s[MAXN], S[MAXN], *ch = s; int dp[MAXN][MAXN], n = -1; int sign_l[MAXN], num_p[MAXN], sign_p[MAXN]; inline char getnext() { if (*ch == 0) return 0; if (*ch == '+' || *ch == '-') { ++c...
You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means...
#include <bits/stdc++.h> using namespace std; const int N = 100005; vector<int> g[N], v[N]; int d[N], dd[N], dep[N], f[N], o[N], n; void dfs(int x, int p) { dep[x] = dep[p] + 1; for (int i = 0; i < g[x].size(); i++) if (g[x][i] != p) dfs(g[x][i], x); } bool judge(int x) { for (int i = 0; i <= n; i++) dep[i] =...
Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges. Input The first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two intege...
#include <bits/stdc++.h> using namespace std; long long n, m, a, b, g[19][19], dp[1 << 19][19], ans; int main() { scanf("%lld%lld", &n, &m); for (int i = 0; i < m; i++) { scanf("%lld%lld", &a, &b); g[--a][--b] = g[b][a] = 1; dp[(1 << a) | (1 << b)][max(a, b)] = 1; } for (int i = 1; i < 1 << n; i++) ...
You are in charge of the BubbleReactor. It consists of N BubbleCores connected with N lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring. Your task is to start the BubbleReactor by starting each BubbleCor...
#include <bits/stdc++.h> using namespace std; template <typename T> inline bool upmin(T &x, T y) { return y < x ? x = y, 1 : 0; } template <typename T> inline bool upmax(T &x, T y) { return x < y ? x = y, 1 : 0; } const long double eps = 1e-9; const long double pi = acos(-1); const int oo = 1 << 30; const long long...
Let's look at the following process: initially you have an empty stack and an array s of the length l. You are trying to push array elements to the stack in the order s_1, s_2, s_3, ... s_{l}. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 300000; int n; int a[MAXN]; int nxt[MAXN + 1]; map<int, int> mp[MAXN + 1]; int mpidx[MAXN + 1]; int len[MAXN + 1]; long long solve() { nxt[n] = -1; mpidx[n] = n, mp[n].clear(...
You are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j. The tournament will be organized as follows: n boxers will be d...
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n; cin >> n; long long int log = log2(n), rem; rem = log; vector<long long int> arr(n); for (long long int i = 0; i < n; i++) cin >> arr[i]; reverse((arr).begin(), (arr).end())...
We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake. Uh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought abo...
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { static int inf = (int) 1e9 + 7; static int n, tri[][]; static ArrayList<Integer> gr[]; static TreeSet<Integer> cnt[]; public static void main(String[] args) throws IOException { ...
You are given a permutation, p_1, p_2, …, p_n. Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb. For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, A. For each i from 1 to n: * Add p_i to...
#include <bits/stdc++.h> using namespace std; int n, p[300005], pp[300005], q[300005]; struct SegTree { int a[300005 << 2], tg[300005 << 2]; inline int lc(int x) { return x << 1; } inline int rc(int x) { return x << 1 | 1; } inline void push_up(int p) { a[p] = max(a[lc(p)], a[rc(p)]); } inline void f(int p, i...
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (∀) and existential (∃). You can read more about them here. The universa...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; const int INF = 0x3f3f3f3f; const long long inf = 0x3f3f3f3f3f3f3f3f; int n, m; vector<int> G[N], GG[N]; int vis[N], mn[N], mn2[N]; bool dfs(int u) { vis[u] = 1; mn[u] = u; for (int v : G[u]) { if (vis[v] == 1) return false; if (!vis[v]...