input
stringlengths
29
13k
output
stringlengths
9
73.4k
Thomson is very weak in set theory. Recently, he came across the following problem: Given a set X with N distinct elements, in how many ways can you select two sets A and B such that both A and B are subsets of X and A is also a subset of B. Help Thomson solve the above problem. As the answer can be very large, print i...
noOfTestCases = int(raw_input()) div = pow(10,9) + 7 for caseNo in range(1, noOfTestCases + 1): elmentCount = int(raw_input()) print pow(3,elmentCount, div)
Today is Kriti's birthday but I forgot to bring a gift for her. She is very angry with me. I have an idea for a gift. She likes coding very much. Why not give her a problem to solve as her gift? I know a problem but I am not sure whether its solvable or not. The problem initially has N strings numbered 1 to N. The pr...
def hash_value(s): a = [ord(i)-97 for i in s] p = 0 b = 0 #hv = 10**9 + 7 for i in xrange(len(a)-1,-1,-1): p+=(a[i]*(26**b)) #p%=hv b+=1 return p t = input() all_str = {} for i in xrange(t): xy = hash_value(raw_input()) if xy in all_str: all_str[xy]+=[i] else: all_str[xy]=[i] n = input() for _ in xra...
Monk has a very good friend, Puchi. As weird as his name, are the games he plays. One fine day, they decided to play a game to test how diverse their choices are. Both of them choose exactly one integer each. Monk chooses an integer M and Puchi chooses an integer P. The diversity of their choices is defined as the nu...
import sys t=int(raw_input('')) for i in range(1,t+1,1): count=0 p,m=raw_input('').split() p=int(p) m=int(m) s1="{0:b}".format(p) s2="{0:b}".format(m) if len(s1)<len(s2): for j in range(1,len(s2)-len(s1)+1,1): s1='0'+s1 else: for j in range(1,len(s1)-len(s2)+1,1): s2='0'+s2 for j in range(0,len(s...
Today professor Ka has given a string task to Oz and RK. He has given a string STR consisting only of characters '(' and ')' and asked them to convert the string STR into a closed one by adding parenthesis to start and/or end of string STR. This means that they could add characters either only to the start of string ...
class Stack: def __init__(self): self.data = list() def push(self, value): self.data.append(value) def empty(self): if len(self.data): return False else: return True def pop(self): if not self.empty(): self.data.pop() de...
Roy is going to organize Finals of Coding Contest in his college's computer labs. According to the rules of contest, problem statements will be available on each computer as pdf file. Now there are N number of computers and only one of them has the pdf file. Roy has collected M number of pendrives from his friends. Co...
tc = int(raw_input()) c = [] for i in range(0, tc): count = 0 dc = 1 dp = 0 str = raw_input() N, M = map(int, str.split()) dnc = N - 1 dnp = M while dnc and dnp: count = count + 1 x = dp + min(dc, dnp) y = dc + min(dp, dnc) dnp = dnp - min(dnp, dc) dnc = dnc - min(dnc, dp) dp = x dc = y if dnc: ...
You are given a list of names. Your task is to find all the distinct names in the list and after that find the frequency count of all these distinct names in the origninal list. We are interested in the maximum value of the frequency. You have to print this maximum frequency. If, the maximum value of the frequency occ...
t=input() d=dict() for i in range(t): s=raw_input() if s not in d: d[s]=1 else: d[s]+=1 #print sorted(d,key=d.get,reverse=True) q=sorted(d,key=d.get,reverse=True) li=dict() sum=d[q[0]] li[q[0]]=d[q[0]] for i in range(1,len(q)): if d[q[i]]==sum: li[q[i]]=d[q[i]] res=0 for i in li: res+=li...
Utkarsh is going to Cherrapunji to visit his brother Saharsh. Cherrapunji faces one of largest rainfall in the country. So, Saharsh and Utkarsh decided to measure this rainfall by T Rain Gauges. They were going to measure it by taking the product of the readings of all the gauges. But, they found out that the gauges we...
T = int(raw_input()) ans = 1 for i in xrange(T): n, r = map(int, raw_input().split()) x, y = 0, 0 for j in xrange(1,n+1): z = (j*1.0)/(r*1.0) x = x + z**3 y = y + z**2 x = x/y ans = ans * x print "%.4f" % ans
You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above. The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner? Constraints * -40 \leq X \leq 40 * X is an integer. Input Input is given from Standard Input in the follo...
#include<stdio.h> int main() { int n; scanf("%d",&n); if(n<30) printf("No\n"); else printf("Yes\n"); }
There is a circular pond with a perimeter of K meters, and N houses around them. The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond. When traveling between these houses, you can only go around the pond. Find the minimum distance that needs to ...
k,n=map(int,input().split()) l=list(map(int, input().split())) m=k-(l[n-1]-l[0]) for i in range(1,n): m=max(m,l[i]-l[i-1]) print(k-m)
N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals. The preliminary stage consists of several rounds, which will take place as follows: * All the N contestants will participate in the first round. * W...
n=int(input()) DC=[list(map(int,input().split())) for _ in range(n)] D,S=0,0 for d,c in DC: D +=c S +=d*c print(D-1+(S-1)//9)
Find the number of sequences of length K consisting of positive integers such that the product of any two adjacent elements is at most N, modulo 10^9+7. Constraints * 1\leq N\leq 10^9 * ~~1~~ 2\leq K\leq 100 (fixed at 21:33 JST) * N and K are integers. Input Input is given from Standard Input in the following forma...
import sys def solve(): N, K = map(int, input().split()) MOD = 10**9 + 7 U = []; V = [] for x in range(1, int(N**.5)+1): U.append(x) if x < N//x: V.append(N//x) V.reverse(); U.extend(V) L = len(U) prv = 0 R = [] for x in U: R.append(x-prv) ...
There is a square grid with N rows and M columns. Each square contains an integer: 0 or 1. The square at the i-th row from the top and the j-th column from the left contains a_{ij}. Among the 2^{N+M} possible pairs of a subset A of the rows and a subset B of the columns, find the number of the pairs that satisfy the f...
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; typedef long long ll; typedef vector<int> vi; #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define rep(i,n) rep2(i,0,n) #define rep2(i,m,n) for(int i=m;i<(n);i++) #define ALL(c) (c).begin(...
Let N be an even number. There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i. Snuke would like to decorate the tree with ribbons, as follows. First, he will divide the N vertices into N / 2 pairs. Here, each vertex must ...
#include <bits/stdc++.h> using namespace std; namespace TYC { typedef long long ll; const int N = 5005, mod = 1e9 + 7; int n, F[N][N], V[N], Siz[N]; vector<int> E[N]; inline int read() { int x = 0, f = 0, ch = getchar(); while (!isdigit(ch)) f |= (ch == '-'), ch = getchar(); while (isdigit(ch)) x =...
E869120 has A 1-yen coins and infinitely many 500-yen coins. Determine if he can pay exactly N yen using only these coins. Constraints * N is an integer between 1 and 10000 (inclusive). * A is an integer between 0 and 1000 (inclusive). Input Input is given from Standard Input in the following format: N A Output...
a = int(input()) b = int(input()) print("Yes" if (a % 500 <= b) else "No")
We have a grid with N rows and M columns of squares. Initially, all the squares are white. There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attach...
N,M,K = map(int, input().split()) for i in range(N+1): for j in range(M+1): if j*(N-i)+i*(M-j) == K: print('Yes') exit() print('No')
Joisino has a bar of length N, which has M marks on it. The distance from the left end of the bar to the i-th mark is X_i. She will place several squares on this bar. Here, the following conditions must be met: * Only squares with integral length sides can be placed. * Each square must be placed so that its bottom si...
#include<bits/stdc++.h> using namespace std; #define LL long long const int maxn=1e5+10; const int mo=1e9+7; int n,m,x[maxn]; struct matrix{ int v[3][3]; void init(int a,int b,int c,int d,int e,int f,int g,int h,int i) { v[0][0]=a; v[0][1]=b; v[0][2]=c; v[1][0]=d; v[1][1]=e; v[1][2]=f; v[2][0]=g; v[2][1]=h...
Rng is baking cookies. Initially, he can bake one cookie per second. He can also eat the cookies baked by himself. When there are x cookies not yet eaten, he can choose to eat all those cookies. After he finishes eating those cookies, the number of cookies he can bake per second becomes x. Note that a cookie always n...
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> using namespace std; typedef long long ll; ll a, n; ll ans; const ll INF = (ll)1e13; ll mult(ll x, ll y) { if ((double)x * y > 2 * INF) return INF; return min(INF, x * y); } int main() { // freopen("input.txt", "r", stdin); // freopen("...
A country has a budget of more than 81 trillion yen. We want to process such data, but conventional integer type which uses signed 32 bit can represent up to 2,147,483,647. Your task is to write a program which reads two integers (more than or equal to zero), and prints a sum of these integers. If given integers or t...
import java.util.Scanner; import java.math.BigInteger; public class Main{ public static void main(String[] args){ Scanner sc= new Scanner(System.in); int n=sc.nextInt(); for(int i=0; i<n; i++){ BigInteger a,b,c; a = sc.nextBigInteger(); b = sc.nextBigInteger(); c = a.add(b); if(c.toStr...
"Fukusekiken" is a popular ramen shop where you can line up. But recently, I've heard some customers say, "I can't afford to have vacant seats when I enter the store, even though I have a long waiting time." I'd like to find out why such dissatisfaction occurs, but I'm too busy to check the actual procession while the ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Main { /** 座席数 */ private final static int SEATS = 17; /** 客グループ数 */ private final static int GROUP = 100; /** 客グループの到着する間隔(分) */ priva...
There was a powerful school where powerful people gathered. At the athletic meet of the powerful school, powerful people march in a formation. While the powerhouses always want to show off their power, most of them don't want to walk on their own. So I thought that some of them would be at the bottom, and a lot of peo...
#include<iostream> #include<algorithm> #include<vector> #include<queue> #include<string> using namespace std; typedef long long ll; typedef pair<ll,ll> P; typedef pair<ll,P> P2; ll n; vector<P> vec; ll dp[1005][1005]={0},dp2[1005]={0}; bool sec_ok[1005][1005]={0}; const ll inf=174417441744; ll sec_dp(ll l,ll r){ if(l=...
problem You decide to invite your friends of the school and your friends of a friend to the Christmas party. The number of students in your school is n, and each student is assigned a number from 1 to n. Your number is 1. You have a list of who and who are your friends. Based on this list, create a program that asks f...
while True: n=int(input()) m=int(input()) if n==0: break a=[None for _ in range(m)] b=[None for _ in range(m)] friend = set() friend1=set() friend2=set() for i in range(m): a[i],b[i] = list(map(int, input().split())) if a[i] ==1: friend.add(b[i]) ...
I came to the summer festival with the elementary school students in my neighborhood. To put it bluntly, it plays the role of a guardian, but the smell of yakisoba and takoyaki in the store, and the sound of fireworks that can be heard from time to time, are still exciting even at this age. But today I have to keep an ...
import java.util.Scanner; //High and Low Cube public class Main{ char[][][] s = { {{}}, { "#######".toCharArray(), "#.....#".toCharArray(), "#...|.#".toCharArray(), "#.....#".toCharArray(), "#...|.#".toCharArray(), "#..-..#".toCharArray(), "#######".toCharArray() }, { "###...
The surveyor starship Hakodate-maru is famous for her two fuel containers with unbounded capacities. They hold the same type of atomic fuel balls. There, however, is an inconvenience. The shapes of the fuel containers #1 and #2 are always cubic and regular tetrahedral respectively. Both of the fuel containers should b...
#include<iostream> #define r(i,n) for(int i=0;i<n;i++) using namespace std; int a[160000],n; int main(){ r(j,1e9){ int t=j*j*j; if(t>=160000)break; a[t]++; r(i,1e9){ int p=i*(i+1)*(i+2)/6; if(p<160000)a[p]++; else break; if(p+t<160000)a[p+t]++; } } r(i,160000){ if(a...
Example Input 3 2 4 0 2 2 -2 -2 -2 2 Output 15
#include <bits/stdc++.h> using namespace std; #define fo(i,a,b) for (int i = (a); i < (b); i++) #define FO(i,a,b) for (int i = (a); i < (b); i++) #define fo2(i,a,b) for (i = (a); i < (b); i++) #define pb push_back #define eb emplace_back typedef long long ll; typedef long double ld; typedef pair<int,int> pii; ll dx[] ...
Problem N circles are given on the two-dimensional plane, each of which has no intersection. In addition, each circle is assigned a number from 1 to N. You can place any number of half-lines such that the endpoints are on the circumference of the first circle. Find out how many half lines must be installed in order f...
#include<bits/stdc++.h> #define rep(i,n) for(int i=0;i<(int)n;i++) #define all(c) (c).begin(),(c).end() #define mp make_pair #define pb push_back #define each(i,c) for(__typeof((c).begin()) i=(c).begin();i!=(c).end();i++) #define dbg(x) cerr<<__LINE__<<": "<<#x<<" = "<<(x)<<endl using namespace std; typedef long lon...
Dr. Keith Miller is a researcher who studies the history of Island of Constitutional People’s Country (ICPC). Many studies by him and his colleagues have revealed various facts about ICPC. Although it is a single large island today, it was divided in several smaller islands in some ancient period, and each island was r...
#include <cmath> #include <cstdio> #include <iostream> #include <vector> #include <algorithm> using namespace std; template<class T> struct Vec2 { Vec2( T _x, T _y ) : x(_x), y(_y) {} T length() const { return sqrt(dot(*this)); } Vec2 operator+( const Vec2& rhs ) const { return Vec2(x+rhs.x, y+rhs.y); }...
Description Since the cubic equation: ax ^ 3 + bx ^ 2 + cx + d = 0 is given, please check the number of positive real roots and the number of negative real roots, respectively. The number of roots shall be counted including the multiple roots. Input The input consists of multiple test cases, and the number is rec...
n=int(input()) def f(a,b,c,d): return lambda x:a*x**3+b*x**2+c*x+d for i in range(n): a,b,c,d=map(int,input().split()) fx=f(a,b,c,d) D=b**2-3*a*c if D<=0 : if d==0: pl=mi=0 elif (a>0 and d<0) or (a<0 and d>0): pl,mi=1,0 elif (a<0 and d<0) or (a>0 and d...
There is a tree that has n nodes and n-1 edges. There are military bases on t out of the n nodes. We want to disconnect the bases as much as possible by destroying k edges. The tree will be split into k+1 regions when we destroy k edges. Given the purpose to disconnect the bases, we only consider to split in a way that...
#include<bits/stdc++.h> #define N 10005 #define rank raljfds using namespace std; typedef pair<int,int> P; typedef pair<int,P> P2; class UF{ public: int V; vector<int> par, rank, mil; UF(){} UF(int V):V(V),par(V),rank(V,0),mil(V,-1){for(int i=0;i<V;i++) par[i]=i;} int find(int x){ assert(x<V); if(...
I - The J-th Number Problem Statement You are given N empty arrays, t_1, ..., t_n. At first, you execute M queries as follows. * add a value v to array t_i (a \leq i \leq b) Next, you process Q following output queries. * output the j-th number of the sequence sorted all values in t_i (x \leq i \leq y) Input ...
#include <bits/stdc++.h> using namespace std; using ll = long long; const int PMAX = 10000000; const int QMAX = 100001; const function<int(int, int)> minQ = [](int l, int r) { return min(l, r); }; const function<int(int, int)> maxQ = [](int l, int r) { return max(l, r); }; const function<ll(ll, ll)> minQll = [](ll l, ...
Example Input 2 1 WE Output 1 2
#include <iostream> #include <vector> #include <cmath> #include <string> #include <climits> #include <iomanip> #include <algorithm> #include <queue> #include <map> #include <tuple> #include <iostream> #include <deque> #include <array> #include <set> #include <functional> #include <memory> #include <stack> int main() ...
You are an employee of Automatic Cleaning Machine (ACM) and a member of the development team of Intelligent Circular Perfect Cleaner (ICPC). ICPC is a robot that cleans up the dust of the place which it passed through. Your task is an inspection of ICPC. This inspection is performed by checking whether the center of I...
import java.io.*; import java.util.*; /** * AIZU ONLINE JUDGE * 2852 Tiny Room * 2018/02/19 */ public class Main { int N; int W; int H; int R; int[] x; int[] y; double func(double th) { double xmax = -Double.MAX_VALUE; double ymax = -Double.MAX_VALUE; d...
Problem Gaccho loses motivation as the final exam approaches and often misses school. There are N days left until the final exam. Gaccho's motivation on day i is Xi, and the motivation needed to go to school on day i is Yi. Gaccho goes to school only on days when Xi ≥ Yi. Haji, who was worried about Gaccho, decided to...
#include<bits/stdc++.h> using namespace std; #define int long long #define rep(i,n) for(int i=0;i<(n);i++) #define all(v) (v).begin(),(v).end() #define pb push_back #define fi first #define se second typedef vector<int>vint; typedef pair<int,int>pint; typedef vector<pint>vpint; template<typename A,typename B>inline...
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$. Constraints * $1 \leq n \leq 100$ Input In the first line, an integer $n$ denoting the number of vertic...
#include <iostream> #include <queue> using namespace std; int c[101][102],ch[101]; queue<int> q; int main(){ int a,b,e,d,n,k; cin>>a; for(int i=1;i<=a;i++)ch[i]=-1; for(int i=0;i<a;i++){ cin>>b>>e; c[b][0]=e; for(int j=1;j<=e;j++){ cin>>d; c[b][j]=d; } } q.push(1); ch[1]=0; ...
Write a program which reads the two dices constructed in the same way as Dice I, and determines whether these two dices are identical. You can roll a dice in the same way as Dice I, and if all integers observed from the six directions are the same as that of another dice, these dices can be considered as identical. Co...
import java.util.Scanner; /** * @author kawakami * */ class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner as = new Scanner(System.in); int dice1[]; int dice2[]; String str = ""; Boolean breakp = null; dice1 = new int[6];...
Ramkumar loves to solve riddles one day SpojSathyagave him a riddle to solve. Sathya will give him pair of integers a and b. Ramkumar has to find the largest number in the range [a,b] inclusive which can be represented as product of atleast two prime numbers. But ramkumar is busy in watching "Arrow" he is asking your ...
def isprime(n): if n == 2 or n == 3: return 0 if n < 2 or n%2 == 0: return 1 if n < 9: return 0 if n%3 == 0: return 1 r = int(n**0.5) f = 5 while f <= r: if n%f == 0: return 1 if n%(f+2) == 0: return 1 f +=6 return 0 def main(): t=raw_input() for j in xrange(int(t)): b,c...
Chef's younger brother is in town. He's a big football fan and has a very important match to watch tonight. But the Chef wants to watch the season finale of MasterChef which will be aired at the same time. Now they don't want to fight over it like they used to when they were little kids. They want to decide it in a fai...
for t in xrange(int(raw_input())): x=0 for c in xrange(int(raw_input())): n,m=map(int,raw_input().split()) g=(m+n-2)%3 x=x^g if x: print "MasterChef" else: print "Football"
For any positive integer, we define a digit rotation as either moving the first digit to the end of the number (left digit rotation), or the last digit to the front of the number (right digit rotation). For example, the number 12345 could be left digit rotated to 23451, or right digit rotated to 51234. If there are any...
# code chef - easy - digit rotation def left(s): return str(int(s[-1]+s[:-1])) def right(s): return str(int(s[1:]+s[0])) nCases = int(raw_input()) for iter in range(nCases): number = raw_input() if len(number)==1: print number continue best = max(int(left(right(number))), int(...
The planet of XANDOR was famous in the intergalactic empire for being home to the Carden - a race of super-intelligent computer scientists that were held in high regard for their achievements in the Intergalactic Mind Game Olympiads. The Carden decided to build a huge computer to answer questions related to Life, the U...
#!/usr/bin/python s=raw_input() dp = [ [ 0 for j in xrange(20)] for i in xrange(20) ] op = [ '_' for i in xrange(20) ] n = len(s) m = 0 f = [0, 1] for i in xrange(2,20): f.append(0) for j in xrange(1,i): f[i] += f[j] * f[i-j] for i in xrange(n): if i%2 == 0 and s[i] == 'T': dp[i/2][1] = 1 ...
Given a string of letters in the input, return a string in the output with each words written in reverse order. Spaces and punctuations must not change their position. Numbers may be present in a string. The end of the string will have a "." without the quotes. Input Input string Output Output String Example Inp...
ans=[] while True: try: s=raw_input() l=[] l=s.split() for i in l: i=i[::-1] ans.append(i) except EOFError: break for i in ans: if i[0]==".": i=i.replace(".","") print i+".", else: print i,
Alok-nath is man of equality. He needs your help to divide his “sanskars” evenly amongst all his followers. By doing this, Alok-nath can create equality amongst his followers and he'll be called a true “sanskari”. Alok-nath has N sanskars, and K followers. Each sanskar is given a numerical value which shows its intensi...
def possible(A, e, n): def rec(i, r): if r == 0: return True if i == n: return False if A[i] > 0 and r >= A[i]: p = rec(i + 1, r - A[i]) if p: A[i] = 0 return True p = rec(i + 1, r) if p: ...
Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, ...
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author dipankar12 */ import java.io.*; import java.util.*; public class r46b { public static void main(String args[]) ...
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras. Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now ...
import sys s = input() n = len(s) if n == 1: print(1) sys.exit(0) for i in range(n-1): if s[i] == s[i+1] and (s[n-1] != s[0]): x = s[:i+1] y = s[i+1:n] s = x[::-1] + y[::-1] ans = 1 mx = 1 for i in range(1, n): if s[i] != s[i-1]: mx += 1 else: ans = max(mx, ans) mx = 1 print(max(mx, ans))
On the surface of a newly discovered planet, which we model by a plane, explorers found remains of two different civilizations in various locations. They would like to learn more about those civilizations and to explore the area they need to build roads between some of locations. But as always, there are some restricti...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const double PI = acos(-1.0); struct point { int x, y, c, id; point() {} point(int x, int y) : x(x), y(y) {} point operator-(const point &b) const { return {x - b.x, y - b.y}; } int operator^(const point &b) const { return x * b.y - y *...
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog. Let us define k-multihedgehog as fol...
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { FastReader reader = new FastReader(); PrintWriter writer = new PrintWriter(System.out); int n = reader.nextInt(); int k = reader.nextInt(); MyList[] graph = new MyList[n]; for (int i=0; i<n; i++) graph...
Vasya had an array of n integers, each element of the array was from 1 to n. He chose m pairs of different positions and wrote them down to a sheet of paper. Then Vasya compared the elements at these positions, and wrote down the results of the comparisons to another sheet of paper. For each pair he wrote either "great...
import java.io.*; import java.math.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.util.Comparator.*; public class Main { FastScanner in; PrintWriter out; private void solve() throws IOException { /...
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. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
# your code goes here n=int(input()) n=str(n) k=0 for i in range(len(n)): if int(n[i]) == 4 or int(n[i]) == 7: k=k+1 if k==4 or k==7: print('YES') else: print('NO')
Vivek initially has an empty array a and some integer constant m. He performs the following algorithm: 1. Select a random integer x uniformly in range from 1 to m and append it to the end of a. 2. Compute the greatest common divisor of integers in a. 3. In case it equals to 1, break 4. Otherwise, return to...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7, N = 1e5 + 1; int dp[N], n, g[N], f[N], e, tim; int vis[N], sav[N], ep, ans, m; inline void sai() { for (int i = 2; i < N; ++i) { if (!g[i]) { f[++e] = i; g[i] = i; } for (int j = 1; j <= e; ++j) { if (i * f[j] >= N) b...
Polycarp has to solve exactly n problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in k days. It means that Polycarp has exactly k days for training! Polycarp doesn't want to procrastinate, so he wants to sol...
#include <bits/stdc++.h> using namespace std; const double pi = 2 * acos(0.0); const int maxn = 2e5 + 10; vector<int> ans; int main() { int n, k; cin >> n >> k; int l = 1, r = 1e9; while (l <= r) { int mid = (l + r) >> 1; long long res = 1LL * (mid + mid + k - 1) * k / 2; if (res <= n) l = mid...
And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator...
#include <bits/stdc++.h> using namespace std; const int inf = 2147483647; const double pi = acos(-1.0); 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(); re...
There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the governm...
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.TreeMap; import java.util.StringTokenizer; import java.util.Map; import java.io.BufferedReader; impo...
The final match of the Berland Football Cup has been held recently. The referee has shown n yellow cards throughout the match. At the beginning of the match there were a_1 players in the first team and a_2 players in the second team. The rules of sending players off the game are a bit different in Berland football. If...
a1=int(input()) a2=int(input()) k1=int(input()) k2=int(input()) n=int(input()) m1=n - (k1-1)*a1 - (k2-1)*a2 if m1<0: m1=0 m2=0 if a1*k1 + a2*k2 <=n: m2=a1+a2 elif k1<=k2: if n//k1 <= a1: m2=n//k1 else: m2=m2+a1 n=n-a1*k1 m2=m2 + min(a2, n//k2) elif k2 < k1: if n...
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height h, and there is a moving platform on each height x from 1 to h. Each platform is either hidden inside the cliff or moved out. At first, there are n moved out platforms...
#include <bits/stdc++.h> using namespace std; ifstream fin("input.txt"); ofstream fout("output.txt"); int gcd(int a, int b) { while (a && b) a > b ? a %= b : b %= a; return a + b; } int val(char c) { if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10; } long long pows(int a, in...
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1'). In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do ...
'''q=int(input()) for i in range(q): n,k=map(int,input().split()) a=input() b=[] indices=[] for j in range(n): if(a[j]=='0'): indices.append(j) b.append(a[j]) e=0 t=0 while(k>0 and e<=len(indices)): if(indices[e]<=k): b[indices[e]],b[t]=b[t],b[indices[e]] k=k-indices[e] t=t+1 else: ar=...
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t...
from sys import stdin def findpass(s): arr = suff_array(s) n = len(s) maxidx = arr[n - 1] valid = False for i in range(n - 1): if arr[i] == maxidx: valid = True break if not valid: maxidx = arr[maxidx - 1] if maxidx == 0: return "Just a le...
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ash...
n, m = input().split(" ") n = int(n) m = int(m) priceList = [] res = [] least = 0 most = 0 fruitCount = 0 seq = input().split(" ") for i in seq: priceList.append(int(i)) item = [] count = [] for i in range(m): inp = input() if inp in item: count[item.index(inp)] += 1 else: item.app...
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task. You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left ha...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.TreeMap; import java.util.Map; import java.util.Map.Entry; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** ...
So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem! Initially, each test in that problem is just an array. The maximum size of an array...
/* * Author: pranay.agra * Time: 2020-04-26 10:36:17 */ import java.io.*; import java.util.*; public class d { public static void main(String[] args) throws IOException { Scanner std = new Scanner(System.in); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); St...
Given a connected undirected graph with n vertices and an integer k, you have to either: * either find an independent set that has exactly ⌈k/2⌉ vertices. * or find a simple cycle of length at most k. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a...
#include <bits/stdc++.h> using namespace std; int n, m, k, vis[100009], go[100009]; vector<int> v[100009], vv, v2[2]; void solve() { if (vv.size() <= k) { cout << "2\n" << vv.size() << "\n"; for (auto i : vv) cout << i << " "; exit(0); } memset(vis, 0, sizeof vis); int sz = vv.size(); for (int i =...
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects can be any letter from the first 20 lowercase letters of English alphabet (read statement for better understanding). You can make hacks in these problems independen...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; const int base = 31337; const int mod = 1e9 + 7; const int inf = 0x3f3f3f3f; const int logo = 20; const int off = 1 << logo; const int treesiz = off << 1; int t; int n; char a[maxn], b[maxn]; int graph[100], graph2[100]; bool dp[treesiz]; bool bio...
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 2 ⋅ 10^4) — the number of test cases. The description of the test cases ...
import java.util.*; import java.io.*; public class B { static class Pair { int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public String toString() { return "(" + a + ", " + b + ")"; } } public static void main(S...
You are a paparazzi working in Manhattan. Manhattan has r south-to-north streets, denoted by numbers 1, 2,…, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,…,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the interse...
#include <bits/stdc++.h> using namespace std; long long mo(long long a) { return a % (long long)(1e9 + 7); } long long po(long long x, long long y, long long p) { long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res % p; } struct cele...
The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version. Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces. In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell ...
def disti(b,ind): a=[] for i in b: h=[] for j in i: h.append(j) a.append(h) ans=0 id=0 for i in range(n): start = ind[id%3] id+=1 for j in range(start ,n,3): left='' right='' up='' down='' mid1='' mid2='' if(j-2 >= 0): left = a[i][j-2] + a[i][j-1] + a[i][j] if(j+2 <n ): ri...
In the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way: * he creates an integer c as a result of bitwise summing of a and b without transfe...
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); i...
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the ...
#include <bits/stdc++.h> using namespace std; int main() { int n, x; cin >> n; multimap<int, int> m, m1, m2; multimap<int, int>::reverse_iterator it; multimap<int, int>::iterator it1; for (int i = 1; i <= n; i++) { cin >> x; m.insert(pair<int, int>(x, i)); } it = m.rbegin(); m1.insert(pair<int...
<image> William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands. A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just...
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstring> #include <set> #include <map> #include <vector> #include <queue> #include <algorithm> #include <ctime> #include <cassert> using namespace std; void solve(int tcase) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < ...
Ilya plays a card game by the following rules. A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom co...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<pair<long long int, long long int> > res(n); for (int i = 0; i < n; i++) { cin >> res[i].second >> res[i].first; } sort(res.begin(), res.end()); long long int result; result = res[n - 1].second; long long int turn =...
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friends...
#include <bits/stdc++.h> using namespace std; const int INF = 1000000; int n, m, k; bool us[2222]; vector<vector<int> > gr; bool dead[2222]; int ans[2222]; bool dfs(int v, int aim) { if (v == aim) return true; us[v] = true; bool flag = false; for (int i = 0; i < (int)gr[v].size(); i++) { if (!us[gr[v][i]]) ...
Qwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen. Y...
#include <bits/stdc++.h> using namespace std; const double EPS = 1e-10; const double PI = atan(1.0) * 4.0; struct Point { double x, y; Point(); Point(double x, double y); }; Point::Point() {} Point::Point(double x, double y) : x(x), y(y) {} bool cmp_x(const Point& lhs, const Point& rhs) { return lhs.x != rhs.x ...
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query ...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10, SQ = 500; int n, q, l, r, ans, sz, v[SQ], a[MAXN - 5], dp[MAXN - 5][SQ]; map<int, int> cnt; int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> n >> q; for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] >=...
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen. On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, ...
#include <bits/stdc++.h> using namespace std; signed main() { string s; cin >> s; long long maxx = 0, minn = 0; long long d = 0; for (long long i = 0; i < s.length(); i++) { if (s[i] == '+') d++; else d--; maxx = max(maxx, d); minn = min(minn, d); } cout << maxx - minn << endl;...
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a...
#include <bits/stdc++.h> using namespace std; struct BOX { long long len, num; } box[100005]; bool cmp(BOX a, BOX b) { return a.len < b.len; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> box[i].len >> box[i].num; sort(box, box + n, cmp); for (int i = 0; i < n - 1; i++) { if (2 * box...
You've got a weighted tree, consisting of n vertices. Each edge has a non-negative weight. The length of the path between any two vertices of the tree is the number of edges in the path. The weight of the path is the total weight of all edges it contains. Two vertices are close if there exists a path of length at mos...
#include <bits/stdc++.h> using namespace std; mt19937 gen(time(NULL)); const long double eps = 1e-9; const int inf = 1e9; const int mod = 1e9 + 7; const long long infinity = 2 * 1e18; struct edge { int to, w; }; vector<edge> g[100005]; int lv[100005]; vector<vector<int>> mx[100005]; int md[100005]; vector<vector<int>...
A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tub...
#include <bits/stdc++.h> using namespace std; int N; long long V; int E; const int MaxN = 305; vector<int> adj[MaxN]; long long start[MaxN], stop[MaxN], needs[MaxN]; void input() { cin >> N >> V >> E; for (int i = 1; i <= N; i++) cin >> start[i]; for (int i = 1; i <= N; i++) cin >> stop[i]; for (int i = 0; i < ...
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work. The girl finds an important permutation for the resea...
import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Trung Pham */ public class E { private static int MOD = 1000000007; private static long[][] dp; publ...
You've got an n × m table (n rows and m columns), each cell of the table contains a "0" or a "1". Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly k times in the rectangle. Input The f...
#include <bits/stdc++.h> using namespace std; inline char gc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline int read() { char c = getchar(); int tot = 1; while ((c < '0' || c > '...
Fox Ciel studies number theory. She thinks a non-empty set S contains non-negative integers is perfect if and only if for any <image> (a can be equal to b), <image>. Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or). Please calculate the number of perfect sets consisting of ...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; long long two[35]; int f[35][35][2], d[35]; int n, len; int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; } int dfs(int i, int j, int limit) { if (!i) return 1; if (f[i][j][limit] != -1) return f[i][j][limit]; int res = 0; i...
You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language. Input This program has only one test (your program doesn't have to read anything). Output ...
"""==================================================================================== ==================================================================================== ___ _______ ___ _______ ___ ___ | /\ | | \ | | / | | | | |\ /| | ...
During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell ...
import random #dsu p = [] def finds(v): if p[v] != v: p[v] = finds(p[v]) return p[v] def union(v1,v2): r1 = finds(v1) r2 = finds(v2) if r1 != r2: if random.choice([0,1]) == 0: p[r1] = r2 else: p[r2] = r1 #input I = lambda:map(int,raw_input().split()) n...
Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak. There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indic...
# 459D import sys from collections import Counter class BIT(): def __init__(self, n): self.n = n self.tree = [0] * n def _F(self, i): return i & (i + 1) def _getSum(self, r): ''' sum on interval [0, r] ''' result = 0 while r >= 0: ...
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. Howe...
#include <bits/stdc++.h> using namespace std; using ULL = unsigned long long; using UL = unsigned; using LL = long long; struct Problem { static const ULL M = 1000000007; void Solve() { UL N, A, B, K; cin >> N >> A >> B >> K; A--; B--; vector<pair<UL, UL>> R(N); for (UL i = 0; i < (N); i++) ...
The Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi....
#include <bits/stdc++.h> using namespace std; FILE* _fin = stdin; FILE* _fout = stdout; int _min(int a, int b) { return a <= b ? a : b; } int _min(long long a, long long b) { return a <= b ? a : b; } int _max(int a, int b) { return a >= b ? a : b; } long long _max(long long a, long long b) { return a >= b ? a : b; } vo...
Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo. Simply speaking, the process of photographing can be describ...
#include <bits/stdc++.h> using namespace std; int X = 1000000005, H[1005], W[1005], N; int g(int h, int k, int w) { priority_queue<int> q; for (int i = 1; i <= N; i++) { if (H[i] <= h && W[i] <= h) { q.push(W[i] - H[i]); w += W[i]; } else if (W[i] <= h && k) { w += H[i]; k--; } e...
Let's define the permutation of length n as an array p = [p1, p2, ..., pn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on. Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a...
#include <bits/stdc++.h> using namespace std; struct T { int x; int y; }; long long fib[10009], k; int main() { int n; scanf("%d%I64d", &n, &k); fib[1] = 1; for (int i = 2; i <= n; i++) fib[i] = fib[i - 1] + fib[i - 2]; for (int i = 1; i <= n; i++) { if (fib[n - i + 1] < k) { printf("%d %d ", i ...
Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the ver...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int is_cat[MAXN], n, m; vector<int> g[MAXN]; int ans; void get_input(), write_output(); void dfs(int, int, int); int main() { get_input(); dfs(-1, 0, 0); write_output(); } void write_output() { cout << ans << endl; } void dfs(int dad, int ad...
When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their aver...
n = int(input()) arr = list(map(int,input().split())) d = {} mx = 0 for c in arr: nd = {} nd[c-0.5] = d.get(c-0.5,0)+1 nd[c+0.5] = d.get(c+0.5,0)+1 mx = max(mx,nd[c-0.5],nd[c+0.5]) d = nd print(mx)
Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals. A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: a...
#include <bits/stdc++.h> using namespace std; const long long INF = 9223372036854775807LL, SQ_MAX = 40000000000000000LL; void getmin(long long &a, const long long b) { if (b < a) a = b; } void getmax(long long &a, const long long b) { if (b > a) a = b; } long long Sq(const long long a) { return a * a; } struct Poin...
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: * Problemset of ...
#include <bits/stdc++.h> using namespace std; template <typename T, typename T1> ostream &operator<<(ostream &out, pair<T, T1> obj) { out << "(" << obj.first << "," << obj.second << ")"; return out; } template <typename T, typename T1> ostream &operator<<(ostream &out, map<T, T1> cont) { typename map<T, T1>::cons...
While creating high loaded systems one should pay a special attention to caching. This problem will be about one of the most popular caching algorithms called LRU (Least Recently Used). Suppose the cache may store no more than k objects. At the beginning of the workflow the cache is empty. When some object is queried ...
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &x); template <typename T> void write(T x); template <typename T> void writesp(T x); template <typename T> void writeln(T x); const int N = 1ull << 21, M = 22; double f[N]; int n, s, k; double P[M], sum[N], p[M]; inline int pop_count(int x)...
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after th...
#include <bits/stdc++.h> using namespace std; int main() { int n, t, i, k; cin >> n >> t; string s; cin >> s; for (i = 0; i < n; i++) { if (s[i] == '.') break; } if (i == n) { cout << s << endl; return 0; } i++; for (k = i; k < n; k++) { if (s[k] >= '5') break; } if (k == n) { ...
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of t...
#include <bits/stdc++.h> using namespace std; int main() { long long int n, a, b, c; cin >> n >> a >> b >> c; int i, j; j = n % 4; if (j == 1) { cout << min(min(3 * a, b + a), c); } else if (j == 2) { cout << min(min(2 * a, b), 2 * c) << endl; } else if (j == 3) { cout << min(min(a, 3 * c), b ...
After his birthday party, Timofey went to his favorite tree alley in a park. He wants to feed there his favorite birds — crows. It's widely known that each tree is occupied by a single crow family. The trees in the alley form a row and are numbered from 1 to n. Some families are friends to each other. For some reasons...
#include <bits/stdc++.h> using namespace std; struct edge { int to, next; } e[100005 * 10]; int head[100005], t[100005], dfn[100005], vis[100005]; int tot, n, T; void add(int x, int y) { e[++tot] = (edge){y, head[x]}; head[x] = tot; } void upd(int x) { for (; x <= n; x += x & (-x)) t[x]++; } int ask(int x) { ...
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one...
import java.util.*; import org.xml.sax.HandlerBase; import java.io.*; import java.lang.*; public class B787 { private static long mod = 1000000007; public static void main(String[] args) { InputReader in=new InputReader(System.in); PrintWriter pw=new PrintWriter(System.out); int n=in.nextInt(); int m=...
Digital collectible card games have become very popular recently. So Vova decided to try one of these. Vova has n cards in his collection. Each of these cards is characterised by its power pi, magic number ci and level li. Vova wants to build a deck with total power not less than k, but magic numbers may not allow him...
#include <bits/stdc++.h> using namespace std; const int UNDEF = -1; const int INF = 1 << 30; template <typename T> inline bool chkmax(T &aa, T bb) { return aa < bb ? aa = bb, true : false; } template <typename T> inline bool chkmin(T &aa, T bb) { return aa > bb ? aa = bb, true : false; } static char stdinBuffer[102...
<image> Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery. Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable t...
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import java.util.Queue; import java.util.stream.IntStream; import static java.lang.Math.max; import static java.lang.Math.min; public class B_SegmentTree implements Runnable{ ...
After long-term research and lots of experiments leading Megapolian automobile manufacturer «AutoVoz» released a brand new car model named «Lada Malina». One of the most impressive features of «Lada Malina» is its highly efficient environment-friendly engines. Consider car as a point in Oxy plane. Car is equipped with...
#include <bits/stdc++.h> template <typename T> inline void repl(T& a, T b) { if (a > b) a = b; } template <typename T> inline void repr(T& a, T b) { if (a < b) a = b; } char buf[10000000], *be = buf, obuf[10000000], *oe = obuf; inline void read(int& x) { while ((*be < 48 || *be > 57) && *be != '-') be++; x = 0;...
Recently a tournament in k kinds of sports has begun in Berland. Vasya wants to make money on the bets. The scheme of the tournament is very mysterious and not fully disclosed. Competitions are held back to back, each of them involves two sportsmen who have not left the tournament yet. Each match can be held in any of...
#include <bits/stdc++.h> using namespace std; const int N = 10; int n, k; struct Node { int mx[N], mn[N], siz; bool operator<(const Node &a) const { for (int i = 0; i < k; ++i) if (mx[i] > a.mn[i]) return 0; return 1; } } t; set<Node> s; set<Node>::iterator it; int main() { scanf("%d%d", &n, &k); ...
<image> Senor Vorpal Kickass'o invented an innovative method to encrypt integer sequences of length n. To encrypt a sequence, one has to choose a secret sequence <image>, that acts as a key. Vorpal is very selective, so the key should be such a sequence bi, that its cyclic shifts are linearly independent, that is, th...
#include <bits/stdc++.h> using namespace std; const int oo = 0x3f3f3f3f; const long long ooo = 9223372036854775807ll; const int _cnt = 1000 * 1000 + 7; const int _p = 1000 * 1000 * 1000 + 7; const int N = 1500105; const double PI = acos(-1.0); const double eps = 1e-9; int o(int x) { return x % _p; } int gcd(int a, int ...
An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens: ...
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Codeforces472_C { // C. Three-level Laser static int[] A = new int[400005]; public static int er(int a[], int l, int r, int v) { // a[i]<=v int mid; while (l <= r) { mid = (l + r) / 2; if (a[mid] > v) { r = mid -...
<image> You have one chip and one chance to play roulette. Are you feeling lucky? Output Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).
print 'even'
Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2 × 1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-6 1-1 1-2 1-3 1-4 1-5 1-6 2-2 2-3 2-4 2-5 2-6 3-3 3-4 3-5 3-6 4-4 4-5 4-...
#include <bits/stdc++.h> using namespace std; int final; int vz[7][7], vis[40][40], c[40][40], cnt[10], u[20], fu[20]; char s[40][40]; vector<int> v[30]; void dfs(int cur, int cm) { if (cur == 15) { memset(vz, 0, sizeof vz); for (int i = (1); i <= (28); i++) { if (vz[u[v[i][0]]][u[v[i][1]]]) return; ...