input
stringlengths
29
13k
output
stringlengths
9
73.4k
Tom is very weak at maths, his teacher gave him a simple problem of dividing two numbers but as usual Tom is having difficulty solving the problem. Can you help tom solve the problem ? Teacher has given him 3 numbers a, b and c. The task is to divide a by b and write the answer upto c decimal places. Input: The firs...
import string import math from decimal import * t1 = int(raw_input()) while t1>0: a,b,c = (raw_input().split(' ')) a = int(a) b,c = int(b),int(c) x=a/b ta = a getcontext().rounding = ROUND_DOWN t = 0; if x==0: t = c +1 else: t = c + int(math.log10(x))+1 getcontext().prec = t a = Decimal(a)/Decimal(b) ...
Most of you know that how much the sleeping barber loves sleeping, and the way he works. For those who don't know, it isn't important for now. Because the problem , that the sleeping barber is facing is a new one for him and because he forgot to take his coding pills, he is not able to tackle with it. Recently, the ba...
d=int(input()) while d : g,m=map(int,raw_input().split()) people=map(int,raw_input().split()) people.sort() cnt=0 capacity=0 while capacity<=m and cnt<g+1: cnt+=1 capacity+=people[cnt-1] print cnt-1 d-=1
Given are integer sequences A and B of length 3N. Each of these two sequences contains three copies of each of 1, 2, \dots, N. In other words, A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N). Tak can perform the following operation to the sequence A arbitrarily many times: * Pick a value from 1, 2...
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<bitset> #include<stack> #include<unordered_map> #include<utility> #include<cassert> #in...
We have a string S consisting of lowercase English letters. If the length of S is at most K, print S without change. If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result. Constraints * K is an integer between 1 and 100 (inclusive). * S is a string ...
#include <bits/stdc++.h> using namespace std; int main(){ string s; long k; cin >> k; cin >> s; if (s.size() > k){ s = s.substr(0,k)+"..."; } cout << s << endl; }
For a finite set of integers X, let f(X)=\max X - \min X. Given are N integers A_1,...,A_N. We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) ove...
# include <bits/stdc++.h> using namespace std; # define pb push_back const int N = 100005; # define MOD 1000000007 typedef long long i64; int a[N]; i64 A[N]; i64 pow_mod(i64 a, i64 n, i64 mod){ i64 ret=1, tmp=a%mod; while (n) { if (n&1) ret=ret*tmp%MOD; tmp=tmp*tmp%MOD; n>>=1; } ...
We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls. Takahashi will distribute these 3N balls to N people so that each pe...
//#define _GLIBCXX_DEBUG #include <iostream> #include <bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define P pair<ll,ll> #define FOR(i,n,m) for(ll i=n; i<(ll)m;i++) #define FORr(i,m,n) for(ll i=n; i>=(ll)m; i--) #define FORm(i,m) for(auto i=m.begin();i!=m.end();i++) #define sortAl...
In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)! There are five means of transport in this empire: * Train: travels from City 1 to 2 in one minute. A train can occupy at most A people. * Bus: travels from City 2 to 3 in one minute. A bus can occupy a...
#include <bits/stdc++.h> int main(){ using namespace std; long N; cin >> N; vector<long> v(5); for(auto& i : v)cin >> i; cout << 5 + (N - 1) / *min_element(v.begin(), v.end()) << endl; return 0; }
There is a train going from Station A to Station B that costs X yen (the currency of Japan). Also, there is a bus going from Station B to Station C that costs Y yen. Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then trav...
L = list(map(int,input().split())) print(L[0]+L[1]//2)
Snuke has a rooted tree with N vertices, numbered 1 through N. Vertex 1 is the root of the tree, and the parent of Vertex i ( 2\leq i \leq N ) is Vertex P_i ( P_i < i ). There is a number, 0 or 1, written on each vertex. The number written on Vertex i is V_i. Snuke would like to arrange the vertices of this tree in a ...
#include<bits/stdc++.h> using namespace std; #define ll long long #define fr(i,j,k) for(int i=j;i<k;i++) #define f(n) fr(i,0,n) #define f1(n) fr(i,1,n+1) #define pb push_back #define F first #define S second #define all(x) x.begin(), x.end() #define sz(x) (int)x.size() const int maxn = 200007; int P[maxn],V[maxn],d[max...
In some place in the Arctic Ocean, there are H rows and W columns of ice pieces floating on the sea. We regard this area as a grid, and denote the square at the i-th row and j-th column as Square (i,j). The ice piece floating in each square is either thin ice or an iceberg, and a penguin lives in one of the squares tha...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; template <class T> using V = vector<T>; template <class T> using VV = V<V<T>>; #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 re...
There are N turkeys. We number them from 1 through N. M men will visit here one by one. The i-th man to visit will take the following action: * If both turkeys x_i and y_i are alive: selects one of them with equal probability, then eats it. * If either turkey x_i or y_i is alive (but not both): eats the alive one. * ...
#include<bits/stdc++.h> using namespace std; const int maxN=410; const int maxM=101000; int n,m; int P1[maxM],P2[maxM],Mark[maxN]; bitset<maxN> B[maxN]; int main(){ scanf("%d%d",&n,&m);for (int i=1;i<=m;i++) scanf("%d%d",&P1[i],&P2[i]); for (int i=1;i<=n;i++){ B[i][i]=1; for (int j=m;j>=1;j--) if (B[i...
Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either `+` or `-`. Your task is to evaluate the formula instead of her. Constraints * 1≦A,B≦10^9 * op is either `+` or `-`. Input The input is given from Standard Input in the following format: A op B Outpu...
a,b,c=input().split();print(int(a)+int(c)if b=='+'else int(a)-int(c))
There is a hotel with the following accommodation fee: * X yen (the currency of Japan) per night, for the first K nights * Y yen per night, for the (K+1)-th and subsequent nights Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee. Constraints * 1 \leq N, K \leq 10000 * 1 \leq ...
import java.util.Scanner; class Main{ public static void main(String[] args) { Scanner stdIn=new Scanner(System.in); int n=stdIn.nextInt(),k=stdIn.nextInt(),x=stdIn.nextInt(),y=stdIn.nextInt(),s=0,i; for(i=0;i<n&&i<k;i++) s+=x; for(i=k;i<n;i++) s+=y; System.out.print(s); } }
Write a program that extracts n different numbers from the numbers 0 to 100 and outputs the number of combinations that add up to s. Each n number is from 0 to 100, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is 1 + 2 + 3 = ...
#include <iostream> using namespace std; long long dp[102][11][1002]; int main(){ int N,S; while(cin>>N>>S&&(N!=0)){ for(int i=101;i>=0;i--){ for(int j=0;j<=N;j++){ for(int k=0;k<=S;k++){ long long res=0; if(i==101)res=(j==0&&k==0); else{ res+=dp[i+1][j][k...
Ataru Oafoot of Aizu Gakuen University High School decided to play with a slot machine. When you insert a medal on this machine, three reels will start spinning and each reel will stop automatically. In a normal game (normal game), 3 medals are inserted, and when the symbols are aligned, the following medals are obtai...
import java.io.*; class Main { public static void main(String args[])throws IOException { BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); while(true) { String str=input.readLine(); String str_ary[]=str.split(" "); if(str_ary[0].equals("0") && str_ary[1].equals("0") && str_ary[2].equals("0") &...
Mr. Kobou found a bundle of old paper when he was cleaning his family home. On each paper, two series of numbers are written. Strange as it appeared to him, Mr. Kobou further went through the storehouse and found out a note his ancestor left. According to it, the bundle of paper is a treasure map, in which the two sequ...
#include <bits/stdc++.h> #define rep(i,n)for(int i=0;i<(n);i++) using namespace std; int a[2000],b[2000]; int main(){ int w,h;cin>>w>>h; priority_queue<int>que; rep(i,w){ scanf("%d",&a[i]); if(a[i])que.push(a[i]); } rep(i,h){ scanf("%d",&b[i]); vector<int>v; rep(j,b[i]){ if(que.empty()){ puts("0...
Emacs is a text editor which is widely used by many programmers. The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed witho...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; const ld eps = 1e-9; //// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_...
There are many blue cards and red cards on the table. For each card, an integer number greater than 1 is printed on its face. The same number may be printed on several cards. A blue card and a red card can be paired when both of the numbers printed on them have a common divisor greater than 1. There may be more than o...
#include <cstdio> #include <cstdlib> #include <algorithm> #include <cstring> #include <queue> #include <vector> #include <functional> #include <map> #include <set> #include <cmath> #include <string> #define SIZE 1002 #define INF 10000005 using namespace std; typedef long long int ll; typedef pair <int,int> P; ll K; ...
The earth is under an attack of a deadly virus. Luckily, prompt actions of the Ministry of Health against this emergency successfully confined the spread of the infection within a square grid of areas. Recently, public health specialists found an interesting pattern with regard to the transition of infected areas. At e...
#include <bits/stdc++.h> using namespace std; int main() { int N; while(cin >> N, N) { string S; for(int i = 0; i < N; i++) { string T; cin >> T; S += T; } queue< string > que; map< string, int > v; que.emplace(S); v[S] = 0; bool flag = false; while(!que.emp...
Problem Rolling Block is a game in which a rectangular parallelepiped metal body is rotated and moved, and dropped into a hole in the goal. The condition to clear this game is to drop the metal body to the goal. image0 About blocks From (1) in the figure below, the block is a 1 × 1 × L rectangular parallelepiped. Th...
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second typedef pair<int,int> P; struct data{ int y,x; int bit; int s; data(){ } data(int y...
Princess, a Cryptanalyst Decryption of the princess English text is not available in this practice contest. A brave princess in a poor country's tomboy got an old document written in Japanese, a town she went out in stealth. The princess can speak Japanese, so I immediately read this old document. Then I found somet...
#include <bits/stdc++.h> using namespace std; #define rep(i,n) repi(i,0,n) #define repi(i,a,b) for(int i=(int)(a);i < (int)(b);++i) template<class T1, class T2> ostream& operator << (ostream &s, pair<T1,T2> P) { return s << '<' << P.first << ", " << P.second << '>'; } template<class T> ostream& operator << (ostream &s,...
We understand that reading English is a great pain to many of you. So we’ll keep this problem statememt simple. Write a program that reports the point equally distant from a set of lines given as the input. In case of no solutions or multiple solutions, your program should report as such. Input The input consists o...
#include<bits/stdc++.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define HUGE_NUM 99999999999999999 #define MOD 1000000007 //#define EPS 0.000000001 using namespace std; #define EPS 0.000001 struct Point{ Point(double arg_x,double arg_y){ x = arg_x; y = arg_y; } ...
The 15th month of 2119. A spellbook was written by the court magician Sengemon Lugene. This magic book "In Magiray" was an innovative book in that it systematized "double magic", which is deeply related to the basis of the magic law of this world, as a technique that anyone can learn. First, let's take a look at a summ...
#include<cstdio> #include<iostream> #include<string> #include<map> #include<stack> #include<vector> #include<algorithm> using namespace std; const int inf=1e8; template<class T> void chMax(T &a,T b){ a=max(a,b); } map<string,int> elements; int m,head[110],to[10100],nxt[10100]; int pre[110]; int comp[110]; int num...
Sliding GCD Problem Statement For the set S of natural numbers, let f (S) be the number of elements in the set \\ {GCD (T) | T ⊆ S, T is not empty \\}. Here, GCD (T) is the greatest integer that divides all the numbers contained in T. In particular, note that GCD (\\ {a \\}) = a when T consists of only one integer a...
#include <cstdio> using namespace std; int ans; bool f[100001]; void check(int k, int t, int u){ if((t <= k && k <= u) || ((t + k - 1) / k < u / k)){ if(!f[k]){ f[k] = true; ++ans; } } else if(f[k]){ f[k] = false; --ans; } } int main(){ int n, w; scanf("%d%d", &n, &w); for(int i = 1; i <= w; +...
Problem statement A programming contest will be held in the Russian Federation. The contest has N questions and has M participants. Question i has a score a_i, and it is known that participant j's ability is b_j. For problem i and participant j, participant j can always solve problem i if a_i ≤ b_j and only then. The ...
#include <iostream> #include <string> #include <sstream> #include <algorithm> #include <vector> #include <utility> #include <functional> #include <stack> #include <queue> #include <map> #include <set> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <deque> #include <ctime> using name...
D: Sunburn-Suntan- story Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. Cute like an angel. Aizu Nyan is planning to participate in this summer festival, so I made a schedule for the band to go to listen to. I'm worried abou...
#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int,int> pii; #define rep(i,n) for(ll i=0;i<(ll)(n);i++) #define all(a) (a).begin(),(a).end() #define pb push_back #define INF (1e9+1) //#define INF (1LL<<59) int main(){ ll t; int n; cin>>t>>n; vector<ll> v; rep(i,n){ ll a,b; ...
problem There is a mysterious device $ M $, and if you put Tanuki and Fox in this device, one animal will come out from the device (hereinafter, Tanuki will be $ T $ and Fox will be $ F $). $ M (x, y) $ represents an animal that came out by putting animals in the device $ M $ in the order of $ x, y $. As a result of...
#include<bits/stdc++.h> #define INF 1e9 #define llINF 1e18 #define MOD 1000000007 #define pb push_back #define mp make_pair #define F first #define S second #define ll long long #define ull unsigned long long #define vi vector<ll> #define vvi vector<vi> #define BITLE(n) (1LL<<(n)) #define BITCNT(n) (__builtin_popcount...
A: Find the difference problem Given rectangular boards A and B with N squares vertically and M squares horizontally. For each board, each square is painted white or black. The color of the square in the i-th row and j-th column of the board X is written as C (i, j, X). Count how many pairs of integers (i, j) meet ...
/* -*- coding: utf-8 -*- * * 3107.cc: Spot The Difference */ #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<string> #include<vector> #include<map> #include<set> #include<stack> #include<list> #include<queue> #include<deque> #include<algorithm> #include<numeric> #in...
For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria: * It is a closed cycle where it ends at the same point it starts. * The route must go through every edge at least once. Constraints * 2 ≤ |V| ≤ 15 * 0 ≤ |E| ≤ 1,000 * 0 ≤ di ≤ 1,000 * si ≠ ti * T...
#include <iostream> #include <algorithm> using namespace std; #define INF 1e8 int main(){ int V,E; cin>>V>>E; int G[V][V]; fill(G[0],G[V],INF); int ans=0; int deg[V]; fill(deg,deg+V,0);//?¬???° for(int i=0;i<E;i++){ int s,t,d; cin>>s>>t>>d; G[s][t]=G[t][s]=min(G[...
Find the least common multiple (LCM) of given n integers. Constraints * 2 ≤ n ≤ 10 * 1 ≤ ai ≤ 1000 * Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1 Input n a1 a2 ... an n is given in the first line. Then, n integers are given in the second line. Output Print the least common multiple of th...
from functools import reduce import math n = int(input()) def lcm_base(x, y): return (x * y) // math.gcd(x, y) def lcm_list(numbers): return reduce(lcm_base, numbers, 1) numlis = [int(a) for a in input().split()] print(lcm_list(numlis))
Akhil comes across a string S of length N. He started wondering about the smallest lexicographical subsequence of string S of length K. A subsequence of a string is formed by deleting some characters (possibly none) from it's original string. A string A is said to be lexicographically smaller than the string B of the s...
import heapq def solve(s, k): res = [] start_index = -1 end_index = len(s) - k #choose the staring window h = [(y, x) for x, y in enumerate(s[:end_index])] heapq.heapify(h) for _ in range(k): # enlarge the window by increamenting one (character, pos_of_haracter) from right ...
Churu is taking the course called “Introduction to Data Structures”. Yesterday, he learned how to use a stack to check is a given parentheses expression is balanced or not. He finds it intriguing, and more importantly, he was given an assignment. The professor gave him a string S containing characters “(” and “)”, and ...
t=input() while t>0: t-=1 n,k=map(int,raw_input().split()) li=['0']*n flag=0 while k>0: k-=1 a,b=map(int,raw_input().split()) for i in range(a,b+1,2): li[i]="(" li[i+1]=")" for i in range(n): if li[i]=='0' and flag==0: li[i]="("...
You're given an integer N. Write a program to calculate the sum of all the digits of N. Input The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N. Output Calculate the sum of digits of N. Constraints 1 ≤ T ≤ 1000 1 ≤ N ≤ 100000 Example Inpu...
t=int(raw_input()) while(t>0): n=[] a=raw_input() n=list(a) n=map(int,list(n)) print sum(n) t-=1
Little Elephant from the Zoo of Lviv hates exams. Since Little Elephant lives in Ukraine, he is going to take exams called 'ZNO'. Help him. There will be n tickets on the table. Each ticket has a number written on it. The i-th ticket can be numbered Ai with probability Pi percent and with probability 100-Pi percent it ...
#! /usr/bin/env python # -* - coding: UTF-8 -* - rounds = int(raw_input()) A,B,P = [],[],[] def main(): for _ in range(rounds): tickets = int(raw_input()) global A, B, P A,B,P = [],[],[] for _ in range(tickets): p, a, b = raw_input().split(" ") P.append(int...
Given two vessels, one of which can accommodate a liters of water and the other which can accommodate b liters of water, determine the number of steps required to obtain exactly c liters of water in one of the vessels. At the beginning both vessels are empty. The following operations are counted as 'steps': emptying...
def gcd(a, b): while b: a, b = b, a%b return a def solve(a,b,c): if c==0:return 0 if c==a or c==b:return 1 if a>b:a,b=b,a if c>b:return -1 if c==b-a:return 2 d=gcd(a,b) if d!=1: if c%d:return -1 a/=d;b/=d;c/=d; q=b/a rk=0 r=a while True: ...
Problem description. A matrix of dimension mxn containing only 0's and 1's as it elements is given.Determine the maximum possible sub-square matrix containing only 1's as its elements Input Input description. The first line of input contains an integer T,denoting the number of test cases First line of each test cas...
t = int(raw_input()) for x in range(t): inputs = raw_input() inputs = inputs.split(" ") m = int(inputs[0]) n = int(inputs[1]) city_array = [] for x in range(m): temp = raw_input() temp = temp.split(" ") city_array.append(temp) for x in range(m): for y in range(n): if city_array[x][y] == '1': c...
After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of mo...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class C { public static void main(String[] args) { FastScanner fs=new FastScanner(); int n=fs.nextInt(); int[] board=fs.readArray(n); Space[] spaces=...
Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in. During his ride, Arkady woke up several time...
import java.util.*; public class determine_line{ public static void main(String[] args){ Scanner s = new Scanner(System.in); int n = s.nextInt(); ArrayList<Integer> ans = new ArrayList<Integer>(); ArrayList<ArrayList<Integer> > list = new ArrayList<ArrayList<Integer> >(); for...
You have a set of n weights. You know that their masses are a_1, a_2, ..., a_n grams, but you don't know which of them has which mass. You can't distinguish the weights. However, your friend does know the mass of each weight. You can ask your friend to give you exactly k weights with the total mass m (both parameters ...
import java.io.*; import java.util.*; public class Main { private void solve() throws Exception { n = nextInt(); HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>(); for(int i = 0; i < n; i++) { int a = nextInt(); countMap.put(a, countMap.getOrDefault(a, 0)+1); } a = countMap.keySet(...
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with ve...
#include <bits/stdc++.h> using namespace std; int n, ans = 1e9 + 5; int main(void) { cin >> n; for (int i = 1; i * i <= n; i++) { int j = (n % i == 0 ? n / i : n / i + 1); ans = ((ans) < (i + j) ? (ans) : (i + j)); } cout << ans << endl; return 0; }
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: * a12 + a22 + ... + an2 ≥ x * a1 + a2 + ... + an ≤ y Input The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please d...
#include <bits/stdc++.h> using namespace std; int main() { long long int n, x, y, i, ans; while (cin >> n >> x >> y) { if (y < n) { cout << -1 << endl; continue; } if (y - n + 1 > 1000000) ans = 1000000; else ans = y - n + 1; if ((n - 1) + ans * ans >= x) { for (i =...
You are given a rooted tree with n nodes, labeled from 1 to n. The tree is rooted at node 1. The parent of the i-th node is p_i. A leaf is node with no children. For a given set of leaves L, let f(L) denote the smallest connected subgraph that contains all leaves L. You would like to partition the leaves such that for...
#include <bits/stdc++.h> using namespace std; const int mod = 998244353; vector<int> v[200010]; int d[200010], d1[200010]; int rid_put(int a, int b) { int sol = 1; for (long long i = 1; i <= b; i <<= 1) { if (b & i) sol = (1LL * sol * a) % mod; a = (1LL * a * a) % mod; } return sol; } void dfs(int nod) ...
You are given an array a_1, a_2, ..., a_n. All a_i are pairwise distinct. Let's define function f(l, r) as follows: * let's define array b_1, b_2, ..., b_{r - l + 1}, where b_i = a_{l - 1 + i}; * sort array b in increasing order; * result of the function f(l, r) is ∑_{i = 1}^{r - l + 1}{b_i ⋅ i}. Calcula...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); const ld pi = acos(0) * 2; template <typename T> inline void read(T &x) { char c; bool nega = 0; while ((!isdigit(c = getchar())) && (c != '-...
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
def solve(n, m, k): if min(m,k) >= n: return "Yes" else: return "No" def main(): n, m, k = list(map(int, input().split())) print(solve(n, m, k)) if __name__ == '__main__': main()
You are given integer n. You have to arrange numbers from 1 to 2n, using each of them exactly once, on the circle, so that the following condition would be satisfied: For every n consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard 2n numbers differ not more th...
n = int(input()) if n%2 == 0: print("NO") exit(0) arr = [] for i in range(1, n+1): if i%2 == 1: arr.append(2*i-1) else: arr.append(2*i) for i in range(n): if arr[i] % 2 == 1: arr.append(arr[i]+1) else: arr.append(arr[i]-1) print("YES") print(*arr)
Alice and Bob play a game. Initially they have a string s_1, s_2, ..., s_n, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select...
#include <bits/stdc++.h> using namespace std; bool solve(int a, int b, char str[]) { vector<int> arr; int curr = 0; for (int i = 0; str[i] != 0; i++) { if (str[i] == '.') curr++; else if (str[i] == 'X' && curr != 0) { arr.push_back(curr); curr = 0; } } if (curr != 0) arr.push_bac...
Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them. The tree looks like a polyline on the plane, consisting o...
#include <bits/stdc++.h> using namespace std; int a[100001]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } sort(a, a + n); unsigned long long sum1 = 0, ans, sum2 = 0; for (int i = n - 1; i >= (n / 2); i--) { sum1 += a[i]; } for (int i = 0; i < (n / 2)...
Let G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v ∈ W the distance between u and v is either k or k+1. You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set. Input The first...
#include <bits/stdc++.h> using namespace std; const long long N = 5e5 + 9; vector<long long> adj[N], vec[N]; long long h[N], up[N], ans[N]; pair<long long, long long> edge[N]; vector<pair<long long, long long> > a[N], b; void DFS1(long long u, long long par) { h[u] = 1; for (long long v : adj[u]) if (v != par) ...
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { double n, d; cin >> n >> d; if (n >= d) { cout << "YES" << endl; continue; } double x = 1, f = 0; double y; for (int i = 0; i < d; i++) { y = double(d / (x + 1)); y = ceil(...
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
value = input() print(int(value, 16)%2)
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
import java.util.*; import java.math.*; public class solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int a1 = sc.nextInt(); int b1 = sc.nextInt(); int a2 = ...
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the gr...
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self...
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu ...
#! /usr/bin/python3 n, d, m = [int(inp) for inp in input().split()] aArr = sorted([int(inp) for inp in input().split()], reverse = True) i = sum([j > m for j in aArr]) aU = aArr[:i] aL = aArr[i:] aUS = aU for i in range(1, len(aU)): aUS[i] += aUS[i - 1] aUS = [0] + aUS aLS = aL for i in range(1, len(aL)): aLS[i]...
You are given four integers n, m, l and r. Let's name a tuple (x_1, y_1, x_2, y_2) as good if: 1. 1 ≤ x_1 < x_2 ≤ n; 2. 1 ≤ y_2 < y_1 ≤ m; 3. x_1 ⋅ y_1 = x_2 ⋅ y_2; 4. l ≤ x_1 ⋅ y_1 ≤ r. Find any good tuple for each x_1 from 1 to n inclusive. Input The first line contains two integers n and m (1 ≤ n...
#include <bits/stdc++.h> constexpr int N = 2e5; std::vector<int> divisors[N + 1]; int cnt[N + 1]; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, m; std::cin >> n >> m; int64_t l, r; std::cin >> l >> r; --l; for (int i = 1; i <= N; ++i) for (int j = i; j <= N; j += i) di...
In this problem MEX of a certain array is the smallest positive integer not contained in this array. Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today. You are given an array a of length n. Lesha considers all the non-empty...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5, S = 355; int n, a[N], cnt[N], B, bel[N], cntb, L[N], R[N], mar[S][N]; vector<int> p[N]; pair<int, int> rg[N]; bool check(int l, int r, int mex) { if (!mex) return true; if (mex > n + 1) return false; for (int i = 1; i < bel[mex]; i++) if (ma...
Ron is a happy owner of a permutation a of length n. A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is...
from sys import stdin from functools import reduce from operator import mul rints = lambda: [int(x) for x in stdin.readline().split()] rfloats = lambda: [float(x) for x in stdin.readline().split()] rfloat_2d = lambda n: [rfloats() for _ in range(n)] out = [] for _ in range(int(input())): n, m = rints() a, qur...
You are a given an array a of length n. Find a subarray a[l..r] with length at least k with the largest median. A median in an array of length n is an element which occupies position number ⌊ (n + 1)/(2) ⌋ after we sort the elements in non-decreasing order. For example: median([1, 2, 3, 4]) = 2, median([3, 2, 1]) = 2,...
import java.io.*; import java.util.*; public class CF { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringToke...
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them. Diana is happy when the product of the numbers ends with he...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vii; typedef vector<vi> vvi; typedef vector<pll> vll; typedef vector<vl> vvl; #define fori(i, n) for (in...
Omkar and Akmar are playing a game on a circular board with n (2 ≤ n ≤ 10^6) cells. The cells are numbered from 1 to n so that for each i (1 ≤ i ≤ n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty. Omkar and Akmar take turns placing either an A or a B on the board, wit...
#include<bits/stdc++.h> using namespace std; #define ll long long #define pii pair<int,int> const ll lp = 1e9+7; const int msize = 1e6+7; //! ll power ll powmod(int a, int x){ //a^x if (x == 0) return 1; if (x % 2 == 0){ ll temp = powmod(a,x/2); return (temp*temp) % lp; }else{ ll t...
The best programmers of Embezzland compete to develop a part of the project called "e-Government" — the system of automated statistic collecting and press analysis. We know that any of the k citizens can become a member of the Embezzland government. The citizens' surnames are a1, a2, ..., ak. All surnames are differen...
#include <bits/stdc++.h> using namespace std; const int MaxN = 1000005; struct node { node* fail; node* next[26]; int lo, hi; vector<node*> link; node() { fail = NULL; for (int i = 0; i < 26; i++) next[i] = NULL; } }; int T, n; char text[MaxN]; node* root = new node(); queue<node*> Q; int fenwick[10...
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
n=int(input()) e=10**9+7 print(1if n==0else(pow(2,n-1,e)+pow(2,n*2-1,e))%e) # Made By Mostafa_Khaled
The Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better. The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered...
#include <bits/stdc++.h> using namespace std; class fenv_tree { static int f(int x) { return x & -x; } vector<int> tr; public: void add(int x, int v) { assert(0 <= x && x + 1 < ((int)(tr).size())); for (x++; x < ((int)(tr).size()); x += f(x)) tr[x] += v; } int get(int x) { assert(-1 <= x && x + ...
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class VasyaMagic { public static void main(String[] args) throws IOException{ BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] ns = bf.readLine().split(" "); int n,d,l; n = Int...
Vasya has got many devices that work on electricity. He's got n supply-line filters to plug the devices, the i-th supply-line filter has ai sockets. Overall Vasya has got m devices and k electrical sockets in his flat, he can plug the devices or supply-line filters directly. Of course, he can plug the supply-line filt...
n,m,k=map(int,input().split(" ")) li=list(map(int,input().split(" ",n)[:n])) li.sort(reverse=True) fl=0 a,s=0,0 if m<=k: print(0) else: while fl==0 and a<n: s+=li[a] a+=1 if a!=1: s-=1 if s+k-1>=m and a!=0: fl=1 break if fl!=1: prin...
You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side tha...
import math def solve(a1, b1, c1, a2, b2, c2): return (c1 * b2 - c2 * b1) / (a1 * b2 - a2 * b1), (c1 * a2 - c2 * a1) / (b1 * a2 - b2 * a1) if __name__ == '__main__': w, h, a = [int(x) for x in raw_input().split()] w, h = max(w, h), min(w, h) a = min(a, 180 - a) / 180.0 * math.pi if a < 2.0 * math.atan2(h, w): ...
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. 1. The algorithm receives a string as the input. We denote this input string as a. 2. The algorithm consists of some number of command. Сommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strin...
#include <bits/stdc++.h> using namespace std; int main() { string s; int n; cin >> n; for (int i = 0; i < n; i++) getline(cin, s); for (int i = 0; i < 10; i++) cout << "??" << i << ">>" << i << "??" << endl; cout << "??>>?" << endl; for (int i = 0; i < 9; i++) cout << i << "?<>" << i + 1 << "\n"; cout <...
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are ...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[]args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int d = in.nextInt(); int [] h = new int [n]; for(int i=0 ; i<n ; i+...
Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain n distinct segments and m distinct circles. We will consider the segments indexed from 1 to n in some way and the circles — indexed from 1 to m in some way. Palpatine defines an owl as a set of a pa...
#include <bits/stdc++.h> #pragma GCC optimize("unroll-loops") #pragma GCC optimize("O3") #pragma GCC optimize("fast-math") using namespace std; const long long INF = 2e9; const long long INFll = 2e18; const long long BASE1 = 179; const long long BASE2 = 653; const long long MOD = 1e9 + 7; const long long MAXN = 1e5 + 1...
Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies". The babies playing board is an infinite plane containing n blue babies and m red ones. Each baby is a segment that grows in time. At time moment t the blue baby (x, y) is a blue segment with en...
#include <bits/stdc++.h> using namespace std; template <class P, class Q> void mmin(P &a, const Q &b) { if (b < a) a = b; } template <class P, class Q> void mmax(P &a, const Q &b) { if (b > a) a = b; } template <class P> P GCD(P a, P b) { if (a < b) swap(a, b); P c; while (b) { c = a % b; a = b; b...
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to w...
#include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); while (t--) { int n, l, r; scanf("%d%d%d", &n, &l, &r); if (n < l) cout << "No" << endl; else if ((n >= l && n <= r) || (n / l * r >= n) || (r >= 2 * l - 1)) cout << "Yes" << endl; else cout <<...
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address (vasya@gmail.com). It is known that a proper email address contains only such symbols a...
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int sl = s.length(); string ans = ""; ans += s[0]; bool at = false; for (int i = 1; i < sl; i++) { if (at == false && (sl - i) > 2 && s.substr(i, 2) == "at") ans += '@', at = true, i++; else if ((sl - i) > 3 && s....
DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment. Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one numb...
def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().split()) def msi(): return map(str,input().split()) def li(): return list(mi()) n=ii() a=li() pre,suf = [1]*n,[1]*n for i in range(1,n): if a[i]>a[i-1]: pre[i]+=pre[i-1] for i in range(n-2,-1,-1): if a[i]...
Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: * If number x belongs to set A, then number a - x must also belong to set A. * If number x belongs to set B, then number b - x must also belong to set B. Hel...
#include <bits/stdc++.h> using namespace std; const int N = int(1e5) + 10; const int K = int(2e6) + 10; const long long MOD = int(1e9) + 7; const int INF = int(1e9) + 5; const long long INF64 = 1e18; map<int, int> mp, ans; int p[N], q[N]; vector<int> f, s, t; void solve() { int n, a, b; cin >> n >> a >> b; for (i...
During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working. Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of...
import math from collections import deque class Empty(Exception): pass class _DoublyLinkedBase: """A base class providing a doubly linked list representation.""" #-------------------------- nested _Node class -------------------------- # nested _Node class class _Node: """Lightweight, nonpublic class ...
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can ...
n, x0, y0 = map(int, input().split()) slopes = {} # key: (num, den), val: count for i in range(n): x, y = map(int, input().split()) num = y - y0 den = x - x0 # print(num, den) if den == 0 and "inf" in slopes: slopes["inf"] += 1 elif den == 0: slopes["inf"] = 1 else: ...
You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice. The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists e...
#include <bits/stdc++.h> using namespace std; int target, n, m; bool same_x(int i, int j) { return ceil(i / (double)m) == ceil(j / (double)m); } bool same_y(int i, int j) { return i - (ceil(i / (double)m) - 1) * m == j - (ceil(j / (double)m) - 1) * m; } bool edge_exists(int i, int j) { return ((abs(i - j) == 1 && (...
One Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities. The Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he...
#include <bits/stdc++.h> using namespace std; struct line { long long a; long long b; long long c; int id; }; vector<pair<int, int> > ans; const long double eps = 1e-12; bool do_inter(const line &l, const line &r) { return (l.a * r.b != r.a * l.b); } bool on(const line &l, const pair<long double, long double> &...
In Berland a money reform is being prepared. New coins are being introduced. After long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. Also the following restriction has been introduced for comfort: the denomination of each coin should be div...
#include <bits/stdc++.h> using namespace std; int main() { int a; cin >> a; for (int i = a; i > 0; i--) { if (a % i == 0) { a = i; cout << a << " "; } } return 0; }
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits! One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some s...
import java.util.Scanner; /** * Created by d40a on 01.01.16. */ public class Main { static final int mod = (int)(1e9) + 7; public static void main(String[] args) { Scanner reader = new Scanner(System.in); int n = reader.nextInt(); reader.nextLine(); char[] s = reader.next().to...
Blake is a CEO of a large company called "Blake Technologies". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem. We define function f(x, l, r) as a bitwise OR of integers xl, xl + 1, ...
#include <bits/stdc++.h> using namespace std; vector<int> a, b; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; a.push_back(x); } for (int i = 0; i < n; i++) { int x; cin >> x; b.push_back(x); } int ret = 0; for (int i = 0; i < n; i++) { int aa = ...
As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the nam...
import java.util.*; import java.math.*; import static java.lang.Character.isDigit; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import static java.lang.Math.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import static java.util.Collections.*;...
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink fo...
def binary(t,s): fir=0 last=len(t)-1 mid=0 while(fir<=last): mid=(fir+last)//2 if t[mid]>s: last=mid-1 else: fir=mid+1 return last+1 n=int(input()) t=list(map(int,input().split())) m=int(input()) p=0 t.sort() for i in range(m): s=int(inp...
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot ...
#include <bits/stdc++.h> using namespace std; void scanint(long long int &x); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int n, a, b, k; cin >> n >> a >> b >> k; long long int i = 0; string s; cin >> s; long long int pre = -1; long long int total = 0; for (i = 0; i < n; ...
You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from l to r. All <image> segments are equiprobable. 2. Let k = r - l + 1, i.e. the le...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; template <class T, class U> inline void Max(T &a, U b) { if (a < b) a = b; } template <class T, class U> inline void Min(T &a, U b) { if (a > b) a = b; } inline void add(int &a, int b) { a += b; while (a >= 10000...
You are given n integers a1, a2, ..., an. Denote this list of integers as T. Let f(L) be a function that takes in a non-empty list of integers L. The function will output another integer as follows: * First, all integers in L are padded with leading zeros so they are all the same length as the maximum length numb...
#include <bits/stdc++.h> using namespace std; const int maxn(1e6 + 5); const int mod(1e9 + 7); inline void Inc(int &x, int y) { x = x + y >= mod ? x + y - mod : x + y; } inline int Add(int x, int y) { return x + y >= mod ? x + y - mod : x + y; } inline void Dec(int &x, int y) { x = x - y < 0 ? x - y + mod : x - y; } in...
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: 1. Set ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; int v[N], lson[N], rson[N], used[N], l[N], r[N]; set<int> s; void dfs(int x) { if (~lson[x]) { l[lson[x]] = l[x]; r[lson[x]] = min(r[x], v[x]); dfs(lson[x]); } if (~rson[x]) { l[rson[x]] = max(l[x], v[x]); r[rson[x]] = r[x];...
You are given a set of integer numbers, initially it is empty. You should perform n queries. There are three different types of queries: * 1 l r — Add all missing numbers from the interval [l, r] * 2 l r — Remove all present numbers from the interval [l, r] * 3 l r — Invert the interval [l, r] — add all missin...
#include <bits/stdc++.h> using namespace std; int seg[2 * (1 << 18)], segFlip[2 * (1 << 18)], l[2 * (1 << 18)], r[2 * (1 << 18)], up[2 * (1 << 18)]; void init() { for (int i = (1 << 18); i < 2 * (1 << 18); i++) { l[i] = r[i] = i - (1 << 18); seg[i] = 1000000000, segFlip[i] = i - (1 << 18); } for (int ...
You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is...
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution1 { public static void main(String[] args) { int n = i(),c=0; TreeMap<Integer,Integer> tm = new TreeMap(); TreeMap<Integer,Integer> ts = new TreeMap(); ...
Recently Ivan noticed an array a while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug. Ivan clearly remembers that there were n elements in the array, and each element was not less...
#include <bits/stdc++.h> using namespace std; bool print = 0; struct Edge { Edge() { x = y = c = f = w = 0; } Edge(long long _x, long long _y, long long _c, long long _f, long long _w) : x(_x), y(_y), c(_c), f(_f), w(_w) {} long long x, y, c, f, w; }; struct MinCostMaxFlow { int n, m, idm = 0, s, t; int...
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Des...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 5; const long long MOD = 1e9 + 7; long long d[N], psum[N], fact[N], ifact[N], n, k, ans, tmp; long long bigExp(long long a, long long b) { long long res = 1; while (b) { if (b & 1) res = (res * a) % MOD; a = (a * a) % MOD; b >>= 1; } ...
During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals. Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow ...
y,b=input().split(' ') ay,ag,ab=input().split(' ') y=int(y) b=int(b) ay=int(ay) ag=int(ag) ab=int(ab) b=b-(ab*3) y=y-(ay*2) b=b-ag y=y-ag br=0 if(y<0): br=br-y if(b<0): br=br-b print(br)
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has n lanterns and Big Ban...
n, m = [int(x) for x in input().split()] lstT = [int(x) for x in input().split()] lstB = [int(x) for x in input().split()] z=-9999999999999999999999999999 T=0 B=0 for i in range(n): for j in range(m): if z<lstT[i]*lstB[j]: T=i B=j ...
Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence...
#include <bits/stdc++.h> using namespace std; int x, d, i; vector<long long> v; long long temp = 1; long long po(int power) { long long ans = 1; for (int j = 0; j < power; j++) ans *= 2; return ans; } int main() { ios_base::sync_with_stdio(false); cin >> x >> d; while (x > 0) { if (x == 1) { v.pus...
You are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). C...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1000005; using namespace std; bool vis[5000000]; bool have[5000000]; int a[5000000]; int N, M, MASK; void dfs(int u) { vis[u] = 1; if (!vis[u ^ MASK] && have[u]) dfs(u ^ MASK); for (int i = 0; i < N; i++) { if (u & (1 << i)) { if (!vis[u ^ (...
Alook was composing magical spells for his mage master. The mage was good at spellcasting but since spell design requires intricate mathematics, this task was given to Alook who had the gift of numbers. The power contained in a spell is a function of its lexicographical structure, which is why Alook wants to extensive...
def matmult(a,b,c,M): #/multiply matrix a and b. put result in c for i in xrange(2): for j in xrange(2): c[i][j]=0 for k in xrange(2): c[i][j]+=(a[i][k]*b[k][j]) c[i][j]=c[i][j]%M def matp...
You are given a collection of words, say as in a dictionary. You can represent it in the following compressed form: The first word will be followed by a sequence of pair of a integer (x) and a word. The number in the pair is the position till which the previous word's characters are included in the new word and ...
N=input(); Q=raw_input(); for _ in xrange(N-1): n,s=raw_input().split(); m=int(n); temp=Q[:m]; temp+=s; Q=temp; print Q
Bosky often helps his younger brother Nitin with his home work and also clears his doubts. Today, Nitin learned about proper fractions. He went a step forward and tried to represent the same proper fraction in its decimal form, but runs into problems. He now seeks help from his brother Bosky. Nitin is a very sincere ...
def nth_digit(a,b,c): r=a digit=0 for _ in xrange(c): if r==0: return 0 digit=(r*10)/b r=(r*10)%b return digit for _ in xrange(input()): temp=map(int,raw_input().split()) a,b,c=temp[0],temp[1],temp[2] print nth_digit(a,b,c)
Andrew is very fond of Maths.He has N boxes with him,in each box there is some value which represents the Strength of the Box.The ith box has strength A[i]. He wants to calculate the Overall Power of the all N Boxes. Overall Power here means Sum of Absolute Difference of the strengths of the boxes(between each pair of...
t = input() while (t > 0): n = input() a = [] i = 0 line = raw_input().split(' ') while(i < n) : a.append(int(line[i])) i = i+1 a.sort(reverse=True) x = n-1 temp = 0 for i in range(0,n): temp += x*a[i] x -= 2 print (temp*a[0])%1000000007 t = t-1
After obtaining a lot of gold from capturing different kingdoms, King Kala buys a large area of land. N trees are planted on the land, numbered from 1 to N. Each tree i, has coordinates as Xi, Yi. King Kala has two sons who, as their father, are selfish. To divide the land between two sons, King Kala draws a partition ...
t=input() count=0 count1=0 while (t): n=input() d=map(int,raw_input().strip().split(' ')) a=d[0] b=d[1] c=d[2] for i in range (n): x,y=raw_input().strip().split(' ') x,y=[int(x),int(y)] w=a*x+b*y+c if(w>0): count=count+1 elif(w==0): ...
You have been given a String S consisting of uppercase and lowercase English alphabets. You need to change the case of each alphabet in this String. That is, all the uppercase letters should be converted to lowercase and all the lowercase letters should be converted to uppercase. You need to then print the resultant St...
a=raw_input() res=[] for i in a: if ord(i)>=65 and ord(i)<=90: res.append(chr(ord(i)+32)) else: res.append(chr(ord(i)-32)) print "".join(res)