input
stringlengths
29
13k
output
stringlengths
9
73.4k
At a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew three points with integer coordinates, and joined them with segments of straight lines, then he showed the triangle t...
//package com.prituladima.codeforce.a2oj.div2A; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import static java.util.stream.IntStream.range; public class Pro95 { private void s...
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies....
#include <bits/stdc++.h> using namespace std; const int INF = 0x3fffffff; int N, home[300], gind[300]; vector<int> gra[220]; int solve(int); int main() { int i, j, k, x, y; scanf("%d", &N); for (i = 1; i <= N; ++i) { scanf("%d", &home[i]); home[i]--; } for (i = 1; i <= N; ++i) { scanf("%d", &k); ...
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ...
t=int(input()) d={} while (t>0): t=t-1 s=input() if s in d: d[s]+=1 else: d[s]=1 print(max(d.values()))
Maxim loves sequences, especially those that strictly increase. He is wondering, what is the length of the longest increasing subsequence of the given sequence a? Sequence a is given as follows: * the length of the sequence equals n × t; * <image> (1 ≤ i ≤ n × t), where operation <image> means taking the remain...
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * f; } int T, n, b, t; in...
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. Petya decided to introduce the sum operation on the se...
#include <bits/stdc++.h> using namespace std; const long double EPS = 1e-8; const long double PI = 3.1415926535897932384626433832795; const long double E = 2.7182818284; const int INF = 1000000000; int t[16][16]; long long res = 0; long long m = 1000000007; long long fact = 1; int n; int f[16]; int vz[16]; void pereb(i...
Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom. King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordina...
#include <bits/stdc++.h> using namespace std; const int maxn = 100000 + 10; double a[maxn], x, y, mx, ans; double dis(int i) { return sqrt((x - a[i]) * (x - a[i]) + y * y); } double cas1(int l, int r) { return a[r] - a[l] + min(dis(l), dis(r)); } double cas2(int l, int r) { return a[r] - a[l] + min(dis(l) + fabs(mx -...
Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original...
import sys s = sys.stdin.readline().split() n = int(s[0]) m = int(s[1]) cells = set([]) even = (n%2 == 0) if even: central = set([]) for i in xrange(n//2+1,n): cells.add((n-i+1,1)) cells.add((1,i)) cells.add((i,n)) cells.add((n,n-i+1)) else: x = n//2 + 1 central...
Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance. The Hamming distance between two strings s = s1s2... sn and t = t1t2... tn of equal length n is value <image>. Record [si ≠ ti] is the Iverson notation and represents the following: if si ≠ ti, it is one, otherwise — zero. ...
import java.io.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.So...
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
from Queue import * # Queue, LifoQueue, PriorityQueue from bisect import * #bisect, insort from datetime import * from collections import * #deque, Counter,OrderedDict,defaultdict #set([]) import calendar import heapq import math import copy import itertools import string myread = lambda : map(int,raw_input().split()...
This is yet another problem on regular bracket sequences. A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequenc...
#include <bits/stdc++.h> using namespace std; char str[50010]; int cnt = 0, a, b; int len; long long ans; struct cost { int p, v; bool operator<(const cost& a) const { return v < a.v; } }; priority_queue<cost> q; cost make(int p, int v) { return {p, v}; } int main() { scanf("%s", str); len = strlen(str); ans ...
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
n=int(input()) a=list(map(int,input().split())) oc=0 cc=0 ans=0 for i in a: if i>0: oc+=i elif oc==0: ans+=1 else: oc-=1 print(ans)
Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her n toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still ca...
def combinacoes(x): # Se for apenas 1 elemento retorna 1 arranjo if x == 1: return [[0]] else: # Adiciona os elementos a lista auxiliar aux = combinacoes(x - 1) pilha = [] par = 0 # Percorre a lista juntando os elementos nas possibilidades possíveis for element in aux...
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of n segments. Each segment was either horizontal or vertical. Now the fr...
#include <bits/stdc++.h> using namespace std; struct event { int x, type, y, righty; }; struct P { int right, dsu, number; }; int xbegin[1000000], compcount, fen[1000000], xend[1000000], ybegin[1000000], yend[1000000], realx[1000000], realy[1000000], parent[1000000]; event events[1000000]; long long ans[1000000...
Mike is trying rock climbing but he is awful at it. There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In othe...
import java.util.*; public class MinimumDifficulty{ //496A public static void main(String[] args) { @SuppressWarnings("resource") Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=scn.nextInt(); int max=Integer.MIN_VALUE, min=Integer.MAX_VALUE;...
Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression. In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ...,...
#include <bits/stdc++.h> using namespace std; int a[100005]; int b[100005]; int n; bool solve1(int m) { for (int i = 1; i < m - 1; i++) if (b[i] * 1LL * b[i] != b[i - 1] * 1LL * b[i + 1]) { return false; } return true; } void solve() { if (n <= 2 && a[0] != 0) { puts("0"); return; } int ...
In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road. Check if is it poss...
#include <bits/stdc++.h> using namespace std; const int N = 203; const int M = 700; const int MAXINT = 1 << 20; struct NetWorkFlow { struct Node { int fe, h, cur, v; }; struct Edge { int t, ne, f; }; Node a[N]; Edge b[M * 2]; int d[M]; int s, t, n, p; void clear(int nn, int ss, int tt) { n...
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample. Limak will repeat the following operation till everything is destroyed. Block is called internal if i...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class Blocks { void solve() { int n = in.nextInt(); int[] h = new int[n]; for (int i = 0; i < n; i++) h...
You are given a non-empty line s and an integer k. The following operation is performed with this line exactly once: * A line is split into at most k non-empty substrings, i.e. string s is represented as a concatenation of a set of strings s = t1 + t2 + ... + tm, 1 ≤ m ≤ k. * Some of strings ti are replaced by st...
#include <bits/stdc++.h> using namespace std; const int N = 5e6 + 10; int n, k, m, A[N], c[N], tlen, z[N << 1]; char s[N], t[N], S[N], T[N], SS[N << 1]; void check(int len) { for (int i = 1; i <= len; i++) { if (T[i] < S[i]) return; if (T[i] > S[i]) break; } for (int i = 1; i <= len; i++) T[i] = S[i]; r...
You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side. Let's call a connected component any non-extendible set of cells such that a...
import java.io.*; import java.util.ArrayList; import java.util.HashSet; /** * Created by ProDota2 on 07.01.2016. * name of project pcms2contest **/ public class Main implements Runnable{ int X , Y; public void run(){ Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(System...
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but ...
#include <bits/stdc++.h> using namespace std; int sa[4 * 200005], sb[4 * 200005], a, b, n = 200003; void modify_sa(int pos, int val, int id = 1, int l = 0, int r = n) { if (r - l < 2) { sa[id] += val; sa[id] = min(sa[id], a); return; } int mid = (l + r) / 2; if (pos < mid) modify_sa(pos, val, 2 ...
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Amo...
import java.util.Scanner; public class Codeforces { public static int getYear(int y, int len) { int mod = 10; int prev = y % 10; int prev_y = (prev < 9) ? 1990 + prev : 1989; mod *= 10; int next = y % mod, next_y = next; int i = 1; while (prev != y || i != le...
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: <image> Together with his old phone, he lost all his cont...
n = int(input()) s = input() fill = [[False for i in range(3)] for j in range(4)] for i in s: if i == "0": j = 10 else: j = ord(i)-ord('1') #0, 1, 2, 3... 8 fill[j//3][j%3] = True #for i in fill: # print(i) top = fill[0][0] or fill[0][1] or fill[0][2] bottom = fill[2][0] or fill[3][1] or ...
zscoder wants to generate an input file for some programming competition problem. His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor. Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a'...
#include <bits/stdc++.h> using namespace std; long long x, y, r[20000001]; int n; long long dp(int a) { if (r[a]) return r[a]; if (a == 1) r[a] = x; else if (a % 2) r[a] = x + min(dp(a - 1), dp(a + 1)); else r[a] = min(y + dp(a / 2), x * (a / 2) + dp(a / 2)); return r[a]; } int main() { scanf("%...
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them. The game they came up with has the following rules. In...
#include <bits/stdc++.h> using namespace std; inline long long read() { register long long x = 0, f = 0; register char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = 1; c = getchar(); } while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + (c ^ '0'), c = getchar(); return f ? -x ...
PolandBall is standing in a row with Many Other Balls. More precisely, there are exactly n Balls. Balls are proud of their home land — and they want to prove that it's strong. The Balls decided to start with selecting exactly m groups of Balls, each consisting either of single Ball or two neighboring Balls. Each Ball ...
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; const int N = 1 << 15; int Jie[N], inv[N], jie[N]; inline int mul(const int &a, const int &b) { return 1ll * a * b % mod; } inline void add(int &a, const int &b) { a += b; if (a >= mod) a -= mod; return; } inline int C(int m, int n) { return...
Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess...
def nap(y): if y==0: p=[0,1,2] return p if y==1: p=[1,0,2] return p if y==2: p=[1,2,0] return p if y==3: p=[2,1,0] return p if y==4: p=[2,0,1] return p if y==5: p=[0,2,1] return p n=int(input()) x=int...
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order. You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions. Find the maximum value ...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pll = pair<ll, ll>; using vll = vector<ll>; using vpll = vector<pll>; struct d_ { template <typename T> d_& operator,(const T& x) { cerr << ' ' << x; return *this; } template <typename T> d_& operator,(co...
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo...
arr1 = input().split() a = int(arr1[0]) b = int(arr1[1]) c = int(min(a, b)) res = 1 for i in range(2, c+1): res *= i print(res)
The elections to Berland parliament are happening today. Voting is in full swing! Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 ≤ k ≤ n) top candidates will take seats in the parliament. After the end of the voting the number of votes for each candidate is calculated. I...
#include <bits/stdc++.h> using namespace std; int main() { int n, k, m, a; scanf("%d %d %d %d", &n, &k, &m, &a); vector<int> votes(n, 0); vector<int> last(n, -1); for (int i = 0; i < a; i++) { int foo; scanf("%d", &foo); foo--; votes[foo]++; last[foo] = i; } vector<bool> chance(n, fals...
Rock... Paper! After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows. A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted ...
#include <bits/stdc++.h> using namespace std; const int N = 2005; int n, ans; int a[N], b[N], cnt[8000005]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", a + i); cnt[a[i]] = 1; } for (int i = 1; i <= n; i++) { scanf("%d", b + i); cnt[b[i]] = 1; } for (int i = 1; i ...
Ralph is going to collect mushrooms in the Mushroom Forest. There are m directed paths connecting n trees in the Mushroom Forest. On each path grow some mushrooms. When Ralph passes a path, he collects all the mushrooms on the path. The Mushroom Forest has a magical fertile ground where mushrooms grow at a fantastic ...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int NINF = 0xc0c0c0c0; const int maxn = 1e6 + 5; struct Edge { int u, v, w; }; Edge edges[maxn]; long long dp[maxn]; long long val[maxn]; int scc, Index, top; vector<pair<int, int> > G_new[maxn]; vector<int> G[maxn]; int Stack[maxn], low[...
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to kno...
#include <bits/stdc++.h> using namespace std; int main() { long long hh, mm, x, ans = 0; cin >> x >> hh >> mm; while (hh % 10 != 7 && mm % 10 != 7) { mm -= x; if (mm < 0) { mm = mm + 60; hh = hh - 1; } if (hh < 0) { hh = 23; } ans++; } cout << ans; return 0; }
Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby. Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters. Dima can buy boxes at a factory. The factory pr...
#include <bits/stdc++.h> using namespace std; int main() { long long int n; long long int k; cin >> n; cin >> k; long long int arr[k]; for (long long int i = 0; i < k; i++) cin >> arr[i]; long long minrem = n % arr[0]; long long number = 0; long long pos = 0; for (long long int i = 0; i < k; i++) { ...
You are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges). A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted. Destroy all vertices in the given tree or...
#include <bits/stdc++.h> using namespace std; void read_file(bool outToFile = 1) { freopen("in", "r", stdin); if (outToFile) freopen("out", "w", stdout); } vector<int> v[300005]; bool dp[300005][2]; int ed[300005]; int ze[300005]; int bo[300005]; int on[300005]; int P[300005]; void dfs(int node, int p = -1) { P[n...
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all. ...
#include <bits/stdc++.h> using namespace std; vector<long long> fact(20); vector<int> f_cnt(10); void precalc() { fact[0] = 1; for (int i = 1; i < 20; i++) fact[i] = fact[i - 1] * i; } int main() { set<vector<int> > st; long long ans(0); string s; cin >> s; int n = s.length(); for (int i = 0; i < n; i++...
Arjit has his own printing press, Bainik Dhaskar (BD). He feels that words on their own simply aren't beautiful enough. So, he wishes to make a Super Manuscript (SM) machine. Now what does this machine do? The SM machine aims to make words as beautiful as they can be by making a word as lexicographically small as possi...
__author__ = 'Siddharth' if __name__ == "__main__": T = int(raw_input()) for t in xrange(T): W = raw_input().strip() R = sorted(raw_input().strip()) X = [] r = 0 for w in W: if r < len(R): if R[r] < w: X.append(R[r]) ...
Akhil gives Ramesh an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero. Formally, find an i, such th...
for _ in range(input()): n=input() arr=map(int,raw_input().split()) total=0 for item in arr: total+=item prevsum=0 current_item=0 flag=1 for key in arr: current_item=key x=(total - current_item)-prevsum if x==prevsum: print "YES" flag=5 break prevsum=prevsum+current_item if flag==1: pri...
DJ Boy is a new generation child he has never seen numeric keypad of mobile. So one day when Prem showed him his mobile, DJ boy started laughing on him. Prem being smart gave him a problem to solve with some condition. Your task is to help DJ boy to solve this problem: Given a number N, DJ boy has to tell how many num...
maxn=10000 mod=10**9+9 d=[] for i in xrange(0,10): d.append([0]*(maxn+1)) d[i][0]=0 d[i][1]=1 for z in xrange(2,(maxn+1)): d[0][z] = d[0][z-1] + d[8][z-1] d[1][z] = d[1][z-1] + d[2][z-1] + d[4][z-1] d[2][z] = d[2][z-1] + d[1][z-1] + d[5][z-1] + d[3][z-1] d[3][z] = d[3][z-1] + d[2][z-1] + d[6][z-1] d[4][z] = d[4...
Gopal is climbing the stairs. He can jump 1 or 2 or 3 steps at a time. He wants to climb N steps. In how many ways can he reach the Nth step? As the answer can be too large Output it modulo 10^9+7. Input: First line of the input contains an integer T denoting the number of test cases. Then T lines follow each line con...
''' # 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=input() s=[0]*100001 s[1]=1 s[2]=2 s[3]=4 for i in range(4,100001): s[i]=(s[i-1]+s[i-2]+s[i-3])%1000000007 while t>0: t-=1 n=input() print s[n]
Little Jhool is an addict. No, unlike the usual drug addicts, he's an addict of the good kind: the shopping addict. Some of his friends also call him a shopaholic, though he tries his level best to deny the title given to him by his friends. Now, he has some favorite websites as we already have seen in another question...
def solve(xs, k): xs.sort() pairs = [x + y for x, y in zip(xs[:len(xs) / 2], xs[len(xs) / 2:][::-1])] diff = max(pairs) - min(pairs) if diff < k: res = "Chick magnet Jhool!" elif diff == k: res = "Lucky chap!" else: res = "No more girlfriends!" return '{}\n{}'.format(diff, res) if __name__ ...
Let us look at the close relative of Fibonacci numbers, called the Phibonacci numbers. They work exactly like Fibonacci numbers. F (1) = 0, F(1) = 1, F(2) = 1, and then F (n) = F ( n - 1 ) + F ( n - 2 ). In number theory, the n^th Pisano period, written as ? (n), is the period with which the sequence of Fibonacci numbe...
''' ans = 0 if(A <= 7 && B >= 7) ans += 8 if(A <= 13 && B >= 13) ans += 144 print ans ''' from sys import stdin t = int(stdin.readline()) for _ in xrange(t): a,b = map(int,stdin.readline().split()) ans = 0 if a<=7 and b>=7: ans += 8 if a <=13 and b >=13: ans += 144 print ans
Prateek wants to give a party to his N friends on his birthday, where each friend is numbered from 1 to N. His friends are asking for a gift to come to the party, instead of giving him one. The cost of the gifts are given in the array Value where i^th friend asks for a gift which has a cost Costi. But, Prateek has o...
T = int(raw_input()) output = [] for i in xrange(T): inp =raw_input().split(' ') N = int(inp[0]) X = int(inp[1]) Value = [] for j in xrange(N): Value.append(int(raw_input())) sumArr = 0 index = 0 for i in range(len(Value)): sumArr += Value[i] while(sumArr > X and ...
Samu's Birthday is near so she had started planning a party for all of her friends. Being a kind and caring girl she calls each of her friend and asks for his/her favorite dish.Now each friend has own liking/disliking for different dishes. A friend can only like or dislike a dish it means if we are having three dishe...
for t in range(input()): n,k = map(int,raw_input().split()) a=[0]*n for i in range(n): a[i] = int( raw_input(), 2 ) p=pow(2,k) ans = k for v in range(p): f=1 for x in a: if v&x == 0: f=0 break if f: ans = min( ans, bin(v).count('1') ) print ans
Sumit had borrowed money from many of his batch mates and today he has decided to pay them because he has got lottery today. The amount of lottery is very large. So to count the money he decided to write the amount in Indian system first. In the Indian system the rightmost comma is placed after three rightmost digit...
import sys t=int(raw_input()) while t>0: t-=1 a=raw_input() l=len(a) if l<=3: print a else: ll=l-3 i=0 if ll%2==0: while i < l-3: sys.stdout.write(a[i]) i+=1 sys.stdout.write(a[i]) i+=1 sys.stdout.write(',') else: sys.stdout.write(a[0]) sys.stdout.write(',') i=1 whi...
Somewhere in Andromeda, (yeah our neighbor galaxy!) Mystery Land, is having some signs of life. We just have found stairs there. But with different heights of each step. Pictorially the stairs are like this: The width of each step is same W, but for each stair numbered 'i', the total height of block of with W used f...
def solve(): [W,N]=[int(x) for x in raw_input().split()] ans = W*N #print ans a=[int(x) for x in raw_input().split()] i=N-1 while i>=0: if a[i] == 1: break i -= 1 cur = 2*(i+1) i += 1 while i<N: cur = cur + 1 i += 1 print ans + cur def main(): for _ in xrange(int(raw_input())): s...
You will be given a contest schedule for D days and M queries of schedule modification. In the i-th query, given integers d_i and q_i, change the type of contest to be held on day d_i to q_i, and then output the final satisfaction at the end of day D on the updated schedule. Note that we do not revert each query. That ...
NTEST = 26 D=int(input()) C=list(map(int,input().split())) SL=list() SL.append([0 for i in range(NTEST)]) for d in range(D): S=list(map(int,input().split())) SL.append(S) tests=list() tests.append(0) for d in range(D): tests.append(int(input())) def calcSat(test_applied): lastDay = [0 for i in rang...
We have a grid with (2^N - 1) rows and (2^M-1) columns. You are asked to write 0 or 1 in each of these squares. Let a_{i,j} be the number written in the square at the i-th row from the top and the j-th column from the left. For a quadruple of integers (i_1, i_2, j_1, j_2) such that 1\leq i_1 \leq i_2\leq 2^N-1, 1\leq ...
#include <bits/stdc++.h> using namespace std; typedef long long int LL; typedef long long int ll; typedef pair<long long int, long long int> pii; typedef pair<double, double> pdd; #define SORT(c) sort((c).begin(),(c).end()) #define BACKSORT(c) sort((c).begin(),(c).end(),std::greater<LL>()) #define FOR(i,a,b) for(LL i...
It's now the season of TAKOYAKI FESTIVAL! This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i. As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points. There are \frac{N...
#include<bits/stdc++.h> using namespace std; int n,d[55],ans; int main(){ cin>>n; for(int i=1;i<=n;i++) cin>>d[i]; for(int i=1;i<n;i++) for(int j=i+1;j<=n;j++) ans+=d[i]*d[j]; cout<<ans; return 0; }
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i. Snuke will perform the following operation some number of times:...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 2100; int N; string S; vector <int> edge[MAXN]; int nnode[MAXN]; int ddep[MAXN]; int dmin[MAXN]; int ans; void flood (int cloc, int last) { int ntot = 0; int nbest = 0; int nmin = 0; nnode[cloc] = S[cloc] - '0'; ...
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i. There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N: * If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ld...
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int K = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); int DP[] = new int[n]; for (...
Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d. For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3. There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusi...
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.InputMismatchException; public class Main { InputStream is; ...
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces: * Form groups consisting of A_i children each! Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m...
from math import ceil def solve(rounds): mx, mn = 3, 2 if rounds[-1] != 2: return (-1,) for r in reversed(rounds[:-1]): if mx < r: return (-1,) mn = ceil(mn / r) * r mx = mx // r * r + r - 1 if mn > mx: return (-1,) return mn, mx k = int(input(...
Snuke lives at position x on a number line. On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery. Snuke decided to get food delivery from the closer of stores A and B. Find out which store is closer to Snuke's residence. Here, the distance between two points s and...
#include<bits/stdc++.h> using namespace std; int main() { int a,b,x; cin>>x>>a>>b; if(abs(x-a)<abs(x-b))cout<<'A'<<endl; else cout<<'B'<<endl; return 0; }
AtCoDeer the deer found N rectangle lying on the table, each with height 1. If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure: <image> AtCoDeer will move these rect...
#include <bits/stdc++.h> #define db double #define ls rt << 1 #define rs rt << 1 | 1 #define pb push_back #define ll long long #define mp make_pair #define pii pair<int, int> #define X first #define Y second #define pcc pair<char, char> #define vi vector<int> #define vl vector<ll> #define rep(i, x, y) for(int i = x - 1...
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically. <image> A pyramid with N=4 steps Snuke wrote a per...
import java.util.*; import java.io.*; import java.awt.geom.*; import java.math.*; public class Main { static final Scanner in = new Scanner(System.in); static final PrintWriter out = new PrintWriter(System.out,false); static boolean debug = false; static void solve() { int n = in.nextInt(); int x = in.nextIn...
A thief sneaked into a museum with a lot of treasures with only one large furoshiki. There are many things I want to steal, but the weight that the furoshiki can withstand is limited, and if it exceeds this, the furoshiki will tear. Therefore, the thief must consider a combination of treasures that will not break the p...
#include <iostream> #include <cstdio> #include <vector> using namespace std; int dp[1001][1001] = {0}; int main() { int W, N; int t = 1; while ( cin >> W, W ) { cin >> N; vector<int> v(N), w(N); for (int i = 0; i < N; ++i) { scanf("%d,%d", &v[i], &w[i]); } fill(&dp[0][0], &dp[0][0]+1001*1001, 0); fo...
It's been a while since I played with A, B, and C. Mr. A and Mr. B became players, and Mr. C became a referee and played a badminton singles game. The rules decided by the three people are as follows. * 3 Play the game. * The person who gets 11 points first wins the game. * The first serve of the first game starts wit...
import java.util.*; public class Main{ public static void main(String[]args){ new Main().run(); } Scanner sc = new Scanner(System.in); String s; int a, b; int game; void run(){ game = 0; while(sc.hasNext()){ s = sc.next(); solve(); game++; } } void solve(){ ...
The smallest unit of data handled by a computer is called a bit, and the amount of information that represents multiple bits together is called a word. Currently, many computers process one word as 32 bits. For a computer that represents one word in 32 bits, create a program that outputs the amount of data W given in ...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int h = scan.nextInt(); System.out.println(h * 32); } }
problem To the west of the Australian continent is the wide Indian Ocean. Marine researcher JOI is studying the properties of N species of fish in the Indian Ocean. For each type of fish, a rectangular parallelepiped habitat range is determined in the sea. Fish can move anywhere in their habitat, including boundaries...
#include <cstdio> #include <algorithm> using namespace std; typedef long long Int; #define MAX_N 60 int N, K; Int X1[MAX_N], Y1[MAX_N], Z1[MAX_N]; Int X2[MAX_N], Y2[MAX_N], Z2[MAX_N]; int xsLen, ysLen, zsLen; Int xs[MAX_N * 2], ys[MAX_N * 2], zs[MAX_N * 2]; int main() { int i; int a, b, c; scanf("%d%d", &N, &K...
> I would, if I could, > If I couldn't how could I? > I couldn't, without I could, could I? > Could you, without you could, could ye? > Could ye? could ye? > Could you, without you could, could ye? It is true, as this old rhyme says, that we can only DO what we can DO and we cannot DO what we cannot DO. Changing ...
#include<iostream> #include<cstdio> #include<set> #include<map> #include<cmath> #include<cstdlib> #include<algorithm> #include<cstring> #include<cassert> #include<string> #include<vector> #include<queue> #define MAX_N 1000010 #define mp make_pair #define pb push_back #define fi first #define se second #define INF 10000...
The ACM ICPC judges are very careful about not leaking their problems, and all communications are encrypted. However, one does sometimes make mistakes, like using too weak an encryption scheme. Here is an example of that. The encryption chosen was very simple: encrypt each chunk of the input by flipping some bits acco...
#include <bits/stdc++.h> typedef long long LL; #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) using namespace std; void hex(LL n){ if(n/16) hex(n/16); LL las=n%16; if(las<10) cout << char(las+'0'); else cout << char(las-10+'a'); } LL solve(...
Problem D Making Perimeter of the Convex Hull Shortest The convex hull of a set of three or more planar points is, when not all of them are on one line, the convex polygon with the smallest area that has all the points of the set on its boundary or in its inside. Your task is, given positions of the points of a set, t...
#include<bits/stdc++.h> using namespace std; using DB = double; struct PT { int x, y; PT (int x = 0, int y = 0) : x(x), y(y) {} void in() { scanf("%d%d", &x, &y); } bool operator <(const PT &pts) const { return make_pair(x, y) < make_pair(pts.x, pts.y); } bool operator ==(const PT &pts) const { return make_pair(x...
Selection of Participants of an Experiment Dr. Tsukuba has devised a new method of programming training. In order to evaluate the effectiveness of this method, he plans to carry out a control experiment. Having two students as the participants of the experiment, one of them will be trained under the conventional metho...
#include <bits/stdc++.h> using namespace std; int a[1000]; int main() { int n; while(scanf("%d",&n),n) { for(int i=0;i<n;i++) scanf("%d",&a[i]); int ans=1<<30; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { ans=min(ans,abs(a[i]-a[j])); } printf("%d\n",ans); ...
At a certain research institute, I was developing a medium for energy transfer. This medium has a polymer structure consisting of a special substance as shown in Fig. 3. Structure of energy transfer medium. --- (-α-Ea-β-) n Figure 3: Structure of energy transfer medium. The part shown by Ea in the figure is the Energ...
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define EPS 0.000000001 using namespace std; #define NUM 81 int N; int energy[NUM]; bool dp[321][321][NUM]; void func(){ scanf("%d",&N); int sum = 0; for(int i = 0; i < N; i++)...
Alice and Bob were in love with each other, but they hate each other now. One day, Alice found a bag. It looks like a bag that Bob had used when they go on a date. Suddenly Alice heard tick-tack sound. Alice intuitively thought that Bob is to kill her with a bomb. Fortunately, the bomb has not exploded yet, and there ...
#include<bits/stdc++.h> #define MAX 1024 #define inf 1<<29 #define linf 1e16 #define eps (1e-6) #define mod 1000000007 #define pi acos(-1) #define phi (1.0+sqrt(5))/2.0 #define f first #define s second #define mp make_pair #define pb push_back #define all(a) (a).begin(),(a).end() #define pd(a) printf("%.10f\n",(double)...
Taro has decided to move. Taro has a lot of luggage, so I decided to ask a moving company to carry the luggage. Since there are various weights of luggage, I asked them to arrange them in order from the lightest one for easy understanding, but the mover left the luggage in a different order. So Taro tried to sort the l...
#include <bits/stdc++.h> using namespace std; using ll = long long; using vint = vector<int>; using vll = vector<ll>; constexpr ll LLINF = 1ll << 60; template<typename T> struct SegmentTree { T id; function<T(T, T)> op; vector<T> dat; int size; SegmentTree(int n, T id, function<T(T, T)> op) : id(id), op(op) { ...
Problem Statement We can describe detailed direction by repeating the directional names: north, south, east and west. For example, northwest is the direction halfway between north and west, and northnorthwest is between north and northwest. In this problem, we describe more detailed direction between north and west a...
#include <bits/stdc++.h> using namespace std; typedef long long Int; class Fraction{ public: Int numerator,denominator; }; void reduce(Fraction &); Int gcd(Int,Int); ostream &operator << (ostream &os,Fraction f){ reduce(f); if(f.numerator == 0){ os << "0"; }else if(f.denominator == 1){ os << f.nume...
Curry making As the ACM-ICPC domestic qualifying is approaching, you who wanted to put more effort into practice decided to participate in a competitive programming camp held at a friend's house. Participants decided to prepare their own meals. On the first night of the training camp, the participants finished the da...
#include "bits/stdc++.h" using namespace std; int main() { int R0, W0, C, R; while (cin >> R0 >> W0 >> C >> R) { if (R0 == 0 && W0 == 0 && C == 0 && R == 0) return 0; int LOSS = W0 * C - R0; if (LOSS <= 0) cout << 0 << endl; else if (LOSS % R == 0) cout << LOSS / R << endl; else cout << LOSS / R + 1 << end...
Revised The current era, Heisei, will end on April 30, 2019, and a new era will begin the next day. The day after the last day of Heisei will be May 1, the first year of the new era. In the system developed by the ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG), the date uses the Japanese calendar (the Japa...
import sys def solve(g, y, m, d): y = int(y) m = int(m) d = int(d) if y == 31 and m >= 5: print('?', y-30, m, d) elif y >= 32: print('?', y-30, m, d) else: print(g, y, m, d) while True: s = input() if s == "#": break solve(*map(str, s.split())...
Problem Given the strings $ s $, $ t $. First, let the string set $ A = $ {$ s $}, $ B = \ phi $. At this time, I want to perform the following operations as much as possible. operation step1 Perform the following processing for all $ u ∊ A $. 1. From all subsequences of $ u $ (not necessarily contiguous), choose ...
#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int,int> pii; #define rep(i,n) for(ll i=0;i<(ll)(n);i++) #define all(a) (a).begin(),(a).end() #define pb emplace_back #define INF (1e9+1) bool isSubstr(string &s, string &t){ int p = 0; rep(i,s.size()){ if(s[i]==t[p]){ ...
You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S. Notes Constraints * Elements in S is sorted in ascending order * n ≤ 100000 * q ≤ 50000 * 0 ≤ an element in S ≤ 109 * 0 ≤ an element in T ≤ 109 ...
#include <bits/stdc++.h> using namespace std; int main(){ int n,S[1001000],q,k,sum=0; cin>>n; for(int i=0;i<n;i++) cin>>S[i]; cin>>q; for(int i=0;i<q;i++){ cin>>k; if(*lower_bound(S,S+n,k)==k) sum++; } cout<<sum<<endl; }
Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string. Constraints * The length of the input string < 1200 Input A string is given in a line. Output Print the converted string in a line. Note that you do not need to convert any characters other than alphabetical lett...
t = input() t = t.swapcase() print(t)
You are given a uniformly randomly generated string S, consisting of letters from the set {"A", "B"}. Your task is to find a string T that appears in S as a subsequence exactly twice. In other words, you need to find such a string T, that there exist exactly two sets of indexes i1, i2, ..., i|T| and j1, j2, ..., j|T| s...
for t in xrange(int(raw_input())): s = raw_input() n = len(s) a = s.count('A') b = n-a if (a==2): print "A" elif (b==2): print "B" elif (n<4): print -1 else: if (s[0]=="A"): s = "B"+s else: s = "A"+s if (s[-1]=="A"): s = s+"B" else: s = s+"A" pos1 = s.find("ABBA") pos2 = s.find("B...
Chef has a box full of infinite number of identical coins. One day while playing, he made N piles each containing equal number of coins. Chef suddenly remembered an important task and left the room for sometime. While he was away, his newly hired assistant came across the piles and mixed them up while playing. When Che...
import sys def getMaxRep(list): count = 0 maxRep = None currRep = list[0] currCount = 1 i = 1 while i < len(list): if list[i] == currRep: currCount += 1 else: if currCount > count: count = currCount currRep = ...
Chef is giving a big party to all his friends and their relatives. Relatives of very far-away (by relation) will be present. Little Joe (uninvited) is curious to know how distant two people are, say X and Y. There are 6 fundamental relations: father relation, mother relation, son relation, daughter relation, brother re...
uniqueueId = 0 class Dictionary(object): #generic dectionary object def __init__(self, type): self.descriptor = type self.hashTable = {} def setKeyValPair(self, key, value): self.hashTable[key] = value def getValue(self, key): if key in self.hashTable: return self.hashTable[key] return None #helper ...
A set of N dignitaries have arrived in close succession at Delhi and are awaiting transportation to Roorkee to participate in the inaugural ceremony of Cognizance. Being big sponsors of Cognizance, it has been deemed unsuitable by the organizing team to arrange for more than one dignitary to travel in a single vehicle....
def getData(file): auta = [] prefs = {} n = int(file.readline()) for i in xrange(0,n): file.readline() for i in xrange(0,n): auta.append(file.readline().strip()) for i in xrange(0,n): prefs[i] = file.readline().strip().split(' ')[1:] return n, auta, prefs def feasible(prefs, i, ...
Arpit & Nikhil were bored from their usual routine of studying, so they decided to play a game. The game was as follows - Given a number N the player must subtract 1, 2 or 3 from N in order to make a number that is divisble by 4. The game will continue until any player is able to make such a number, the corresponding...
noc = input() while noc: noc -=1 curr = input() % 4 print "First" if curr else "Second"
Recently Chef become very much interested in perfect squares. We all know Chef and his weird interests. Anyways Chef will be soon writing his masters thesis on perfect squares revealing what-not-known properties of perfect squares. While doing his research, he happened to be confronted with some interesting perfect squ...
''' from collections import Counter import string,sys N = int(raw_input()); s = raw_input(); if N == 1: print s; sys.exit(0) sc = Counter(s) for i in range(N-1): st = raw_input(); stc = Counter(st) for i in list(string.ascii_lowercase): if sc.get(i) != None and stc.get(i) == None: sc.pop(i,None) ...
The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] — are not. A sequence of integers is called good if it can be divided into a positive number of good arrays....
#include <bits/stdc++.h> using namespace std; const int maxn = 1e3 + 7; const int mod = 998244353; int a[maxn], c[maxn][maxn]; long long dp[maxn]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]), dp[i] = 1; for (int i = 0; i <= n; i++) { c[i][0] = 1; for (int j = 1; ...
Vasya passes all exams! Despite expectations, Vasya is not tired, moreover, he is ready for new challenges. However, he does not want to work too hard on difficult problems. Vasya remembered that he has a not-so-hard puzzle: m colored cubes are placed on a chessboard of size n × n. The fact is that m ≤ n and all cubes...
#include <bits/stdc++.h> using std::sort; using std::swap; const int MAXN = 55; const int MAXM = 55; const int MAXS = 11111; int N, M; int Cnt; bool Inv = false; struct Pos { int x, y; Pos() {} Pos(int _x, int _y) { x = _x; y = _y; } void read() { scanf("%d%d", &x, &y); } }; bool operator==(Pos A, Pos...
In the last mission, MDCS has successfully shipped N AI robots to Mars. Before they start exploring, system initialization is required so they are arranged in a line. Every robot can be described with three numbers: position (x_i), radius of sight (r_i) and IQ (q_i). Since they are intelligent robots, some of them wil...
#include <bits/stdc++.h> using ll = long long; using namespace std; long long n, k; const long long maxn = 3e5 + 10; struct Point { long long p, l, r, len, q; }; Point a[maxn]; long long b[maxn], c[maxn]; inline long long low(const long long& x) { return x & -x; } inline void add(long long x, long long y) { for (; ...
There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly — you can find them later yourselves if you want. To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", ...
r = '6789TJQKA' ts = raw_input() c1, c2 = raw_input().split() if c1[1] == ts and c2[1] != ts: print 'YES' elif c1[1] == c2[1] and r.index(c1[0]) > r.index(c2[0]): print 'YES' else: print 'NO'
There are n houses along the road where Anya lives, each one is painted in one of k possible colors. Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color. H...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numberOfHouses = sc.nextInt(), numberOfColors = sc.nextInt(), counter = 1, previousHouse, max = 1; int[] theH...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with...
//https://codeforces.com/problemset/problem/109/A //A. Lucky Sum of Digits import java.util.*; import java.io.*; public class Lucky_Sum_Of_Digits{ public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(n...
There are m people living in a city. There are n dishes sold in the city. Each dish i has a price p_i, a standard s_i and a beauty b_i. Each person j has an income of inc_j and a preferred beauty pref_j. A person would never buy a dish whose standard is less than the person's income. Also, a person can't afford a dis...
#include <bits/stdc++.h> using namespace std; inline void read(int &x) { int v = 0, f = 1; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = v * 10 + c - '0'; while (isdigit(c = getchar())) v = v * 10 + c - '0'; x = v * f; } inline void read(long lon...
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle. A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen peop...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 9; const int Maxn = 2e5; namespace FastIO { inline int read() { int x = 0, F = 1; char ch = getchar(); while (ch < '0' || ch > '9') F = (ch == '-') ? -1 : 1, ch = getchar(); while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch & 15), ...
A tournament is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes u and v (u ≠ v) exists either an edge going from u to v, or an edge from v to u. You are given a tournament consisting of n vertexes. Your task is to find there a...
#include <bits/stdc++.h> using namespace std; int n; char m[5005][5005], vis[5005]; bool bfs(int u, int pre) { vis[u] = 1; for (int i = 1; i <= n; i++) if (m[u][i] == '1') { if (m[i][pre] - '0') { printf("%d %d %d\n", pre, u, i); return 1; } if (!vis[i] && bfs(i, u)) return 1; ...
There is a square grid of size n × n. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs max(h, w) to color a rectangle of size h × w. You are to make all cells white for minimum total cost. Input The first line c...
#include <bits/stdc++.h> using namespace std; int k, i, n, j, ii, jj, f[51][51], d[51][51][51][51], val; char c[51][51]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) cin >> c[i][j]; for (i = 1; i <= n; i++) ...
Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string...
a=int(input()) s=input() r=input() cmap=[] tmap=[] for i in range(len(s)): if(s[i]=='a' and r[i]=='b'): cmap.append(i) elif(s[i]=='b' and r[i]=='a'): tmap.append(i) r=len(cmap) t=len(tmap) if(((r%2==1 and t%2==0) or (r%2==0 and t%2==1))): print(-1) else: total=r//2+t//2 if(r...
You have a password which you often type — a string s of length n. Every character of this string is one of the first m lowercase Latin letters. Since you spend a lot of time typing it, you want to buy a new keyboard. A keyboard is a permutation of the first m Latin letters. For example, if m = 3, then there are six ...
#include <bits/stdc++.h> using namespace std; const int N = 22, M = 100005, INF = 1000000009; int m, n; char a[M]; int q[N][N]; int dp[1 << N]; int main() { scanf("%d%d", &m, &n); scanf(" %s", a); for (int i = 0; i < m - 1; ++i) { q[a[i] - 'a'][a[i + 1] - 'a']++; q[a[i + 1] - 'a'][a[i] - 'a']++; } for...
You are given two strings s and t both of length n and both consisting of lowercase Latin letters. In one move, you can choose any length len from 1 to n and perform the following operation: * Choose any contiguous substring of the string s of length len and reverse it; * at the same time choose any contiguous ...
#include <bits/stdc++.h> using namespace std; int MAX(int m1 = INT_MIN, int m2 = INT_MIN, int m3 = INT_MIN, int m4 = INT_MIN, int m5 = INT_MIN, int m6 = INT_MIN, int m7 = INT_MIN, int m8 = INT_MIN, int m9 = INT_MIN, int m10 = INT_MIN) { return max(max(max(max(m1, m2), max(m3, m4)), max(m5, m6)), ...
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning: * If ℓ = 0, then the cursor...
for _ in range(int(input())): x = int(input()) s = input() l = 0 while(len(s)<x): s += s[l+1:]*(int(s[l])-1) l+=1 count=len(s) for k in range(l,x): count+=((count-k-1)*(int(s[k])-1)) count%= 1000000007 print(count)
Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n × n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain onl...
#include <bits/stdc++.h> using namespace std; short lastrow[1002]; int main() { int n, r, c, p, remember; cin >> n; lastrow[0] = n - 1; lastrow[n - 1] = 0; for (r = 0; r < n - 1; r++) { for (p = 0, c = r; c < r + n; c++, p++) { if (p == r) { cout << "0 "; if (c < n) remembe...
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); ; long long int t, i; cin >> t; int m, n, p, j, e; for (i = 0; i < t; i++) { cin >> m; int arr[m]; for (j = 0; j < m; j++) cin >> arr[j]; sort(arr, arr + n); int fl...
You are given an array a consisting of n elements. You may apply several operations (possibly zero) to it. During each operation, you choose two indices i and j (1 ≤ i, j ≤ n; i ≠ j), increase a_j by a_i, and remove the i-th element from the array (so the indices of all elements to the right to it decrease by 1, and n...
#include <bits/stdc++.h> template <typename int_t> inline int_t lowbit(int_t x) { return x & -x; } inline int h_bit(unsigned long long x) { return int(sizeof(unsigned long long) * 8 - __builtin_clzll(x)); } unsigned long long pow2(unsigned long long x) { return x == lowbit(x) ? x : 1ull << h_bit(x); } template <t...
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must ...
t = int(input()) for _ in range(t): n,m = map(int,input().split()) l = [] s = 0 t1,t2 = 0,0 for i in range(n): l1 = list(map(int,input().split())) l.append(l1) for i in range(n): f = 1 for j in range(m): if l[i][j] == 1: f = 0 if f: t1 += 1 for i in range(m): f = 1 for j in range(n): ...
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
t = int(input()) input_list = [[0,0,0] for i in range(t)] for i in range(t): x,y,z = input().split() input_list[i][0] = int(x) input_list[i][1] = int(y) input_list[i][2] = int(z) ans_list = ["NO" for i in range(t)] output_list = [[0,0,0] for i in range(t)] for i in range(t): x,y,z = input_list[i] ...
You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≤ i≤ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≤ n, b_i≥ b_{i-1} must hold * c is non-increasing, which means that for every 1<...
#include <bits/stdc++.h> using namespace std; int n; int main() { scanf("%d", &n); vector<long long> a(n + 2); for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); vector<long long> f(n + 2); f[1] = a[1]; for (int i = 2; i <= n; i++) { f[i] = a[i] - a[i - 1]; } long long sum = a[1]; for (int i = 2; ...
You have a blackboard and initially only an odd number x is written on it. Your goal is to write the number 1 on the blackboard. You may write new numbers on the blackboard with the following two operations. * You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the ...
#include <bits/stdc++.h> std::set<long long> Set; const long long maxn = 4e18; long long S[1000005], BIT[64], cnt; long long read() { char c = getchar(); long long ans = 0; bool flag = true; while (c < '0' || c > '9') flag &= (c != '-'), c = getchar(); while (c >= '0' && c <= '9') ans = ans * 10 + c - '0', c ...
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j. In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more...
#include<cstdio> #include<iostream> #include<queue> #include<algorithm> #include<cstring> #include<set> #include<vector> #include<cmath> #define PII pair<int,int> #define pb push_back #define ep emplace_back #define mp make_pair #define fi first #define se second using namespace std; inline int read(){ int x=0,f=1;cha...