input
stringlengths
29
13k
output
stringlengths
9
73.4k
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and swap specified elements by a list of the following operation: * swapRange($b, e, t$): For each integer $k$ ($0 \leq k < (e - b)$, swap element $(b + k)$ and element $(t + k)$. Constraints * $1 \leq n \leq 1,000$ * $-1,000,000,0...
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <map> #include <numeric> #include <string> #include <cmath> #include <iomanip> #include <queue> #include <list> #include <stack> #include <cctype> #include <cmath> using namespace std; /* typedef */ typedef long long ll; /* consta...
Recently Johnny have learned bogosort sorting algorithm. He thought that it is too ineffective. So he decided to improve it. As you may know this algorithm shuffles the sequence randomly until it is sorted. Johnny decided that we don't need to shuffle the whole sequence every time. If after the last shuffle several fir...
def gcd(a,b): if b==0: return a return gcd(b,a%b) def simplify(a,b): g=gcd(a,b) return (a/g,b/g) E = {0:(0,1), 1:(1,1), 2:(2,1)} for i in xrange(3,151): a,b=E[i-1] c,d=E[i-2] E[i]=simplify(b*d*(i*i-3*i+3)+2*a*d*(i-1)-b*c,b*d*(2*i-3)) t=input() while t: t-=1 n=input() a,b=E[n] if b>1: print "%d/%d" % (...
Chef had a hard time arguing with his friend, and after getting a great old kick Chef saw a colored array with N cells, numbered from 1 to N. The kick was so strong that Chef suddenly understood the rules of the game. Each cell is painted with a color. Here the colors are numbered from 1 to M. For any cell i, Chef c...
t = int(raw_input()) for _ in range(t): n, m, k = map(int, raw_input().split()) a = map(int, raw_input().split()) b = [] # gain for _ in range(n): b.append(map(int, raw_input().split())) c = [] # loss for _ in range(n): c.append(map(int, raw_input().split())) init_...
Two players are playing a game. The game is played on a sequence of positive integer pairs. The players make their moves alternatively. During his move the player chooses a pair and decreases the larger integer in the pair by a positive multiple of the smaller integer in the pair in such a way that both integers in the...
#!/usr/bin/env python #-*- coding:utf-8 -*- def convert_pair(a, b): res = [] if a < b: a, b = b, a while b: res.append(a / b) a, b = b, a % b res[-1] -= 1 while res[-1] == 0: del res[-1] return tuple(res) def grundy(col): res = 0 for N in reversed(col)...
Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Chef has a positive integer N. He can apply any of the following operations as many times as he want...
t=input() while t: t-=1 n=raw_input().strip() print len(n)-n.count('4')-n.count('7')
In PrimeLand, there existed a very handsome young prince named Prima. He greatly desired the Princess of Mathematics – Facie. However, before accepting his hand in marriage, Facie asked Prima to solve the following problem: The figure below shows a simple multiplication problem. However, not all the decimal digits ar...
def isvalid(s, c): if c.difference(s): return False return True def main(): n = input() l = raw_input().split() s = set(l) answer = 0 for _ in xrange(111, 1000): a = [i for i in str(_)] if isvalid(s, set(a)): for __ in xrange(11, 100): b = ...
You are given a square with 'n' points on each side of the square. None of these points co-incide with the corners of this square. You have to compute the total number of triangles that can be formed using these '4n' points (n points on each side of the square) as vertices of the triangle. Input First line contains ...
t = int(input()) for i in range(t): n = int(input()) print(int(10 * n * n * n - 6 * n * n))
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table. Recently scientists discovered that for every four...
#include <bits/stdc++.h> using namespace std; const int N = 4e5 + 10; int fa[N]; int n, m, q; int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); } void solve() { scanf("%d%d%d", &n, &m, &q); for (int i = 1; i <= n + m; i++) { fa[i] = i; } int res = n + m - 1; for (int i = 1; i <= q; i++) { ...
You are given an array a of n integers and an integer s. It is guaranteed that n is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s. The median of the array with odd length is the ...
# -*- coding: utf-8 -*- # @Date : 2018-09-03 08:46:01 # @Author : raj lath (oorja.halt@gmail.com) # @Link : http://codeforces.com/contest/1037/problem/B # @Version : 1.0.0 import os from sys import stdin max_val=int(10e12) min_val=int(-10e12) def read_int() : return int(stdin.readline()) def read_ints() ...
Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res). Each item belongs to one class. In this problem we will only consider three of such...
#include <bits/stdc++.h> using namespace std; int n, m; struct lut { string name; int cl; int val; int size; }; struct an { string name; string whr; int cl; int val; int num; }; vector<lut> l; vector<an> anim; vector<an> d[3]; vector<bool> used; int all_size; void Inputdata() { cin >> n; l.resize(...
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago. You are given a connected undirected graph with n vertices and m weighted edges. There are k special vertices: x_1, x_2, …, x_k. Let's define the cost of the path as the maximum weight of the edges in it. And th...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.util.Collec...
This is an interactive task. Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below. There are 666 black rooks and 1 white king on the chess board of size 999 × 999. The white king wins if he gets checked by rook...
import java.util.*; public class Main { public static Scanner sc = new Scanner(System.in); public static Pair king; public static Pair []rook = new Pair[666]; public static boolean finished; public static boolean checkWhereCorner = false; public static long movX; public static long movY; ...
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit afte...
import java.util.*; import java.io.*; public class a { public static void main(String[] Args) throws Exception { FS sc = new FS(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = sc.nextInt(); int m = sc.nextInt(); ...
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace. The Word of Uni...
#include <bits/stdc++.h> using namespace std; void fast() { ios_base::sync_with_stdio(false); cin.tie(NULL); } vector<string> vec_splitter(string s) { s += ','; vector<string> res; while (!s.empty()) { res.push_back(s.substr(0, s.find(','))); s = s.substr(s.find(',') + 1); } return res; } void deb...
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem. Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa...
#include <bits/stdc++.h> using namespace std; int main() { string s; int n; cin >> n >> s; int cnt0 = 0, cnt1 = 0; for (int i = 0; i < n; i++) { if (s[i] == '0') { cnt0++; } else cnt1++; } if (cnt0 != cnt1) { cout << "1" << endl; cout << s << endl; } else { cout << "2" <<...
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: * f(0) = a; * f(1) = b; * f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de...
import java.io.*; import static java.lang.Integer.parseInt; import java.util.*; import javax.swing.*; public class Start { public static void main(String arge[]) throws IOException { BufferedReader in =new BufferedReader(new InputStreamReader(System.in)); StringBuilder out =new StringBuilder(); String...
Your math teacher gave you the following problem: There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], …, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l ≤ x ≤ r. The length of the segment [l; r] is equal to r - l. Two segments [a; b] and [c; d] have a common point (inters...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n, i; cin >> n; int l[n], r[n]; for (i = 0; i < n; i++) { cin >> l[i] >> r[i]; } if (n == 1) cout << 0 << endl; else { ...
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is cons...
#include <bits/stdc++.h> using namespace std; int f(string s) { int k = 0; for (int i = 0; i < s.size(); i++) k = 10 * k + int(s[i]) - 48; return k; } int main() { int n, k, l, m, i, j; int x3, y3, x4, y4, a, b, x1, x2, y1, y2; cin >> a >> b >> x1 >> y1 >> x2 >> y2; if (x1 + y1 >= 0) x3 = (x1 + y1) / ...
You are given a positive integer m and two integer sequence: a=[a_1, a_2, …, a_n] and b=[b_1, b_2, …, b_n]. Both of these sequence have a length n. Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [...
import sys input=sys.stdin.readline from collections import deque n,m=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() b.sort() a=deque(a) b=deque(b) ans=0 for _ in range(n): if a==b: break f=1 for j in range(n-1): if b[j+1]-a[j+1]!=b[j]-a[j]: f=0 break i...
You're given an array a_1, …, a_n of n non-negative integers. Let's call it sharpened if and only if there exists an integer 1 ≤ k ≤ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: * The arrays [4], [0, 1], [...
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) rok = True rrok = True if n == 2 and a[0] == 0 and a[1] == 0: print("No") else: if n%2 == 0: ar = [0]*n for i in range(n//2): ...
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again. You know that you ...
from sys import stdin from bisect import bisect_left from collections import Counter for k in range(int(stdin.readline())): n,m=[int(x) for x in stdin.readline().split()] s=input() d=Counter(s) l=list(map(int,stdin.readline().split())) l.sort() ans=[0 for j in range(0,26)] for j in range(0,l...
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level. All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases...
T=int(input()) list=[] c=-1 d=-1 for i in range(T): n=int(input()) k="Yes" for j in range(n): a,b=map(int,input().split()) if a>=b and c<=a and d<=b and (b-d)<=(a-c): g=0 else: k="No" c=a d=b c=-1 d=-1 list.append(k) for i in range(len(list)): print(list[i])
The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd. You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n...
# Why do we fall ? So we can learn to pick ourselves up. from math import pi,cos t = int(input()) for _ in range(0,t): n = int(input()) theta = pi/4 delta = pi/n maxi,mini,x = 0,0,0 for i in range(0,2*n): x += cos(theta) theta -= delta maxi = max(maxi,x) mini = min(m...
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
t=int(input()) for i in range(t): n=int(input()) if n==1: print(0) else: if n%3!=0: print(-1) else: threes=0 twos=0 while n%3==0: threes+=1 n=n//3 while n%2==0: twos+=1 ...
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("avx2") using namespace std; const int BUBEN = 550; const int MOD = 1e9 + 7; const int BASE = 29; const int MOD1 = 998244353; const int BASE1 = 31; char _getchar_nolock() { return getchar_unlocked(); } char _p...
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened. Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional de...
import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)] def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)]...
You are given an array a_1, a_2, …, a_n of integers. This array is non-increasing. Let's consider a line with n shops. The shops are numbered with integers from 1 to n from left to right. The cost of a meal in the i-th shop is equal to a_i. You should process q queries of two types: * 1 x y: for each shop 1 ≤ i ≤ ...
#include <bits/stdc++.h> using namespace std; template <class T> using vc = vector<T>; template <class T> using vvc = vc<vc<T>>; template <class T> void mkuni(vector<T> &v) { sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); } long long rand_int(long long l, long long r) { static mt19937_64 ...
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades. Orpheus, a famous poet, and musician plans to calm Cerberus with his poe...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define FOR(i, st, n) for (int i = st; i < n; i++) const int INF = 1e9+100; int main(){ ios::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while (t--){ string s; cin>>s; int n = s.size(); int ans = 0; for (int i = 0; i < n-1;...
A permutation — is a sequence of length n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] — permutations, and [2, 3, 2], [4, 3, 1], [0] — no. Polycarp was recently gifted a permutation a[1 ... n] of length n. Polycarp likes trees more than permutations, s...
//firstly save by ctrl+s before running the code //press f5 to debug and input in terminal //typcast by e.g (long long)variable and for constant e.g 5ll //----------------------------------------------------------------------------------------------------------------------------- //count set bits using __builtin_popcou...
Let us denote by d(n) the sum of all divisors of the number n, i.e. d(n) = ∑_{k | n} k. For example, d(1) = 1, d(4) = 1+2+4=7, d(6) = 1+2+3+6=12. For a given number c, find the minimum n such that d(n) = c. Input The first line contains one integer t (1 ≤ t ≤ 10^4). Then t test cases follow. Each test case is char...
//#pragma GCC optimize ("O3", "unroll-loops") //#pragma GCC target ("avx2") //#pragma comment(linker, "/stack:200000000") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <bits/stdc++.h> #define LL long long #define PII pair<int, int> #define PLL pair<LL, LL> #define all_of(v) (v...
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — a and b. The order of the numbers is not important. Let's consider a ≤ b for the sake of definiteness. The players can cast one of the two spells in turns: * Replace b with b - ak. Number k can be chosen by...
#include <bits/stdc++.h> using namespace std; bool check(long long a, long long b) { if (!a || !b) return false; if (a > b) swap(a, b); if (!check(a, b % a)) return true; return !(((b / a) % (a + 1)) & 1); } int main() { int T; cin >> T; for (; T; --T) { long long a, b; cin >> a >> b; printf("...
Flatland is inhabited by pixels of three colors: red, green and blue. We know that if two pixels of different colors meet in a violent fight, only one of them survives the fight (that is, the total number of pixels decreases by one). Besides, if pixels of colors x and y (x ≠ y) meet in a violent fight, then the pixel t...
#include <bits/stdc++.h> using namespace std; template <class T> inline void read(T& num) { num = 0; bool f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = 0; ch = getchar(); } while (ch >= '0' && ch <= '9') { num = num * 10 + ch - '0'; ch = getchar(); } num =...
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th...
import java.util.*; public class CodeForces236C{ public static void main(String[] args) { Scanner input = new Scanner(System.in); long n = input.nextLong(); if(n == 1){ System.out.println(1); } else if(n == 2){ System.out.println(2); } else if(n == 3){ System.out.println(6); } else{ if(n...
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way r...
inp=input() #1:37 start code adj={} rem=[] remv=set() vis=set() part=[] for i in xrange(inp-1): u,v=map(int,raw_input().split()) if u not in adj:adj[u]=[] if v not in adj:adj[v]=[] adj[u].append(v) adj[v].append(u) def dfs(node,before): vis.add(node) if node not in adj:return for i in ad...
Bessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help! A pair (x, y) of positive integers is "cool" if x can be expressed as the sum of y consecutive integers (not necessarily positive). A sequence (a1, a2...
#include <bits/stdc++.h> using namespace std; const int N = 5005; const int INF = 0x3f3f3f3f; int n; long long a[N], g[2][N]; int dp[2][N]; inline long long read() { long long f = 1, x = 0; char ch = getchar(); while (ch > '9' || ch < '0') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' &&...
Polycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to ta...
#include <bits/stdc++.h> long long ans; long long jc[4010]; long long c[4010][4010]; int w, n, b; int main() { int i, j; for (i = 0; i <= 4000; ++i) { c[i][0] = 1; for (j = 1; j <= i; ++j) { c[i][j] = c[i - 1][j] + c[i - 1][j - 1]; if (c[i][j] >= 1000000009) c[i][j] -= 1000000009; } } jc...
Don't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≤ x, y ≤ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transp...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9; const double eps = 1e-9; const double INF = inf; const double EPS = eps; int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int N[2][1100 * 1100 * 4]; long long T[110000]; int V[110000]; int main() { int x, y, n, q, a, b, c, d, bb, it; int i, j, ...
Given an n × n table T consisting of lowercase English letters. We'll consider some string s good if the table contains a correct path corresponding to the given string. In other words, good strings are all strings we can obtain by moving from the left upper cell of the table only to the right and down. Here's the form...
#include <bits/stdc++.h> using namespace std; inline int read() { int 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; } const int N = 1e5 + 10;...
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth...
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vl = vector<ll>; const int INF = 0x3f3f3f3f; template <class K, class V> ostream& operator<<(ostream& out, const pair<K, V>& v) { out << '(' << v.first << ',' << v.second << ')'; return out; } template <class C, class ...
You all know the Dirichlet principle, the point of which is that if n boxes have no less than n + 1 items, that leads to the existence of a box in which there are at least two items. Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. T...
#include <bits/stdc++.h> using namespace std; const double eps = 1e-8; map<pair<int, int>, int> Set; int a, b, n, ret; void init() { scanf("%d%d%d", &a, &b, &n); } int solve(int a, int b) { pair<int, int> cur = make_pair(a, b); if (Set.find(cur) != Set.end()) return Set[cur]; bool A = false, B = false; if (log(...
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation: <image> A swap operation is the following sequence of actions: * choose two indexes i, j (i ≠ j); * perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Serej...
//package codeforces; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; i...
Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y deno...
#include <bits/stdc++.h> long long memo[(1 << 21)]; long long modexp(long long a, long long n) { long long res = 1; while (n) { if (n & 1) res = ((res % 1000000007) * (a % 1000000007)) % 1000000007; a = ((a % 1000000007) * (a % 1000000007)) % 1000000007; n >>= 1; } return res; } int main(void) { s...
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the ...
#include <bits/stdc++.h> using namespace std; int main() { int t = 0, sl = 0; char s[100010]; cin >> s; for (int i = 0; i < strlen(s); i++) if (s[i] == '#') { t++; } else if (s[i] == '(') sl++; else sl--; if (sl <= 0) cout << "-1"; else { int t1 = 0, t2 = 0; for (in...
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n. This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, ...
#include <bits/stdc++.h> using namespace std; int a[220020], l, r, n, k, t, st, p; bool f[220020]; char s[100]; int main() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) { scanf("%s", s); if (s[0] == '?') f[i] = 0; else { f[i] = 1; sscanf(s, "%d", &a[i]); } } for (int i ...
You have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i....
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 21; const int maxs = 1 << 21; int n, m; int a[maxn][maxn]; char str[maxn][maxn]; int dp[maxs]; int lowzero(int s) { for (int i = 0; i < maxn; ++i) { if (!(s & (1 << i))) return i; } return maxn - 1; } int main() { whi...
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n. You need to permute the array elements so that value <image> became minimal possible. In particular, it is allowed not to change order of elements at all. Input The first line contains two integers n,...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; const ll inf = 1E17; const ll mod = 1; ll a[300010]; int n, k, chnk; ll dp[5001][5001]; ll solve(int pos, int xtra, int l) { if (pos == 0) { if (xtra == 0) return 0; return inf; } ll &...
BCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces. BCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team. <image> In B...
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; /** * Built using CHelper plug-in * Actual solution is at the top * @author Tifuera */ public class Main { publ...
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
import java.awt.*; import java.awt.geom.*; import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.stream.Collector; /** * Created by ribra on 11/15/2015. */ public class Main { private static InputReader sc = new InputReader(System.in); private static PrintWriter pw = new PrintW...
Yash is finally tired of computing the length of the longest Fibonacci-ish sequence. He now plays around with more complex things such as Fibonacci-ish potentials. Fibonacci-ish potential of an array ai is computed as follows: 1. Remove all elements j if there exists i < j such that ai = aj. 2. Sort the remain...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e4 + 50; int n, m, mod, a[maxn], len, F[maxn << 1]; int sz, bnum, cnt[maxn], belong[maxn], ans[maxn]; vector<int> v; struct Tree { int le, ri; int shift, S1, S2; } tree[maxn << 2]; void move(int& S1, int& S2, int k) { int newS1 = (S1 * F[len + k - 1]...
You are given a table consisting of n rows and m columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa. What is the minimum number of cells with value 1 you can get after applying some number of o...
#include <bits/stdc++.h> const int mod = 1000000007; const int inf = 1000000009; const long long INF = 1000000000000000009; const long long big = 1000000000000000; const long double eps = 0.0000000001; using namespace std; int T[21][100005], C[100005]; long long int DP[(1 << 20)][21]; int main() { ios::sync_with_stdi...
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. <image> or <image>...
#!/usr/bin/python from collections import deque def ir(): return int(raw_input()) def ia(): line = raw_input() line = line.split() return map(int, line) n, m = ia() adj = [[] for v in range(n)] for i in range(m): u, v = ia() u-=1; v-=1 adj[u].append(v) adj[v].append(u) c = [None fo...
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed <image>. You are given a tree of size n and can perform no more than one edge ...
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const long long INF = 1e18; const double PI = acos(-1); const long long tam = 1000100; const long long MOD = 1e9 + 7; const long long cmplog = 29; int hijos[tam]; vector<int> g[tam]; pair<long long, long l...
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order...
#include <bits/stdc++.h> using namespace std; const int maxn = 209; struct node { int l, r; node() {} node(int l, int r) : l(l), r(r) {} bool operator<(const node& R) const { return l < R.l; } }; set<node> S; set<node>::iterator it; int main() { S.insert(node(1, 2e9)); int n; scanf("%d", &n); for (int i...
Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making...
#include <bits/stdc++.h> using namespace std; char board[4][4]; bool Valid(int x, int y) { return (x >= 0 && x < 4 && y >= 0 && y < 4); } int main() { std::ios::sync_with_stdio(false); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { cin >> board[i][j]; } } bool valid = false; for (in...
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa". Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowe...
import math from sys import stdin, stdout fin = stdin fout = stdout n = int(fin.readline().strip()) s = fin.readline().strip() ans = [] gl = frozenset({'a', 'e', 'i', 'y', 'o', 'u'}) met = False cdel = False for i in range(n): if i > 0: if s[i] != s[i - 1]: met = False cdel = Fa...
Finally Fox Ciel arrived in front of her castle! She have to type a password to enter her castle. An input device attached to her castle is a bit unusual. The input device is a 1 × n rectangle divided into n square panels. They are numbered 1 to n from left to right. Each panel has a state either ON or OFF. Initially...
#include <bits/stdc++.h> using namespace std; int n, k, m, x, s, p[10005], c[105], y[30][30], d[10005], q[10005], f, r, g[1100005]; bool a[10005]; void work(int x, int y) { if (x > 0 && x <= n && y < d[x]) { d[x] = y; q[++r] = x; } } void bfs(int x) { int i; memset(d, 1, sizeof(d)); d[x] = 0; f ...
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages. At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at second —...
c,v0,v1,a,l = list(map(int, input().split(" "))) count=1 sum=v0 while sum<c: sum+=min(v0+count*a-l,v1-l) count+=1 print(count)
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him tj minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order. By solving s...
#include <bits/stdc++.h> using namespace std; const int INF = numeric_limits<int>::max(); const long long LLINF = numeric_limits<long long>::max(); const unsigned long long ULLINF = numeric_limits<unsigned long long>::max(); const double PI = acos(-1.0); int main() { ios_base::sync_with_stdio(0); cin.tie(0); long...
You're trying to set the record on your favorite video game. The game consists of N levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the i-th level in either Fi seconds or Si ...
#include <bits/stdc++.h> using namespace std; int n, m, a[55], b[55], x; long double f[55][5050], c[55], now, res; void doit() { for (int i = 0; i <= m; i++) f[n + 1][i] = 0; for (int i = n; i > 0; i--) { for (int j = 0; j <= m; j++) { f[i][j] = c[i] * (a[i] + (j + a[i] > m ? now : min(f[i + 1][...
Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three. So they play with each other according to following rules: ...
#include <bits/stdc++.h> using namespace std; int a[1005]; int main() { int n; while (cin >> n) { int x = 1, y = 1, z = 0, k = 0; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) { if (a[i] == 1 && x == 1 && y == 1) { y = 0; z = 1; } else if (a[i] == 2 && ...
Given a string s, process q queries, each having one of the following forms: * 1 i c — Change the i-th character in the string to c. * 2 l r y — Consider the substring of s starting at position l and ending at position r. Output the number of times y occurs as a substring in it. Input The first line of the inp...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; inline int read() { int x = 0, f = 1; char c = getchar(); for (; c < '0' || c > '9'; c = getchar()) if (c == '-') f = -1; for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - 48; return x * f; } inline void write(int x) { i...
Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't m...
#include <bits/stdc++.h> using namespace std; int const maxn = 1e5 + 10; struct bkn { int to, next; } e[maxn * 2]; int n, m; int c[maxn], head[maxn], tot, vis[maxn][2], in[maxn]; int ans[maxn], cnt, h, win; void add(int a, int b) { e[++tot].to = b; e[tot].next = head[a], head[a] = tot; } void dfs(int x, int now) ...
You are given an undirected graph, consisting of n vertices and m edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself). A cycle in a graph is called a simple, if it contains ...
#include <bits/stdc++.h> using namespace std; const int N = 300005; struct edge { int to, next; } e[N << 1]; int h[N], xb, dfn[N], low[N], n, m, i, j, x, y, w, stx[N], sty[N], ste[N]; vector<int> ans; bool b[N], cant[N]; inline void addedge(int x, int y) { e[++xb] = (edge){y, h[x]}; h[x] = xb; e[++xb] = (edge){...
You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them. You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constan...
n, m = map(int, input().split()) l = sorted(map(int, input().split())) t, b = l[::-1], -m for a in l: while b < a: if a <= b + m: n -= 1 b = t.pop() print(n)
Coach Ankit is forming a team for the Annual Inter Galactic Relay Race. He has N students that train under him and he knows their strengths. The strength of a student is represented by a positive integer. The coach has to form a team of K students. The strength of a team is defined by the strength of the weakest stude...
def power(x,m): global mod if m==0: return 1 if m&1==0: temp=power(x,m/2)%mod return (temp*temp)%mod return ((x%mod)*power(x,m-1)%mod)%mod mod=1000000007 t=input() for kk in range(0,t): n,k=(int(i) for i in raw_input().split()) l=[int(i) for i in raw_input().split()] l.sort() nCr=[0]*n nCr...
Continuing from previous version of codeXplod series i.e. CodeXplod 1.0,Chandu and daspal are still fighting over a matter of MOMO's(they are very fond of Mo Mos of sector 3..:P).This time the fight became so savior that they want to kill each other.As we all know that during a fight it is most probable outcome that b...
def gcd(x,y): if y==0: return x else: return gcd(y,x%y) t=int(input()) for zz in range(t): x,y,win=raw_input().split() x=int(x);y=int(y) while True: k=gcd(x,y) x-=k;y-=k if x==0 or y==0: break if win=='Chandu': win="Daspal" else: win="Chandu" p...
Bosky is a very curious child who turned 13 yesterday. His parents gifted him a digital watch which he really liked. He was amazed to see how each number can be represented inside one cell only by switching different edges on and off. Today, while he was in his home alone, getting bored looking at his watch, an idea p...
digits=[6,2,5,5,4,5,6,3,7,6] valids=[{} for i in xrange(11)] st0={} for i in xrange(10): valids[1][1<<i]=[digits[i],1] for l in xrange(2,11): for k in xrange(10): for prev in valids[l-1]: if prev&(1<<k)==0: act=prev|(1<<k) prevdata=valids[l-1][prev] if k==0: st0[act]=st0[...
Professor just has checked all the N students tests. Everything was fine but then he realised that none of the students had signed their papers, so he doesn't know which test belongs to which student. But it's definitely not professors's job to catch every student and asked him to find his paper! So he will hand out...
mod=10**9+7 A=[[0 for i in range(105)] for j in range(105)] B=[0]*105 for i in range(0,102): A[i][0]=1 for j in range(1,i+1): A[i][j]=A[i-1][j]+A[i-1][j-1] B[0]=1 for i in range(1,102): B[i]=B[i-1]*i def ans(n,x): y=0 for i in range(0,x+1): y+=((-1)**i)*B[x]/B[i] return y*A[n][x] def finalans(n,l,r): ret...
Given an integer n and a permutation of numbers 1, 2 ... , n-1, n write a program to print the permutation that lexicographically precedes the given input permutation. If the given permutation is the lexicographically least permutation, then print the input permutation itself. Input Format: First line is the test c...
for _ in xrange(input()): n= input() a=map(int,raw_input().split()) b=[] flag=0 for x in xrange(n-1,0,-1): b=a[:x-1] if a[x]<a[x-1]: for y in xrange(n-1,x-1,-1): if a[x-1]>a[y]: b.append(a[y]) flag=1 ...
Monk's birthday is coming this weekend! He wants to plan a Birthday party and is preparing an invite list with his friend Puchi. He asks Puchi to tell him names to add to the list. Puchi is a random guy and keeps coming up with names of people randomly to add to the invite list, even if the name is already on the list...
t = int(raw_input()) for j in range(t): a = int(raw_input()) c = [] d = [] for i in range(a): x = raw_input() c.append(x) for i in c: if i not in d: d.append(i) d.sort() for i in d: print i
Suppose you have a string S which has length N and is indexed from 0 to N−1. String R is the reverse of the string S. The string S is funny if the condition |Si−Si−1|=|Ri−Ri−1| is true for every i from 1 to N−1. (Note: Given a string str, stri denotes the ascii value of the ith character (0-indexed) of str. |x| denote...
tc=int(raw_input()) for case in range(tc): s=raw_input() r=s[::-1] l=len(s) flag=1 for i in range(l-1): t=ord(s[i])-ord(s[i+1]) if t>0: a=t else: a=-1*t t=ord(r[i])-ord(r[i+1]) if t>0: b=t else: b=-1*t if not a==b: flag=0 break if flag==1: print "Funny" else: print "Not Funny"
Roy is looking for Wobbly Numbers. An N-length wobbly number is of the form "ababababab..." and so on of length N, where a != b. A 3-length wobbly number would be of form "aba". Eg: 101, 121, 131, 252, 646 etc But 111, 222, 999 etc are not 3-length wobbly number, because here a != b condition is not satisfied. ...
combos = [] for i in range(1, 10): for j in range(0, 10): if i != j: combos += [[i, j]] for i in range(input()): n, k = map(int, raw_input().rstrip().split()) if k > 81: print -1 else: numbers = combos[k-1] ans = "" for i in range(n): ans += str(numbers[i % 2]) print ans
Jack is the most intelligent student in the class.To boost his intelligence,his class teacher gave him a problem named "Substring Count". Problem : His Class teacher gave him n strings numbered from 1 to n which consists of only lowercase letters (each having length not more than 10) and then ask Q questions related t...
t = int(raw_input()) d = {} for i in range(t): s = raw_input().strip() for j in range(len(s)): for k in range(j, len(s)): if not d.get(s[j:k+1], 0): d[s[j:k+1]] = [i] else: if i not in d[s[j:k+1]]: d[s[j:k+1]].append(i) q = int(raw_input()) while q: q-=1 l, r, sub = raw_input().strip...
In code world all genders are considered equal ( It means their is nothing like male or female). Now their are N distinct persons living in this hypothetical world. Each person can pair up with any other person or can even remain single. One day Vbhu planned to visit code world. Being a maths guy , he always try to b...
n=int(raw_input()) in_array=[] for i in xrange(n): num=int(raw_input()) in_array.append(num) mx=max(in_array) arr=[1,1] for j in xrange(2,mx+1): arr.append((arr[j-1]+(j-1)*arr[j-2])%(10**9+7)) for i in in_array: print arr[i]
We have N camels numbered 1,2,\ldots,N. Snuke has decided to make them line up in a row. The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise. Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel. Solve this probl...
import sys from heapq import heappush, heappop from operator import itemgetter sys.setrecursionlimit(10 ** 7) rl = sys.stdin.readline def solve(): N = int(rl()) res = 0 camel_left, camel_right = [], [] for _ in range(N): K, L, R = map(int, rl().split()) res += min(L, R) if R <...
Print the K-th element of the following sequence of length 32: 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51 Constraints * 1 \leq K \leq 32 * All values in input are integers. Input Input is given from Standard Input in the following format: K Output Print ...
#include<iostream> using namespace std; int main(){ int a[33]={1,1,1,2,1,2,1,5,2,2,1,5,1,2,1,14,1,5,1,5,2,2,1,15,2,2,5,4,1,4,1,51}; int k; cin >> k; cout << a[k-1] << endl; }
We have N balance beams numbered 1 to N. The length of each beam is 1 meters. Snuke walks on Beam i at a speed of 1/A_i meters per second, and Ringo walks on Beam i at a speed of 1/B_i meters per second. Snuke and Ringo will play the following game: * First, Snuke connects the N beams in any order of his choice and m...
#ifndef BZ #pragma GCC optimize "-O3" #endif #include <bits/stdc++.h> #define ALL(v) (v).begin(), (v).end() #define rep(i, l, r) for (int i = (l); i < (r); ++i) using ll = long long; using ld = long double; using ull = unsigned long long; using namespace std; /* ll pw(ll a, ll b) { ll ans = 1; while (b) { while...
Diverta City is a new city consisting of N towns numbered 1, 2, ..., N. The mayor Ringo is planning to connect every pair of two different towns with a bidirectional road. The length of each road is undecided. A Hamiltonian path is a path that starts at one of the towns and visits each of the other towns exactly once...
#include<bits/stdc++.h> using namespace std; long long a1[13]={1,2,4,7,12,20,29,38,52,101},a2[13]={1,2,4,7,12,20,30,39,67,101},n,an[15][15],no=1; int main(){ cin>>n; for (int i=1;i<=n;i++)an[i][i]=0; for (int i=1;i<=n;i++){ for (int j=i+1;j<=n;j++)an[i][j]=an[j][i]=no*a1[j-i-1]; no*=a2[n-i]; } for (int i=1;i<=...
A string is called a KEYENCE string when it can be changed to `keyence` by removing its contiguous substring (possibly empty) only once. Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string. Constraints * The length of S is between 7 and 100 (inclusive). * S consists of lowerc...
public class Main { private static void solve() { char[] s = ns(); int n = s.length; for (int i = 1; i <= n; i ++) { for (int j = i; j < n; j ++) { String a = new String(s, 0, i); String b = new String(s, j, n - j); if ((a + b).equals("keyence")) { System.out.pri...
You are given N positive integers a_1, a_2, ..., a_N. For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N). Here, X\ mod\ Y denotes the remainder of the division of X by Y. Find the maximum value of f. Constraints * All values in input are integers. * 2 \leq N \leq 3000 * 2 ...
#include <bits/stdc++.h> using namespace std; int main(){ int n,ans=0; cin>>n; for(int i=0,a;i<n;i++){ cin>>a;ans+=a-1; } cout<<ans<<endl; }
There are N people standing on the x-axis. Let the coordinate of Person i be x_i. For every i, x_i is an integer between 0 and 10^9 (inclusive). It is possible that more than one person is standing at the same coordinate. You will given M pieces of information regarding the positions of these people. The i-th piece of...
#include <bits/stdc++.h> using namespace std; const int maxn=112345; typedef pair<int,int> pii; int n,m,l,r,x,d[maxn],vis[maxn]; vector<pii> G[maxn]; bool dfs(int u,int dep) { vis[u]=1; d[u]=dep; for (int i=0;i<(int)G[u].size();++i) { int v=G[u][i].first,w=G[u][i].second; if (vis[v]&&d[u]+w!...
You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N. You can perform the following operation any number of times (possibly zero): Operation: Swap two adjacent elements in the permutation. You want to have p_i ≠ i for all 1≤i≤N. Find the minimum required number of operations to achieve this. Constraint...
#include <iostream> #include <vector> using namespace std; int main() { int N; cin >> N; int S = 0; int seq = 0; int p; for(int i = 1; i <= N; i++) { cin >> p; if(i != p) { S += seq / 2 + seq % 2; seq = 0; } if(i == p) seq++; } S += seq / 2 + seq % 2; cout << S << endl; return 0; }
There are N oases on a number line. The coordinate of the i-th oases from the left is x_i. Camel hopes to visit all these oases. Initially, the volume of the hump on his back is V. When the volume of the hump is v, water of volume at most v can be stored. Water is only supplied at oases. He can get as much water as he...
#include <bits/stdc++.h> #define rep(i,n) for ((i)=1;(i)<=(n);(i)++) #define repd(i,n) for ((i)=(n);(i)>=1;(i)--) using namespace std; int n,m; int i,j; int a[200005],d[200005],lim[25]; int tor[200005][25],tol[200005][25]; int dppre[1<<19],dpsuf[1<<19]; void calc(int x){ int i; rep(i,n){ tor[i][x]=tor[i-1][x]; ...
Imagine a game played on a line. Initially, the player is located at position 0 with N candies in his possession, and the exit is at position E. There are also N bears in the game. The i-th bear is located at x_i. The maximum moving speed of the player is 1 while the bears do not move at all. When the player gives a c...
//Love and Freedom. #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #define ll long long #define inf 20021225 #define N 100100 using namespace std; int read() { int s=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();} while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getch...
There is a factory that inputs the data of the side and diagonal lengths to the machine and cuts out the plastic plate. At this factory, we cut out only parallelogram molds, although they vary in size. You have been ordered by your boss to count the number of rectangles and rhombuses produced among the parallelograms t...
#include <iostream> using namespace std; int main(void){ int rectangle=0, lozenge=0; while (true){ int a,b,c; char e; cin>>a>>e>>b>>e>>c; if (cin.eof()) break; if (a==b) lozenge++; if (a*a+b*b==c*c) rectangle++; } cout<<rectangle<<endl; cout<<lozenge<<endl; return 0; }
In 20XX, the Aizu Chuo Road, which has a total distance of 58km and 6 sections from Atsushiokanomachi, Kitakata City to Minamiaizucho, is scheduled to be completed and opened. For half a year after opening, the toll will be halved for vehicles that pass the departure IC or arrival IC between 17:30 and 19:30 and have a...
#include<iostream> using namespace std; int main() { int list[7][7]={ {0,300,500,600,700,1350,1650}, {6,0,350,450,600,1150,1500}, {13,7,0,250,400,1000,1350}, {18,12,5,0,250,850,1300}, {23,17,10,5,0,600,1150}, {43,37,30,25,20,0,500}, {58,52,45,40,35,15,0} }; int in,out,h,m,start,end,f...
The educational program (AHK Education) of the Aiz Broadcasting Corporation broadcasts a program called "Play with Tsukuro" for children. Today is the time to make a box with drawing paper, but I would like to see if the rectangular drawing paper I prepared can make a rectangular parallelepiped. However, do not cut or ...
#include <bits/stdc++.h> using namespace std; using namespace std::chrono; typedef long long ll; typedef pair<int,int> pii; typedef pair<double,double> pdd; #define _overload4(_1,_2,_3,_4,name,...) name #define _overload3(_1,_2,_3,name,...) name #define _rep1(n) _rep2(i,n) #define _rep2(i,n) _rep3(i,0,n) #define _rep3(...
problem Chairman K is a regular customer of the JOI pizza shop in the center of JOI city. For some reason, he decided to start a life-saving life this month. So he wanted to order the pizza with the highest calories per dollar among the pizzas he could order at the JOI pizza store. Let's call such a pizza the "best pi...
import java.util.Scanner; import java.util.Arrays; public class Main{ public static void main(String[] args){ new Main().run(); } public void run(){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int a = scan.nextInt(); int b = scan.nextInt(); int cal = scan.nextInt(); int max = cal / a...
Problem KND is a student programmer at the University of Aizu. His chest is known to be very sexy. <image> For simplicity, the part of the skin that can be seen from the chest is represented by the isosceles triangle ABC in the figure. However, due to the slack in the clothes, the two sides AC and BC (where these l...
#include "bits/stdc++.h" using namespace std; //#define int long long #define DBG 1 #define dump(o) if(DBG){cerr<<#o<<" "<<(o)<<" ";} #define dumpl(o) if(DBG){cerr<<#o<<" "<<(o)<<endl;} #define dumpc(o) if(DBG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;} #define rep(i,a,b) for(int i=(a);i<(b);i++) #define rrep...
The King of a little Kingdom on a little island in the Pacific Ocean frequently has childish ideas. One day he said, “You shall make use of a message relaying game when you inform me of something.” In response to the King’s statement, six servants were selected as messengers whose names were Mr. J, Miss C, Mr. E, Mr. A...
#include<bits/stdc++.h> #define rep(i,n) for(int i=0; i<(n); i++) #define INF 1e8 using namespace std; bool is_digit(char x){ for(int i=48; i<=57; i++){ if(x == i) return true; } return false; } int main(){ int n; cin >> n; rep(k,n){ string s,t; cin >> s >> t; for...
Example Input ACM Output 0
#include <bits/stdc++.h> using namespace std; typedef pair<string,string> P; int bnf(); set<P> used; map<char,int> M; string S; int idx,valid; char ch[8]={'0','1','+','-','*','(',')','='}; int ord[8]; bool check(string a){//??????????????????°???¨???????????????????????¢???? int par=0; for(char s:a){ par += (...
Story At UZIA High School in the sky city AIZU, the club activities of competitive programming are very active. N Red Coders and n Blue Coders belong to this club. One day, during club activities, Red Coder and Blue Coder formed a pair, and from this club activity, n groups participated in a contest called KCP. At th...
#include <iostream> #include <iomanip> #include <complex> #include <vector> #include <algorithm> #include <cmath> #include <array> using namespace std; const double EPS = 1e-5; const double INF = 1e12; const double PI = acos(-1); #define EQ(n,m) (abs((n)-(m)) < EPS) #define X real() #define Y imag() typedef complex<do...
You are working as a private teacher. Since you are giving lessons to many pupils, you are very busy, especially during examination seasons. This season is no exception in that regard. You know days of the week convenient for each pupil, and also know how many lessons you have to give to him or her. You can give just ...
#include<cstdio> #include<numeric> #include<algorithm> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; typedef long long ll; const int V_MAX=109; const int E_MAX=1000; template<class T> struct graph{ int n,m,head[V_MAX],next[2*E_MAX],to[2*E_MAX]; T capa[2*E_MAX],flow[2*E_MAX]; void init(int N){ ...
A rabbit is playing a role-playing game. Just before entering the castle, he was ambushed by an enemy! It was a battle between one hero operated by a rabbit and n enemies. Each character has four stats, health hi, attack power ai, defense power di, and agility si. I = 0 is the information of the main character, 1 ≤ i ...
#include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; using ll = long long; struct Data { ll h, a, d, s; Data() {} Data(ll h, ll a, ll d, ll s) : h{h}, a{a}, d{d}, s{s} {} bool operator < (const Data& d) const { return s < d.s; } };...
E: Markup language has declined It's been centuries since we humans have been declining slowly. The earth may already belong to "Progurama". Programa-sans with an average height of 170 cm, 7 heads, high intelligence, and loves Kodingu. I have returned to my hometown of Nibunki, becoming an important international civi...
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <iostream> #include <vector> #include <map> using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) struct Node; struct Fun; int h, w, cr, cc; char scr[512][512]; Node *lnk[512][512]; Fun *evt[512][512]; map<string, vector<pair<stri...
E --Disappear Drive Story The person in D likes basketball, but he likes shooting, so other techniques are crazy. I'm not particularly good at dribbling, and when I enter the opponent's defensive range, I always get the ball stolen. So I decided to come up with a deadly dribble that would surely pull out any opponent...
#include <bits/stdc++.h> using namespace std; #define dump(...) (cerr<<#__VA_ARGS__<<" = "<<(DUMP(),__VA_ARGS__).str()<<endl) struct DUMP : stringstream { template<class T> DUMP &operator,(const T &t) { if(this->tellp()) *this << ", "; *this << t; return *this; } }; constexpr double EPS = 1e-8; struct point...
Example Input 3 2 3 1 2 1 2 3 2 3 3 1 Output 1
#include <bits/stdc++.h> using namespace std; struct SegmentTree { vector< pair< int, int > > seg; int sz; SegmentTree(int n) { sz = 1; while(sz < n) sz <<= 1; seg.assign(2 * sz - 1, make_pair(0, 0)); } void push(int k) { if(k >= sz - 1 || seg[k] == make_pair(0, 0)) return; if(seg[...
D: The Diversity of Prime Factorization Problem Ebi-chan has the FACTORIZATION MACHINE, which can factorize natural numbers M (greater than 1) in O ($ \ log $ M) time! But unfortunately, the machine could display only digits and white spaces. In general, we consider the factorization of M as p_1 ^ {e_1} \ times p_2 ...
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <string> #include <iomanip> #include <algorithm> #include <cmath> #include <stdio.h> using namespace std; #define int long long int MOD = 1000000007; vector<int> sieve_of_eratosthenes(int n) { vector<int> primes(n); for (int...
Problem Tomorrow is finally the day of the excursion to Maizu Elementary School. Gatcho, who attends Maizu Elementary School, noticed that he had forgotten to buy tomorrow's sweets because he was so excited. Gaccho wants to stick to sweets so that he can enjoy the excursion to the fullest. Gaccho gets a $ X $ yen al...
#include <bits/stdc++.h> using namespace std; #define F first #define S second typedef pair<int,int> P; typedef pair<int,P> PP; const int N=14; int dp1[N][1001],c[N][N],dp2[1<<N][N],dp3[2][1<<(N/2+1)][1001],dp[1<<N][1001],ans; vector<PP> a[N+1]; int main() { int A,B,n; cin >> n >> A >> B; for(int k=0; k<n; k++) {...
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7. Write a program which reads a list of N integers and prints the number of prime numbers in the list. Constraints 1 ≤ N ≤ 10000 2 ≤ an element of the ...
import math n = int(input()) count = 0 for i in range(n): t = int(input()) a = int(t ** (1 / 2)) end = 0 for j in range(2, a + 1): if t % j == 0: end = 1 break if end == 0: count += 1 print(count)