input
stringlengths
29
13k
output
stringlengths
9
73.4k
Takahashi has a string S of length N consisting of digits from `0` through `9`. He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten. Here substrings starting with a `0`...
n,m=map(int,input().split());s=input();l=[0]*m;a,t,p=0,0,1 if 10%m: for i in s[::-1]:l[t%m]+=1;t+=int(i)*p;a+=l[t%m];p=p*10%m else:a=sum(i+1 for i in range(n) if int(s[i])%m<1) print(a)
Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-e...
#include<cstdio> #include<algorithm> #include<vector> #include<queue> #include<cstring> using namespace std; const int N=205; int n,mrk[N],dep[N],ans;vector<int>E[N];queue<int>Q; void dfs(int u,int c){ mrk[u]=c; for(int v:E[u]) if(!~mrk[v])dfs(v,c^1); else if(mrk[v]!=(c^1))puts("-1"),exit(0); } void bfs(int u){ ...
Consider the following arithmetic progression with n terms: * x, x + d, x + 2d, \ldots, x + (n-1)d What is the product of all terms in this sequence? Compute the answer modulo 1\ 000\ 003. You are given Q queries of this form. In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i. Constraints *...
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; typedef pair<int,int> P; typedef long long ll; const int maxn=1e6+10; const int mod=1000003; ll sum[mod]; ll ni[mod]; ll pows(ll a,ll b) { ll re=1; while(b) { if(b&1) re=a*re%mo...
Let N be a positive odd number. There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i. Taro has tossed all the N coins. Find the probability of having more heads than tails. Constraints * N is an od...
import java.util.*; public class Main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); double P [] = new double[N+1]; double DP[][] = new double[N+1][N+1]; for(int i=1;i<=N;i++){ P[i]= sc.nextDouble(); ...
There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.) For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem: * Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K. Here, or denot...
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define pb push_back #define fi first #define se second typedef pair<ll,ll> P; using VP = vector<P>; using VVP = vector<VP>; using VI = vector<int>; using VVI = vector<VI>; using VVVI = vector<VVI>; const int inf=1e9+7; const ll INF=1LL<<61; const ll mo...
An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have...
#include <bits/stdc++.h> using namespace std; int main(){ int n, x; set<int> him; cin >> n; for (int i = 0; i < n; i++){ cin >> x; him.insert(x); } cout << (int) him.size() << "\n"; }
Alice and Bob are controlling a robot. They each have one switch that controls the robot. Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up. Bob started holding down his button C second after the start-up, and released his button D second...
a,b,c,d=map(int,input().split()) print(max(0,min(d,b)-max(a,c)))
There is a railroad in Takahashi Kingdom. The railroad consists of N sections, numbered 1, 2, ..., N, and N+1 stations, numbered 0, 1, ..., N. Section i directly connects the stations i-1 and i. A train takes exactly A_i minutes to run through section i, regardless of direction. Each of the N sections is either single-...
#include<cstdio> #include<cstring> #include<algorithm> #define int long long using namespace std; const int N=100005; int n,k,ans,a[N],b[N],L[N],R[N],sum[N],f[N],h[N*2],val[N*8]; void pushdown(int o){ if(val[o]){ val[o*2]=val[o*2+1]=val[o]; val[o]=0; } } void update(int o,int l,int r,int L,int R,int v){ if(L>R){...
There are K pieces of cakes. Mr. Takahashi would like to eat one cake per day, taking K days to eat them all. There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i. Eating the same type of cake two days in a row would be no fun, so Mr. Takahashi would like to decide the order for eating ...
#!/usr/bin/env python3 k,t = map(int,input().split()) a = list(map(int,input().split())) print(max(0,2*(max(a)-(k+1)//2)-1))
Fukushima Prefecture is also famous for producing fruits, and among them, peaches and apples boast one of the highest production volumes in Japan. By the way, when I made a print manuscript of an English pamphlet for sale, I mistakenly wrote the description about apples and the description about peaches in reverse. Yo...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNextLine()){ String s = sc.nextLine(); s = s.replaceAll("apple", "\n\n\n\n\n"); s = s.replaceAll("peach", "apple"); s = s...
Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities. Recently, it was decided to reduce the maintenance cost of the brid...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(true){ int n = sc.nextInt(); int m = sc.nextInt(); if(n == 0 && m == 0) break; ArrayList<ArrayList<Edge>> map = new ArrayList<ArrayList<Edge>>(); for(int i=0;i<n;i++){ map...
We, the researchers who discovered and investigated the ancient nation Iwashiro, finally discovered the temple in the center of Iwashiro. A lithograph dedicated to the god of Iwashiro was stored in the temple. On the lithograph, two strings were written, one for each sentence and one for the spell. In Iwashiro, how ma...
#include<iostream> #include<algorithm> #include<vector> #include<queue> #define lol(i,n) for(int i=0;i<n;i++) #define mod 1000000007 typedef long long ll; using namespace std; #define N 1010 string s,t; ll dp[N][N]; int main(){ cin>>s>>t; int n=s.size(),m=t.size(); lol(j,m+1)dp[0][j]=0;dp[0][0]=1; for(...
Take the'IOI'train A new railway has been laid in IOI. Trains running on railways in IOI are a combination of several vehicles, and there are two types of vehicles, I and O. Vehicles can only be connected to different types of vehicles. Also, because the train has a driver's seat, the cars at both ends of the train mu...
#include <bits/stdc++.h> #define FOR(i,n) for(int i=0;i<(int)(n);i++) #define FORR(i,m,n) for(int i=(int)(m);i<(int)(n);i++) #define pb(a) push_back(a) #define mp(x,y) make_pair(x,y) #define ALL(a) a.begin(),a.end() #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,-1,sizeof(a)) #define len(a) sizeof(a) #...
Professor Tsukuba invented a mysterious jewelry box that can be opened with a special gold key whose shape is very strange. It is composed of gold bars joined at their ends. Each gold bar has the same length and is placed parallel to one of the three orthogonal axes in a three dimensional space, i.e., x-axis, y-axis an...
def solve(sentence): now = [0, 0, 0] # x,y,z num_p = {} positions = [] for s in sentence: if s.isdecimal(): if s in num_p: now = num_p[s] else: num_p[s] = now else: sign = 1 if s[0] == "+" else -1 if s[1] ==...
Prof. Bocchan is a mathematician and a sculptor. He likes to create sculptures with mathematics. His style to make sculptures is very unique. He uses two identical prisms. Crossing them at right angles, he makes a polyhedron that is their intersection as a new work. Since he finishes it up with painting, he needs to k...
#include<stdio.h> #include<algorithm> #include<vector> #include<math.h> using namespace std; int X[2][5]; int Y[2][5]; int L[20]; int R[20]; double EPS=1e-9; int ABS(int a){return max(a,-a);} int main(){ int a; while(scanf("%d",&a),a){ for(int i=0;i<20;i++){ L[i]=R[i]=0; } for(int i=0;i<a;i++)scanf("%d%d",&X...
Problem K Counting Cycles Given an undirected graph, count the number of simple cycles in the graph. Here, a simple cycle is a connected subgraph all of whose vertices have degree exactly two. Input The input consists of a single test case of the following format. $n$ $m$ $u_1$ $v_1$ ... $u_m$ $v_m$ A test case ...
#include <bits/stdc++.h> using namespace std; using Edge = int; using Edges = vector<Edge>; using Graph = vector<Edges>; Graph Compression(const int n, const int m, vector<set<int>> &g) { stack<int> st; for (int v = 0; v < n; ++v) if (g[v].size() == 1) st.push(v); while (!st.empty()) { i...
Warp Drive <image> The warp drive technology is reforming air travel, making the travel times drastically shorter. Aircraft reaching above the warp fields built on the ground surface can be transferred to any desired destination in a twinkling. With the current immature technology, however, building warp fields is q...
#include <bits/stdc++.h> using namespace std; using VI = vector<int>; using VVI = vector<VI>; using PII = pair<int, int>; using LL = long long; using VL = vector<LL>; using VVL = vector<VL>; using PLL = pair<LL, LL>; using VS = vector<string>; #define ALL(a) begin((a)),end((a)) #define RALL(a) (a).rbegin(), (a).rend...
The median filter is a nonlinear digital filter used to reduce noise in images, sounds, and other kinds of signals. It examines each sample of the input through a window and then emits the median of the samples in the win- dow. Roughly speaking, a window is an interval that contains a target sample and its preceding an...
#include<iostream> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cmath> #include<set> #include<vector> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) #define ALL(C) (C).begin(),(C).end() const int N = 8; const int inf = (1<<20); char m[N][N]; inline in...
Problem A: Swap crypto A 2D enthusiast at R University, he often writes embarrassing sentences that blush when seen by people. Therefore, in order for a third party to not be able to see the text he is writing, he encrypts the text using a method called swap encryption that he devised independently. In swap encryption...
#include <iostream> #include <sstream> #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <cstring> #include <string> #include <vector> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <bitset> #include <numeric> #include <utility> #include <iomanip>...
A gene is a string consisting of `A`,` T`, `G`,` C`. The genes in this world are strangely known to obey certain syntactic rules. Syntax rules are given in the following form: Non-terminal symbol 1: Symbol 1_1 Symbol 1_2 ... Symbol 1_n1 Non-terminal symbol 2: Symbol 2_1 Symbol 2_2 ... Symbol 2_n2 ... Non-terminal sy...
#include <cstdio> #include <string> #include <iostream> #include <vector> #include <map> #include <cctype> #include <cstring> #include <sstream> #define MOD 1000000007LL using namespace std; typedef long long ll; typedef string::const_iterator State; typedef pair<int,int> P; int n[4]; int all; int m; string str[51]; ...
Problem Statement One day, my grandmas left $N$ cookies. My elder sister and I were going to eat them immediately, but there was the instruction. It said * Cookies will go bad; you should eat all of them within $D$ days. * Be careful about overeating; you should eat strictly less than $X$ cookies in a day. My sist...
#include <bits/stdc++.h> template< typename T > T mod_pow(T x, T n, const T &p) { if(x < 0) return 0; T ret = 1; while(n > 0) { if(n & 1) (ret *= x) %= p; (x *= x) %= p; n >>= 1; } return ret; } using namespace std; using ll = long long; using vi = vector<int>; using vvi = vector<vi>; using vll = ...
Problem statement Meatishi can increase or decrease the number of fingers. There are n buns in front of Nikunishi-kun. Meatishi is trying to count the number of steamed buns by breaking his finger. There are only two shapes that Nishikun's fingers can take, whether they are broken or not. Nikunishi understands binary ...
#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_...
casino The company you work for is developing a new casino game. Today I decided to consider a recently proposed game. In this game, N dice are rolled at the same time, and the total number of rolls is the score. The player plays with the goal of increasing the score. If you don't like the roll, you can roll the dice...
//#include <bits/stdc++.h> #include <cstdio> #include <iostream> #include <cmath> using namespace std; typedef long double ld; typedef long long ll; ld dice[23][23*6]; struct Mat{ ld val[2][2]; Mat operator* (const Mat &b) const{ Mat res; for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ ...
Problem Given a sequence $ A $ of length $ H $ and a sequence $ B $ of length $ W $. Define the matrix $ C $ consisting of $ H $ rows and $ W $ columns as follows. $ C_ {i, j} = A_i \ times B_j (1 \ leq i \ leq H, 1 \ leq j \ leq W) $ Process the following four types of queries a total of $ Q $ times. Query 1 $ 1 $...
#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 #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pa...
For a given sequence $A = \\{a_0, a_1, ... a_{n-1}\\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program: bubbleSort(A) cnt = 0 // the number of inversions for i = 0 ...
#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef pair<int,int> pii; #define rep(i,n) for(ll i=0;i<(ll)(n);i++) #define all(a) (a).begin(),(a).end() #define pb emplace_back #define INF (1e9+1) //#define INF (1LL<<59) ll solve_inversion(vector<int> &v){ if(v.size()==1)return 0; ...
Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card. The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner ...
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int T = 0; int H = 0; for(int i = 0; i < n; i++){ String sT = scan.next(); String sH = scan.next(); if(sT.compareTo(sH) < 0){ H += 3; } else if(sT.co...
Abhi and his friends (Shanky,Anku and Pandey) love to play with strings. Abhi invented a simple game. He will give a string S to his friends. Shanky and Anku will play the game while Pandey is just a spectator. Shanky will traverse the string from beginning (left to right) while Anku will traverse from last (right to l...
# cook your code here T = int(raw_input()) for i in range(T): s = raw_input() l = [0 for j in range(26)] length = len(s) for j in range(length): index = ord(s[j])-97 l[index] = l[index]+1 flag = 0 x = 0 y = 0 for j in range(length): x = ord(s[j])-97 if l[x...
Every great chef knows that lucky numbers are 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. Our chef has recently returned from the Lucky country. He observed that every restaurant in the Lucky country had a luc...
import sys t = int(sys.stdin.readline()) while t>0: n = int(sys.stdin.readline()) count = n/7 rem = n%7 count-=rem%4 if count<0: print -1 else: print count*7 t-=1
Are you fond of collecting some kind of stuff? Mike is crazy about collecting stamps. He is an active member of Stamp Collecting Сommunity(SCC). SCC consists of N members which are fond of philately. A few days ago Mike argued with the others from SCC. Mike told them that all stamps of the members could be divided in...
n=int(int(raw_input())) c=map(int,raw_input().split()) total=sum(c) x=(n*(n+1))/2 if total==x: print 'YES' else: print 'NO'
Problem description. This problem deals with the I/O methods used in codechef. You are supposed to print the integer in its reverse form , or in simple words, print the reverse of the given integer . For instance , reverse of 120 is 21 (not 021) . Input The first line of each test case contains an integer T . fol...
# cook your code here n=input() for i in range(n): x=raw_input() print long(x[::-1])
Alice is a very brilliant student. He considers '4' and '7' as Magic numbers. The numbers containing only magic numbers are also magical. Given a magic number N ,he wants to know what could be the next magical number greater than the given number. Input First line of input contains number of test cases T. For each t...
t=int(input()) while t>0: t-=1 s=raw_input() l=len(s) loc=-1 for i in range(l-1,-1,-1): if s[i]=='4': loc=i break if loc==-1: s='4'+s.replace('7','4') else: s=s[:loc]+'7'+s[loc+1:].replace('7','4') print s
Problem Statement Sereja has a sequence of n integers a[1], a[2], ..., a[n]. Sereja can do following transformation of the array:   create a new sequence of n integers b[1], b[2], ..., b[n]in this way: (1 ≤ i ≤ n) Replace the sequence a by b, i.e., a[i] = b[i] for all i in [1, n]   Sereja decided to use his trans...
#http://ruhinraihan.blogspot.in/2013/10/codechef-october-challenge-2013_7091.html MOD=1000000007 def Bigmod(base,power): ret=1 while power>0: if power%2==1: ret=(ret*base)%MOD base=(base*base)%MOD power>>=1 return ret t=int(raw_input()) for _ in range(0,t): n,m,q,k=map(int,raw_input().split()) if m<=q: ...
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ...
n = int(input()) mn = list(map(int, input().split())) k = 1 for i in range(1, 101): s = mn.count(i) if s > k: k = s print(k)
You are given a chessboard of size n × n. It is filled with numbers from 1 to n^2 in the following way: the first ⌈ (n^2)/(2) ⌉ numbers from 1 to ⌈ (n^2)/(2) ⌉ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest n^2 - ⌈ (n^2)/(2) ⌉ numbers from ⌈ (n^2)/(2) ⌉ + 1 to n^2 ...
import sys n,q=map(int,sys.stdin.readline().strip().split()) nc=n # print(n,q) if(n%2==0): n2=int((n*n)/2) else: n2=int((n*n)/2)+1 n1=int(n/2) if(1==1): for i in range(q): x,y=map(int,sys.stdin.readline().strip().split()) # print(n,q,x,y) x1=int(x/2) y1=int(y/2) ...
In the last mission, MDCS has successfully shipped N AI robots to Mars. Before they start exploring, system initialization is required so they are arranged in a line. Every robot can be described with three numbers: position (x_i), radius of sight (r_i) and IQ (q_i). Since they are intelligent robots, some of them wil...
#include <bits/stdc++.h> using namespace std; const int N = 4e5 + 50; struct node { int x, r, q; int L, R; void print() { printf("%d %d %d %d %d\n", L, R, x, r, q); } bool operator<(const node& rhs) const { return r < rhs.r; } } a[N]; struct Orz { vector<int> a; void clr() { a.clear(); } void add(int x) {...
The Galaxy contains n planets, there are many different living creatures inhabiting each planet. And each creature can get into troubles! Space rescuers know it perfectly well and they are always ready to help anyone who really needs help. All you need to do is call for them. Now the space rescuers plan to build the ...
#include <bits/stdc++.h> double dis(double a, double b, double c) { return sqrt(a * a + b * b + c * c); } double x[105], y[105], z[105]; int main() { int n; scanf("%d", &n); double tx = 0, ty = 0, tz = 0, eps = 1.0; for (int i = 0; i < n; i++) { scanf("%lf %lf %lf", &x[i], &y[i], &z[i]); tx += x[i]; ...
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence p. For example, if n = 3, then p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence will be n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We cal...
import java.io.*; import java.util.*; public class D { static long[] fact; static long A = 998244353l; static void gen(){ fact = new long[1000002]; fact[0] = 1; for(int i=1;i<fact.length;i++){ fact[i] = fact[i-1]*i; fact[i]%=A; } } public sta...
You have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired. You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece...
n, m, k = (int(x) for x in input().split()) b = [int(x) for x in input().split()] deltaB = sorted([b[i + 1] - b[i] for i in range(n - 1)]) print(sum(deltaB[:n - k]) + k)
One day as Petya and his friend Vasya were having one of their numerous trips, they decided to visit a museum castle. The museum has a specific shape: it consists of n rooms connected with m corridors so that one can access any room from any other one. After the two friends had a little walk around the museum, they de...
#include <bits/stdc++.h> using namespace std; struct Edge { int to, next; } e[500]; int tot, head[25], n, m, a, b, i, j, num, id[25][25], pos[630][2], d[25], k; double v[630][630], p[25], ans[25]; inline void add(int u, int v) { e[++tot].to = v; e[tot].next = head[u]; head[u] = tot; } int main() { int uu, vv;...
Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≤ i ≤ n it is true that 1 ≤ p_i ≤ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≤ n, such that p_j > p_i. If there is no su...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using pll = pair<ll, ll>; const int MOD = (int)1e9 + 7; const int MAX = (int)2e9; const double PI = acos(-1); int nex[500010]; vector<int> adj[500010]; int cnt; int p[500010]; void dfs(int u) { p[u] = cnt--; for (int v :...
Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 ⋅ a_2 ⋅ ... a_n of its elements seemed to him not large enough. He was ready t...
#include <bits/stdc++.h> using namespace std; int main() { long long n; cin >> n; long long arr[n]; long long cntp = 0, cntz = 0; for (long long i = 0; i < n; i++) { cin >> arr[i]; } for (long long i = 0; i < n; i++) { if (arr[i] >= 0) { arr[i] = -1 * arr[i] - 1; } } long long max = ...
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac...
import math h, l = input().split() h = int(h) l = int(l) a = float((pow(l,2)-pow(h,2))/(2*h)) print(a)
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n. He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arb...
l = int(input()) s = list(input().strip()) ct = 0 for i in range(0,l-1,2): if s[i] == s[i+1]: ct += 1 if s[i] == 'a': s[i] = 'b' else: s[i] = 'a' print(ct) print(''.join(s))
This is a harder version of the problem. In this version, n ≤ 300 000. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya beli...
#include <bits/stdc++.h> int main() { std::ios::sync_with_stdio(0); std::cin.tie(0); int n; std::cin >> n; if (n % 2 != 0) { std::cout << "0\n1 1\n"; return 0; } std::string s; s.reserve(n); std::cin >> s; assert(s.size() == n); if (std::count(begin(s), end(s), '(') * 2 != n) { std::co...
You play a computer game. In this game, you lead a party of m heroes, and you have to clear a dungeon with n monsters. Each monster is characterized by its power a_i. Each hero is characterized by his power p_i and endurance s_i. The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero ...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int inf = 0x3f3f3f3f; int p[200005]; int v[200005]; int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int a = 1; a <= n; a++) { scanf("%d", &v[a]); p[a] = 0; } int m, x, y;...
Your friend Kirchhoff is shocked with the current state of electronics design. "Ohmygosh! Watt is wrong with the field? All these circuits are inefficient! There's so much capacity for improvement. The electrical engineers must not conduct their classes very well. It's absolutely revolting" he said. The negativity ju...
#include <bits/stdc++.h> using namespace std; const int maxn = 160010; int T, r, f[maxn], lnk[1000010], mark[maxn], from[maxn]; long long ans[maxn]; string str; vector<int> G[maxn]; int main() { ios::sync_with_stdio(0); cin >> T; while (T--) { cin >> r; getline(cin, str); stack<int> st; for (int i...
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of t...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int N = 1e5 + 5; int n, m, k, t, T; double x, y; pair<int, int> p[N]; void solve() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d%d", &p[i].first, &p[i].second); if (n % 2) { printf("NO\n"); return; } x = (double)(...
Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in...
def indices(arr): ind = [] for i, val in enumerate(arr): if val >= 0: ind.append(i) return ind def e(hours, mem, lo, hi, hour_day): for i in range(len(hours)): # for each day non_zero = indices(mem[i]) for v in non_zero: next_hour = (v + hours[i]) % ho...
You are given an array a consisting of n integers (it is guaranteed that n is even, i.e. divisible by 2). All a_i does not exceed some integer k. Your task is to replace the minimum number of elements (replacement is the following operation: choose some index i from 1 to n and replace a_i with some integer in range [1...
from bisect import bisect_left from collections import Counter def solve(n, k, a): s = [a[i] + a[n-i-1] for i in range(n//2)] amin = sorted([min(a[i], a[n-i-1]) for i in range(n//2)]) amax = sorted([max(a[i], a[n-i-1]) for i in range(n//2)]) ans = float('inf') counter = Counter(s) fo...
Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers. The value of a non-empty subsequence of k elements of a is defined as ∑ 2^i over all integers i ≥ 0 such that at least max(1, k - 2) elements of the subsequence have the i-th bit set in their bin...
import java.io.*; import java.util.*; import java.math.*; public class E { static final boolean RUN_TIMING = false; static char[] inputBuffer = new char[1024]; static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1024); static PrintWriter out = new PrintWr...
You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a w...
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") using namespace std; using ull = unsigned long long; using ll = long long; using ld = long double; using pii = pair<int, int>; using pll = pair<long long, long long>; using pil = pair<int, long long>; using pli = pair<long long, in...
This is an interactive problem. We hid from you a permutation p of length n, consisting of the elements from 1 to n. You want to guess it. To do that, you can give us 2 different indices i and j, and we will reply with p_{i} mod p_{j} (remainder of division p_{i} by p_{j}). We have enough patience to answer at most 2...
#include <bits/stdc++.h> using namespace std; const int Max_N = 1e4; int n, a[Max_N + 5]; inline int Read() { int num = 0; char ch = getchar(); for (; ch < '0' || ch > '9'; ch = getchar()) ; for (; ch >= '0' && ch <= '9'; num = num * 10 + ch - '0', ch = getchar()) ; return num; } inline int Ask(int x,...
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2). He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will...
#include <bits/stdc++.h> using namespace std; long long power(long long x, long long y) { if (y == 0) return 1; else if (y % 2 == 0) return power(x, y / 2) * power(x, y / 2); else return x * power(x, y / 2) * power(x, y / 2); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t;...
Ridbit starts with an integer n. In one move, he can perform one of the following operations: * divide n by one of its proper divisors, or * subtract 1 from n if n is greater than 1. A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 2...
for _ in range(int(input())): k = 3 n = int(input()) if n == 1: print("0") elif n == 2: print("1") elif n == 3: print("2") elif n%2==0: print("2") else: print("3")
You are given an integer n. Check if n has an odd divisor, greater than one (does there exist such a number x (x > 1) that n is divisible by x and x is odd). For example, if n=6, then there is x=3. If n=4, then such a number does not exist. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of t...
test_cases = 1 test_cases = int(input()) for ttttt in range(test_cases): n = int(input()) while n%2==0: n/=2 if n==1: print("NO") else: print("YES")
As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path ...
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class D14 { static ArrayList<Integer>[]ages; static int[]depth; static int sum_max; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ages...
You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly k\ \% magic essence and (100 - k)\ \% water. In one step, you can pour either one liter of magic essence or one liter of water i...
import math for i in range(int(input())): n=int(input()) a=100-n b=n if n==100: print(1) else: g=math.gcd(a,b) print(a//g+b//g)
Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of somethin...
#include <bits/stdc++.h> using namespace std; char X[102]; int t, n; int A[102][2501]; int i, j; int k, s, ct; long long suma; int main() { for (i = 0; i <= 25; i++) A[1][i] = 1; for (i = 1; i <= 100; i++) A[i][0] = 1; for (k = 2; k <= 100; k++) for (s = 1; s <= 2500; s++) { i = k - 1; j = s; ...
The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series. There are n single men and n single women among the main characters. An opinion poll showed that viewers lik...
#include <bits/stdc++.h> using namespace std; clock_t __stt; inline void TStart() { __stt = clock(); } inline void TReport() { printf("\nTaken Time : %.3lf sec\n", (double)(clock() - __stt) / CLOCKS_PER_SEC); } template <typename T> T MIN(T a, T b) { return a < b ? a : b; } template <typename T> T MAX(T a,...
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some...
#include <bits/stdc++.h> using namespace std; const int MX = 1e5 + 7; vector<long long> v[MX]; bool vis[2][MX], ans; string s[2]; long long n, k; void DFS(bool UD, long long i, long long flood) { if (s[UD][i] == 'X' || i <= flood || vis[UD][i]) return; if (i >= n - k) { ans = 1; return; } vis[UD][i] = 1...
Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most m different nucleotides, numbered from 1 to m. Special characteristics of the Martian DNA prevent some nucleotide pairs from followin...
#include <bits/stdc++.h> using namespace std; const int bfsz = 1 << 16; char bf[bfsz + 5]; int rsz = 0; int ptr = 0; char gc() { if (rsz <= 0) { ptr = 0; rsz = fread(bf, 1, bfsz, stdin); if (rsz <= 0) return EOF; } --rsz; return bf[ptr++]; } void ga(char &c) { c = EOF; while (!isalpha(c)) c = gc...
General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants. All soldiers in the battalion have different beauty that is represented by a positive integer. The value...
#include <bits/stdc++.h> using namespace std; int a[100010], b[100010]; int main() { int n, sum, k; while (~scanf("%d%d", &n, &k)) { sum = 0; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } sort(a, a + n); for (int i = 0; i < n && k; i++) { for (int j = n - 1 - i; j >= 0 && k; j-...
You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad. A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2...s|s| (where |s| is the length of string s) is string slsl + 1...sr. The substring s[l...r] is good, if among the letters sl, sl + 1, ..., sr t...
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author Saju * */ public class Main { static int[] dx = { 0, 1, 0, -1 }; static int[] dy = { -1, 0, 1, 0 }; static final int MOD = 1000000007; static final int MAX = 100000007; public static void main(String[] args) { InputRead...
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di. Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, ...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 7; long long mas[maxn] = {0}; long long a[maxn]; long long mean[maxn] = {0}; long long ask[maxn][3]; long long ans[maxn] = {0}; int main() { int n, m, k; cin >> n >> m >> k; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= m; i++...
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x ...
#include <bits/stdc++.h> using namespace std; const int N = 150; int cnt[2][N][N]; int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; int main() { memset(cnt, 0, sizeof(cnt)); int n, t; scanf("%d%d", &n, &t); int now = 0, flag; cnt[1][N / 2][N / 2] = n; do { flag = 0; for (int i = 1; i < N; i++) for ...
Xenia likes puzzles very much. She is especially fond of the puzzles that consist of domino pieces. Look at the picture that shows one of such puzzles. <image> A puzzle is a 3 × n table with forbidden cells (black squares) containing dominoes (colored rectangles on the picture). A puzzle is called correct if it meets...
#include <bits/stdc++.h> using namespace std; const int maxn = 10010; const long long mod = 1e9 + 7; long long f[maxn][8], g[maxn][8]; char a[3][maxn]; int n; int lst[3], now[3]; long long work() { memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 0; i < n; i++) for (int j = 0; j < 8; j++) { if (!f[i][...
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can b...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); boolean found = false; for (int j = 1; j < 5; ++j) { int a = s.nextInt(); int b = s.nextInt(); int c = s.nextInt(); int d = s.nextInt...
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom o...
#include <bits/stdc++.h> using namespace std; int dp[105][105][105], n; vector<int> pilesNumbers[105]; set<pair<int, int> > s[2]; int getMaxDiff(int p, vector<pair<int, int> > indices, bool turn) { int i, j, res = INT_MIN, curr; if (~dp[p][indices[p].first][indices[p].second]) return dp[p][indices[p].first][ind...
A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? Input The input contains two integers a and b (0 ≤ a, b ≤ 103), separated by a single space. Output Output ...
import sys import os a,b=input().split() a=int(a) b=int(b) print(a+b)
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The...
import java.util.*; public class CFC219{ public static void main(String args[]){ Scanner ob=new Scanner(System.in); //System.out.println("SAKJJ"); int n=ob.nextInt(); int m=ob.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=ob.nextInt(); int sum=0; ...
Vasya is a born Berland film director, he is currently working on a new blockbuster, "The Unexpected". Vasya knows from his own experience how important it is to choose the main characters' names and surnames wisely. He made up a list of n names and n surnames that he wants to use. Vasya haven't decided yet how to call...
import java.util.Arrays; import java.util.Scanner; public class E { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String[] p = new String[n]; String[] s = new String[n]; int pc[] = new int[26]; int sc[] = ne...
You have a rooted tree consisting of n vertices. Let's number them with integers from 1 to n inclusive. The root of the tree is the vertex 1. For each i > 1 direct parent of the vertex i is pi. We say that vertex i is child for its direct parent pi. You have initially painted all the vertices with red color. You like ...
#include <bits/stdc++.h> using namespace std; const int mod = (int)1e9 + 7; const int inv2 = 500000004; vector<int> g[100100]; int f[100100][2]; int n; void loadtree(void) { scanf("%d", &n); for (int i = (2), _b = (n); i <= _b; i = i + 1) { int u; scanf("%d", &u); g[u].push_back(i); } for (int i = (...
Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi. Mr. Kitayuta wants you to process the following q queries. In the i-th query, he gives you two integers - ui and vi. ...
#make a table n,m = map(int,input().split()) arr = [[] for i in range(n+1)] for i in range(1,m+1): l = list(map(int,input().split())) arr[l[0]].append((l[1],l[2])) arr[l[1]].append((l[0],l[2])) #dfs def dfs(a,b,k): if a == b: return True seen.append(a) for i in arr[a]: x,c = i...
You are given circular array a0, a1, ..., an - 1. There are two types of operations with it: * inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v; * rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively). Assume segments to be c...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; struct segNode { long long val; long long lazy; int l, r; segNode() { val = lazy = 0; } segNode(int a, int b, int c) { val = a; l = b; r = c; lazy = 0; } }; int arr[N]; segNode segTree[4 * N]; void shift(int num, int left, ...
Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network. In this network are n vertices, some pairs of vertices are connected by m undirected channels. It is planned to transfer q important messages via this network, the i-th of w...
import java.io.*; import java.util.*; public class Main { static final boolean _DEBUG = true; static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner(BufferedReader _br) { br = _br; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new Str...
Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no e...
#include <bits/stdc++.h> using namespace std; int main() { int x[30], y[30], k = 0, n = 0, s = 0; for (int i = 1; i <= 3; i++) { cin >> x[i] >> y[i]; if (x[i] > k) k = x[i], n = i, s = y[i]; if (y[i] > k) k = y[i], n = i, s = x[i]; } int n1 = 0, s1 = 0; for (int i = 1; i <= 3; i++) { if (n == ...
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the pow...
#include <bits/stdc++.h> using namespace std; int k; const int N = 1e5 + 5; int a[N]; inline int GetSG(int x) { if (x < 2) return x; if (k & 1) { if (x == 2) return 0; if (x == 3) return 1; if (x == 4) return 2; if (x & 1) return 0; else { int tmp = GetSG(x / 2); return tmp > 1...
Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the sam...
import io import sys import time import random start = time.clock() #~ test = '''6 #~ URLLDR''' #~ test = '''7 #~ RLRLRLR''' #~ test = '''200 #~ ''' #~ for i in range(200): #~ test += random.choice("UDLR") #~ print(test) #~ test = '10 15' #~ test = '1 1000000' #28733372 #~ test = '1 11' #55 #~ test = '1 21' #130 ...
Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 × 3, each cell contains a single integer from 1 to n, an...
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { new Main().run(); } void run() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); ...
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
import math n=int(raw_input()) A=[int(x) for x in raw_input().split()] A=[(1-x%2,1-x/2) for x in A] #print A g={} def f(d,i):#d is the day he's on (from 0 to n-1) and i=-1,0,1. -1 means he's resting. D=3*d+i if D in g: return g[D] if d==n-1: if i==-1: g[D]=1 return 1 ...
There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a ...
#include <bits/stdc++.h> const int INF = 2147483647; const int INF2 = 0x3f3f3f3f; const long long INF64 = (long long)2e18; const double INFD = 1e30; const double EPS = 1e-9; const double PI = std::acos(-1); const int MOD = 1e9 + 7; template <typename T> inline T read() { T X = 0, w = 0; char ch = 0; while (!isdig...
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if...
n, m, k = map(int, input().split()) a = map(int, input().split()) b = map(int, input().split()) ab = [(0, 0)] + list(zip(a, b)) l = list(range(n + 1)) def f(x): if x == l[x]: return x l[x] = f(l[x]) return l[x] for i in range(m): x, y = map(int, input().split()) x, y = f(x), f(y) ...
There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team ...
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class submission{ public static void main(String[] args) throws IOException { BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); int num=Integer.parseInt(input.readLine()); String home=inp...
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should als...
#include <bits/stdc++.h> using namespace std; int n, k; bool a[2042]; int minTo[2042]; priority_queue<pair<int, int> > q; int main() { ios::sync_with_stdio(false); cin.tie(NULL); cin >> n >> k; for (int i = 0; i < k; i++) { int b; cin >> b; a[1000 + (n - b)] = 1; } for (int i = 0; i <= 2000; i++...
Tired of boring dates, Leha and Noora decided to play a game. Leha found a tree with n vertices numbered from 1 to n. We remind you that tree is an undirected graph without cycles. Each vertex v of a tree has a number av written on it. Quite by accident it turned out that all values written on vertices are distinct an...
#include <bits/stdc++.h> using namespace std; inline int read() { int res = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -f; ch = getchar(); } while (isdigit(ch)) { res = res * 10 + ch - '0'; ch = getchar(); } return res * f; } namespace qiqi { const int N = 2e5...
<image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's s...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
l = [] for _ in range(int(input())): s = input() if s not in l: print('NO') l.append(s) else: print('YES')
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai. Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in ...
#include <bits/stdc++.h> using namespace std; int main() { long long int n, k, m; cin >> n >> k >> m; vector<long long int> a(n); vector<int> blockLen, blockCity; long long int gone = 0, last = 0, consec = 0; for (int i = 0; i < n; i++) { cin >> a[last]; if (last == 0 || a[last] == a[last - 1]) ...
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken. CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th...
t = int(input()) for i in range(0,t): flag = 0 x = int(input()) b = 0 temp = x while temp >= 0 : if(temp%3 == 0): flag = 1 break b = b+1 temp = x-7*b if flag == 1 : print("YES") else: print("NO")
One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units. In order for production to work, it is needed ...
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll N = 1e6; ll n, first, second; pair<ll, ll> a[N]; signed main() { ios::sync_with_stdio(0), cin.tie(0); cin >> n >> first >> second; for (ll i = 0; i < n; ++i) { cin >> a[i].first; a[i].second = i + 1; } sort(a, a + n); ll fi...
There is a matrix A of size x × y filled with integers. For every <image>, <image> Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you st...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 7; const int M = 1e9; int a[N]; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; int common = -1; for (int i = 1; i < n; i++) { int dif = abs(a[i] - a[i - 1]); if (dif =...
The city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon p...
EMPTY = "." HOTEL = "#" def main(): n, k = map(int, input().split()) print("YES") print(EMPTY * n) if k % 2 == 0: m = k // 2 s = EMPTY + HOTEL * m + EMPTY * (n - m - 1) print(s) print(s) elif k < n - 1: s = (HOTEL * k).center(n, EMPTY) print(s) ...
And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x. Poor Student knows the following: * during one run the minibus makes n st...
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 Main { static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReade...
After a lot of hard work, Goyal has finally completed his app. But before he launches it, he needs to test it. His friends are helping him on this. Whenever a friend uses the app, his name is recorded in the logs. At the end of the day, Goyal makes a "Hall of Fame" by number of times a person has used his app, and prom...
# -*- coding: utf-8 -*- """ Created on Fri Jul 3 19:24:47 2015 @author: ishank011 """ n=int(raw_input()) s=raw_input().split() d={} for a in s: d[a]=0 for a in s: d[a]+=1 for i in range(101, 0, -1): for key in d: if d[key]==i: print key, d[key]
Now After eliminating the invalid registrations they are planning to form connections to the participants laptops. The connection can be direct or indirect form and there should be only one connection exists between them. After setting the connections management wanted to know the laptops are connected or not. This pro...
n=input();c=[];t=[] for j in range(input()): c.append(raw_input().split(" ")) for i in range(input()): t.append(raw_input().split(" ")) for k in t: if k in c: print "Direct Connection" else: found=False z=k[0] for i in c: if z==i[0]: z=i[1] ...
Write a program to find the mode of a given list of integers. Mode of a number is defined as the number which is most frequently occured. For example: L = {1,2,2,3} // Here mode is 2(most frequently occured) It is possible that multiple answers are possible for a list. In that case print all possible answers in no...
test_cases=input() while test_cases>0: num_of_integers=input() # li = [0]*1000001 a=list(map(int,raw_input().split())) b=[0]*len(a) mydict=dict(zip(a,b)) # print mydict if len(a)==num_of_integers: for i in a: # li[i]=li[i]+1 mydict[i]+=1 else: ...
Write your program in Ruby which takes an un-indented Ruby code as string and outputs the indented Ruby code as string. Input Format A string which is un-indented Ruby code Output Format A string which is indented Ruby code SAMPLE INPUT class YabbaDabbaDoo def foo if foo == 42 puts 'world hel...
a = "" st = "" g = 0; while(a!="end"): a = raw_input() i = 0 n = len(a) while(a[i]==" "): i = i + 1 b = a[i:n] c = map(str,b.split(" ")) if "class" in c: print b elif "def" in c: st = st + " " print st + b elif "if" in c: st = st + " " ...
Arya is new to matrices. With lots of subtopics in the chapter, he finds it difficult in getting good in all of them. As of now, he is practising matrix multiplications. He takes two different matrices and checks in how many different ways could they be multiplied. If they are multiplicable, he multiplies in all the wa...
tc=int(raw_input()) while tc>0: tc-=1 a,b,c,d=map(int,raw_input().split()) t=0 if b==c: t+=1 if a==d: t+=1 print t
Some people remain old fashioned and John is one of them. He doesn't like the new smart phones with full keypads and still uses the old keypads which require you to tap a key multiple times to type a single letter. For example, if the keyboard has two keys, one with the letters "adef" and the other one with the letters...
n = input() freq = map(int,raw_input().split()) freq.sort(reverse=True) k = input() key = map(int,raw_input().split()) ans=0 indx=1 if(sum(key)<n): print -1 else: i=0 while i<n: j=0 while j<k and i<n: if(key[j]>0): ans += freq[i]*indx key[j] -=1 i +=1 j +=1 indx +=1 print ans
Raju has a very pretty girlfriend. He chats with her all day and night through his phone. His phone lacks a QWERTY keypad, instead it has a T9 keypad. This takes a lot of time to type a message in his phone and he often fears that his girlfriend might get angry if he doesn't reply on time. So he sets a time limit to t...
l1 = [['.',',','?','!','1'],['a','b','c','2'],['d','e','f','3'],['g','h','i','4'],['j','k','l','5'],['m','n','o','6'],['p','q','r','s','7'],['t','u','v','8'],['w','x','y','z','9'],['_','0']] T = input() while T > 0: X,Y,Z = map(int,raw_input().split()) string = raw_input() current = 0 final = '' tot = 0 for s in...