input
stringlengths
29
13k
output
stringlengths
9
73.4k
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct points and m segme...
import java.util.*; import java.io.*; import java.math.BigInteger; import java.text.*; public class Main { static long mod = 1000_000_007; static long mod1 = 998244353; static boolean fileIO = false; static boolean memory = true; static FastScanner f; static PrintWriter pw; static double eps...
You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before i...
#include <bits/stdc++.h> using namespace std; const int INF = (1 << 31) - 1; const long long int LINF = (1LL << 63) - 1; const int NMAX = 100000 + 5; const int MMAX = 100000 + 5; const int KMAX = 100000 + 5; const int PMAX = 100000 + 5; const int LMAX = 100000 + 5; const int VMAX = 100000 + 5; int N[4], T[4], K; long l...
Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traff...
#include <bits/stdc++.h> int main() { int n, m; scanf("%d %d\n", &n, &m); std::string horizontal; getline(std::cin, horizontal); std::string vertical; getline(std::cin, vertical); std::string cycle = std::string("") + horizontal[0] + vertical[0] + horizontal[n - 1] + vertical[m - 1];...
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes. You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Scanner; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Praveen */ public class Main { pu...
Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food. The flight menu has k dishes in t...
#include <bits/stdc++.h> using namespace std; const int N = 1234567; int cnt[N]; bool res[N]; int main() { int tt; cin >> tt; while (tt--) { int people, dishes; cin >> people >> dishes; for (int i = 0; i < dishes; i++) { cin >> cnt[i]; res[i] = false; } people--; bool good = tr...
Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has n points, Sasha — m. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that ...
#include <bits/stdc++.h> using namespace std; const int N = 10100; const double eps = 1e-9; struct node { int x, y; node operator+(const node &q) const { return node{x + q.x, y + q.y}; } node operator-(const node &q) const { return node{x - q.x, y - q.y}; } bool operator==(const node &q) const { return x == q.x...
People in BubbleLand like to drink beer. Little do you know, beer here is so good and strong that every time you drink it your speed goes 10 times slower than before you drank it. Birko lives in city Beergrade, but wants to go to city Beerburg. You are given a road map of BubbleLand and you need to find the fastest wa...
#include <bits/stdc++.h> using namespace std; vector<int> e[100001], w[100001], sv[100001]; int dis[100001], diss[100001], dl[100001], fr[100001], ff[100001], nt[100001], rr[100001], vis[100001], rk[100001]; int ed, n, m, dd, x, y, z; inline bool cmp(int x, int y) { if (rk[x] != rk[y]) return rk[x] < rk[y]; ...
You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given. One operation of a cyclic shift (rota...
#include <bits/stdc++.h> using namespace std; long long n; string s, f; int main() { cin >> s >> n; if (s.length() == 1) { cout << s << endl; return 0; } for (int j = 1; j <= n; j++) { int l, r, k; cin >> l >> r >> k; k %= (r - l + 1); l--; for (int i = 0; i < l; i++) f += s[i]; ...
Your friend recently gave you some slimes for your birthday. You have a very large amount of slimes with value 1 and 2, and you decide to invent a game using these slimes. You initialize a row with n empty spaces. You also choose a number p to be used in the game. Then, you will perform the following steps while the l...
#include <bits/stdc++.h> const size_t maxN = 1005; const int pppp = 100; int N, P; long double A[maxN][maxN], B[maxN][maxN], F[maxN][maxN]; struct matrix_t { long double a[pppp + 3][pppp + 3]; inline long double *operator[](int x) { return a[x]; } inline const long double *operator[](int x) const { return a[x]; }...
Limak is a big polar bear. He prepared n problems for an algorithmic contest. The i-th problem has initial score pi. Also, testers said that it takes ti minutes to solve the i-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it...
#include <bits/stdc++.h> using namespace std; const long double pi = 3.1415926535897932384626433832795l; template <typename T> inline auto sqr(T x) -> decltype(x * x) { return x * x; } template <typename T1, typename T2> inline bool umx(T1& a, T2 b) { if (a < b) { a = b; return 1; } return 0; } template...
<image> As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to tran...
n, l = int(input()), list(map(int, input().split())) print(2 * max(l) - sum(l) + 1)
Zombies have found out about the Zombie Contamination level checker and managed to damage it! Now detecting the shape of their main compound will be a real challenge for Heidi. As before, a lair can be represented as a strictly convex polygon on a lattice. Each vertex of the polygon occupies a point on the lattice. How...
#include <bits/stdc++.h> using namespace std; bool isLeft(const pair<int, int>& a, const pair<int, int>& b, const pair<int, int>& c) { return (b.first - a.first) * 1LL * (c.second - a.second) - (b.second - a.second) * 1LL * (c.first - a.first) <= 0LL; } vector<pair<int, int>> convexH...
Owl Sonya gave a huge lake puzzle of size n × m to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be empty — there was no picture on them. Parts with picture on it are denoted by 1, while empty parts are denoted by 0. Rows of the puzzle are n...
import java.io.*; import java.util.*; public class D_2d_sparse { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; int n, m; static int log2(int x) { return 31 - Integer.numberOfLeadingZeros(x); } void solve() throws IOException { n = nextInt(); m = nextInt(); int[][] a = new int...
Recently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6. Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task! Each digit c...
import javax.lang.model.element.Element; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class TestClass { static class FastReader { BufferedReader br; StringToken...
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland. Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is workin...
import java.util.*; import java.io.*; import java.lang.*; public class B758 { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); String s=in.nextLine(); HashMap< Integer,Character> hm=new HashMap<>(); for(int i=0;i<s.len...
Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters. Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his lang...
#include <bits/stdc++.h> using namespace std; const int N = 300005; const int K = 26; vector<pair<int, char> > g[N]; int n, tr[N << 1][K], sz[N << 1]; int ans[N], ptr; void dfs(int v, int p) { sz[v] = 1; for (auto x : g[v]) { if (x.first != p) { tr[v][x.second - 'a'] = x.first; dfs(x.first, v); ...
The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed. The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has...
#include <bits/stdc++.h> using namespace std; void read_file(bool outToFile = true) {} struct MCMF { struct Edge { int u, v; int cap, cost; int prv; Edge(int u, int v, int cap, int cost, int prv) : u(u), v(v), cap(cap), cost(cost), prv(prv) {} }; int src, snk; int par[(3000 + 99)]; int...
Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string s initially. Evolution of the species is described as a sequence of changes i...
#include <bits/stdc++.h> using namespace std; int sum[11][11][4][100002], n, m, num[100], block, cur, ans = 0, lef[12], ri[12], now[12]; char second[100002], ch, ss[15]; void update(int pos, int c, int val) { for (int i = 1; i <= 10; i++) { block = pos / i, ...
From beginning till end, this message has been waiting to be conveyed. For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times: * Remove any two elements s and t...
import java.math.BigInteger; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Wtf { public static void main(String[] args) throws IOException { Ifmo ifmo = new Ifmo(); } } class Ifmo { ArrayList<Integer> Graph[]; int n, l, m, primes, timer; char[][] fie...
You are given a positive integer n. Let's build a graph on vertices 1, 2, ..., n in such a way that there is an edge between vertices u and v if and only if <image>. Let d(u, v) be the shortest distance between u and v, or 0 if there is no path between them. Compute the sum of values d(u, v) over all 1 ≤ u < v ≤ n. Th...
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long rand(long long l, long long r) { uniform_int_distribution<long long> uid(l, r); return uid(rng); } const int mod = 1e9 + 7; int pwr(int a, int b) { int ans = 1; while (b) { if (b & 1)...
— Willem... — What's the matter? — It seems that there's something wrong with Seniorious... — I'll have a look... <image> Seniorious is made by linking special talismans in particular order. After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly. Seniorious has n p...
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } long long lcm(long long a, long long b) { return (a * b) / gcd(a, b); } long long poww(long long a, long long b) { if (b == 0) return 1; long long tmp = poww(a, b / 2); return (b & 1 ? a * tmp *...
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that a yuan for b kilos (You don't need to care about what "yuan" is), the same as a/b yuan for a kilo. Now imagine you'd like ...
import java.util.Collections; import java.util.Scanner; public class Super { public static void main(String[] args) { Scanner jk = new Scanner(System.in); int n = jk.nextInt(); Long m = jk.nextLong(); Double[] ins = new Double[n]; for (int i=0; i<n; i++) { Double a = jk.nextDouble(); Double b =...
You come home and fell some unpleasant smell. Where is it coming from? You are given an array a. You have to answer the following queries: 1. You are given two integers l and r. Let ci be the number of occurrences of i in al: r, where al: r is the subarray of a from l-th element to r-th inclusive. Find the Mex of ...
#include <bits/stdc++.h> using std::lower_bound; using std::sort; using std::swap; using std::unique; const int N(3e5 + 5); template <class type> inline const void read(type &in) { in = 0; char ch(getchar()); while (ch < 48 || ch > 57) ch = getchar(); while (ch > 47 && ch < 58) in = (in << 3) + (in << 1) + ...
Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin ...
#include <bits/stdc++.h> using namespace std; char lower(char a) { if (a >= 'A' && a <= 'Z') return (a + 32); return a; } bool isGede(char a) { if (a >= 'A' && a <= 'Z') return true; return false; } int main() { int n; cin >> n; vector<string> v(n); for (int i = 0; i < n; i++) cin >> v[i]; for (int i ...
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect. The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the ...
//package com.prituladima.codeforce.contests;//package com.prituladima.codeforce; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * Created by prituladima on 6/16/18. */ public class C994A { public cl...
Exams are approaching soon and everyone tries to get ready for them. So, Omar decides to begin studying his subjects. He has N subjects and he wants to study M of them today. According to Omar, every subject has an interest level, A_i which indicates how much Omar likes that subject. Unfortunately, Omar feels bored ea...
for t in xrange(input()): n,m = map( int, raw_input().split() ) arr = map( int, raw_input().split() ) a = [ [0 for j in xrange(n)] for i in xrange(m) ] if m == 1 : print 0 continue for j in xrange(n): a[0][j] = 0 for i in xrange(1,m): for j in xrange(i): a[i][j] = - (1L<<62) for j in xrange(i,n...
On Chocolate day, Chotu wants to give his girlfriend a box of chocolate. Chotu has a N X N square box and N^2 chocolates each having a distinct sweetness value between 1 and N^2. To make the box look attractive Chotu must fill each row with chocolates arranged in increasing value of sweetness. Chotu also knows that hi...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=input() while t>0: t-=1 n,k=map(int,raw_input().split()) if k==1: print n+((n*n*(n-1))/2) else: x=n+k-2 print (n*n*x+n*(k+1))/2
After the death of Meghnad and Kumbhakaran, Raavan got scared. He used his mind and presented a proposal of a war of numbers instead of Bow and arrows to Ram. According to him, Laxman will select a number N, Raavan has to subtract a number which is at least 1 and at most k. After that Ram has to subtract a number at l...
t=int(raw_input()) while t>0: s=raw_input() li=[] li=s.split() p=int(li[0]) k=int(li[1]) for i in range(1,p+1): res=(k+1)*i; print res, print "" t=t-1
You all might have heard about hamming distance in Information Theory. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. It measures the minimum number of errors that could have transformed one string into the other. Given two integer...
import sys t=input() while t>0: s=sys.stdin.readline().strip().split() s=map(int,s) a,b=s c=a^b print bin(c).count("1") t=t-1
Darth Vader, the lord of the dark side has created a Death-Star (it can destroy any star). You have to deactivate the Death-star. To deactivate the death-star one must find the unique most powerful Lightsaber. Lightsaber’s power is associated with a number. You ask for Lightsaber from your friendly Jedis(person). You...
from collections import Counter n=input() l=map(int,raw_input().split()) c=Counter(l) flag=[-1] for key in c: if(c[key]==1): flag.append(key) print max(flag)
Solve the Mystery. Note There is partial marking for this question. Input The first line of each test file contains a single integer T. Then T lines follow. Each line contains a string of lowercase characters Output For each test case output the answer in a new line. Constraints 1 ≤ T ≤50000 1 ≤ length of stri...
t=int(raw_input()) b=[] while t>0: x={} s=raw_input() for i in s: if i not in x: x[i]=1 else: x[i]+=1 b.append(max(x.values())) t-=1 for i in b: print i
Steve Jobs' ghost has come down to BITS Pilani Hyderabad Campus, since he has heard a lot about the coding culture here. Hoping to recruit talented people to work on top-secret Apple software, he keeps a strict coding test. Apple is currently working on a upgraded version of a automated form filler. They call it the i...
w=raw_input() n=input() l=list() for i in range(0,n): a=raw_input() l.append(a) le=0 s=-1 for j in range(0,n): if w==str(l[j]): s=j break if(str(l[j]).find(w,0,len(l[j]))==0): if(le==0): le=len(str(l[j])) s=j else: if(le>len(l[j])): le=len(l[j]); s=j if s==-1: print w else: print ...
Captain Jack loves tables. He wants to know whether you love tables or not. So he asks you to solve the following problem: Given an array A and element m, you have to find the value up to which table of m is present in the array. (example - if the array is 3 4 5 2 4 7 10 6 and value of m is 2 then answer is 6 because w...
n,m=map(int,raw_input().split()) lst=map(int,raw_input().split()) lst=set(lst) if m not in lst: print 0 else: i=2 while 1: if m*i in lst: i+=1 else: break print m*(i-1)
Chandu is a bad student. Once his teacher asked him to print the reverse of a given string. He took three hours to solve it. The teacher got agitated at Chandu and asked you the same question. Can you solve it? Input: The first line contains an integer T, denoting the number of test cases. Each test case contains a s...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' lst=[] no=int(raw_input()) for i in range(0,no): a=raw_input() a=a[::-1] lst.append(a) for word in lst: print word
A sequence of integers is called a wonderful sequence if all the integers in it are positive and it is a strictly increasing sequence. Given a sequence of integers, you have to make it a wonderful sequence. For that you can change any element you want, but you should make as less changes as possible in order to make i...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(raw_input()) while t>0: n = int(raw_input()) arr = [int(i) for i in raw_input().split()] count = 0 if arr[0]>arr[1]: arr[0]= arr[1]-1 count+=1 if arr[0]<0: arr[0] = 1...
Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S between 0 and K times (inclusive): * Choose a pair of integers i, j (1\leq i < j\leq |S|) such that the i-th and j-th characters of S are `0` and `1`, respectively. Re...
#include<bits/stdc++.h> #define ll long long using namespace std; const int p=998244353; int n,m,mx,i,j,k,l,val,ans,f[302][302][302],a[302],b[302],sum,sz; char s[10010]; int main(){ scanf("%s",s+1); scanf("%d",&mx); n=strlen(s+1); for(i=1;i<=n;i++){ if(s[i]=='1')sz++,sum++; else{ a[++m]=sz;sz=0; } } f...
Given is an integer N. Find the number of digits that N has in base K. Constraints * All values in input are integers. * 1 \leq N \leq 10^9 * 2 \leq K \leq 10 Input Input is given from Standard Input in the following format: N K Output Print the number of digits that N has in base K. Examples Input 11 2 O...
N,K=map(int,input().split()) x=0 while K**x<=N: x=x+1 print(x)
We have N locked treasure boxes, numbered 1 to N. A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times. Find the minimum cost required to unlock all the treasure boxes....
import java.util.*; import java.util.Map.Entry; class Main { static int mod = (int) (Math.pow(10,9)+7); static List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); ...
The development of algae in a pond is as follows. Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds: * x_{i+1} = rx_i - D You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order. Constraints * 2 ≤ r ≤ 5 * 1 ≤ D...
a,b,c=(int(i) for i in input().split()) for i in range(10): c=a*c-b print(c)
There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N. For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j. If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not. Find ...
#include<bits/stdc++.h> #define mod 1000000007 using namespace std; int n; long long a[55][55],A[55][55],tmp[55][55]; long long k; void copy(long long x[][55],long long y[][55]){ for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ x[i][j]=y[i][j]; } } } void mul(long long x[][55],long long y[][55],long long z[][55...
As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}. Snuke, an employee, would like to play with this sequence. Specifically, he would like to repeat the following operation as many times as possible: For every i satisfy...
n = int(raw_input()) input_list = map(int, raw_input().split()) total = 0 for num in input_list: partial = 0 while (num % 2 == 0): partial += 1 num /= 2 total += partial print(total)
As a token of his gratitude, Takahashi has decided to give his mother an integer sequence. The sequence A needs to satisfy the conditions below: * A consists of integers between X and Y (inclusive). * For each 1\leq i \leq |A|-1, A_{i+1} is a multiple of A_i and strictly greater than A_i. Find the maximum possible ...
#include<iostream> using namespace std;; int main(){ long long x,y; cin >> x>>y; long long count=0; while(x <=y){ count++; x= x*2; } cout <<count; return 0; }
Takahashi loves numbers divisible by 2. You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique. Here, the number of times an integer can be divisible by 2, is how many times the integer can...
#include <iostream> int N,x=2; int main() { for(std::cin>>N;x<=N;x*=2); std::cout<<x/2<<'\n'; }
Snuke loves flags. Snuke is placing N flags on a line. The i-th flag can be placed at either coordinate x_i or coordinate y_i. Snuke thinks that the flags look nicer when the smallest distance between two of them, d, is larger. Find the maximum possible value of d. Constraints * 2 ≤ N ≤ 10^{4} * 1 ≤ x_i, y_i ≤ 10^...
#include<iostream> #include<vector> #include<algorithm> #include<cstring> #include<cstdio> #include<cmath> #include<cstdlib> #include<ctime> #include<queue> #include<set> #include<map> #include<stack> #include<bitset> using namespace std; typedef long long LL; const int N=2e5,M=1e7; int gi() { int w=0;bool q=1;cha...
CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard. He intended to write `CODEFESTIVAL2016` on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length. So Mr. Takahashi decided to perform an operation that replaces a ce...
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S = sc.next(); int cnt = 0; String T = "CODEFESTIVAL2016"; for ( int i = 0; i < S.length(); i++ ) { if ( S.charAt(i) != T.charAt(i) ) cnt++; } System.out.println(cnt); } }
There are two rectangles whose bases are parallel to the x-axis. Read the lower left coordinates (xa1, ya1) and upper right coordinates (xa2, ya2) of rectangle A, the lower left coordinates (xb1, yb1) and upper right coordinates (xb2, yb2) of rectangle B, and rectangle A and B Create a program that outputs YES if there...
import java.io.*; import java.util.StringTokenizer; class Rectangle { double x[] = new double[2]; double y[] = new double[2]; Rectangle(double x1,double y1,double x2,double y2) { //左下:(x0,y0) 右上:(x1,y1) x[0] = x1; y[0] = y1; x[1] = x2; y[1] = y2; } boolean hasIntersection(Rectangle r) { if (this.x[0]<...
Taro is very good at 8 puzzles and always has his friends sort them out during breaks. At that time, my friend asked me, "Can you solve more complicated puzzles?", But I have never done other puzzles. Apparently the friend made 11 puzzles by himself. The puzzle has the following shape. <image> 11 The puzzle is done ...
#include <iostream> #include <sstream> #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <cstring> #include <climits> #include <algorithm> #include <map> #include <set> #include <stack> #include <vector> #include <queue> #include <bitset> #include <string> using namespace std; #define re...
Of the real numbers, those with a circular decimal part and those with a finite number of digits can be expressed as fractions. Given a real number that can be represented by a fraction, write a program that outputs an irreducible fraction equal to that real number (a fraction that cannot be reduced any further). ...
#include <bits/stdc++.h> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() #define fi first #define se second template<typename A, typename B> inline bool chmax(A &a, B b) { if (a<b) { a=b; return 1; } return 0; } template<typename A, typen...
Wall (Rampart) Historian Professor JOI is studying the once-existing Kingdom of IOI. According to past research, the IOI Kingdom was in the shape of a rectangle divided into squares with H rows and W columns. The capital of the IOI kingdom was walled for defense. The walls surrounding the capital of the IOI Kingdom ...
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <string> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <cassert> typedef long long ll; using namespace std; #define mod 100000...
The ICPC committee would like to have its meeting as soon as possible to address every little issue of the next contest. However, members of the committee are so busy maniacally developing (possibly useless) programs that it is very difficult to arrange their schedules for the meeting. So, in order to settle the meetin...
#include<bits/stdc++.h> using namespace std; int main(){ int N, Q, M, temp; while(1){ int temp2[300] = {}, ans = 0; cin>>N>>Q; if(N == 0 && Q == 0) break; for(int i = 1; i <= N; i++){ cin>>M; for(int j = 1; j <= M; j++){ cin>>temp; temp2[temp]++; } } for(int i = 1; i <= 250; i...
You are given two solid polygons and their positions on the xy-plane. You can move one of the two along the x-axis (they can overlap during the move). You cannot move it in other directions. The goal is to place them as compactly as possible, subject to the following condition: the distance between any point in one pol...
#include <stdio.h> #include <math.h> #include <iostream> #include <complex> #include <vector> #include <algorithm> using namespace std; #define rep(i, n) for(int i=0; i<(int)(n); i++) #define INF (1e100) #define EPS (1e-5) typedef complex<double> P; inline double sq(double a) { return a*a; } inline double cross(const ...
Ranks A finite field F2 consists of two elements: 0 and 1. Addition and multiplication on F2 are those on integers modulo two, as defined below. | + | 0 | 1 ---|---|--- 0| 0| 1 1| 1| 0 | | $\times$ | 0 | 1 ---|---|--- 0| 0| 0 1| 0| 1 A set of vectors $v_1, ... , v_k$ over F2 with the same dimension is said to be ...
#include <bits/stdc++.h> using namespace std; #define rep(i, N) for (int i = 0; i < (N); i++) #define all(a) (a).begin(), (a).end() #define pb push_back using ll = long long; using i_i = tuple<int, int>; using B = bitset<1000>; tuple<B, B> f(vector<B> a, vector<B> b, vector<int> msb, B x) { int N = a.size(); ...
Equivalent Deformation Two triangles T1 and T2 with the same area are on a plane. Your task is to perform the following operation to T1 several times so that it is exactly superposed on T2. Here, vertices of T1 can be on any of the vertices of T2. Compute the minimum number of operations required to superpose T1 on T2...
#include<bits/stdc++.h> using namespace std; using P = pair<double, double>; const double eps = 1e-6; bool equal(P a, P b) { return max(abs(a.first - b.first), abs(a.second - b.second)) < eps; } bool tan_equal(P a1, P a2, P b1, P b2) { return abs((a2.first - a1.first) * (b2.second - b1.second) - (b2.first - ...
“Hey, what’s up? It’s already 30 minutes past eleven!” “I’m so sorry, but actually I got lost. I have no idea where I am now at all and I got tired wandering around. Please help!” - Today you came to the metropolis to play with your friend. But she didn’t show up at the appointed time. What happened to her? After som...
#include <cstdio> #include <cmath> #include <cstring> #include <cstdlib> #include <climits> #include <ctime> #include <queue> #include <stack> #include <algorithm> #include <list> #include <vector> #include <set> #include <map> #include <iostream> #include <deque> #include <complex> #include <string> #include <iomanip>...
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to improve reflexes and memory by performing whac-a-mole many times. I want to hit the moles that come out one after another and get as many points as possible. The p...
#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 HUGE_NUM 10000000000 #define NUM 6050 typedef pair<ll,ll> P; struct Edge{ Edge(int arg_...
It was the last day of the summer camp you strayed into the labyrinth on the way to Komaba Campus, the University of Tokyo. The contest has just begun. Your teammates must impatiently wait for you. So you have to escape from this labyrinth as soon as possible. The labyrinth is represented by a grid map. Initially, each...
#include<iostream> #include<queue> using namespace std; int H,W,S; string s[50],t[10][50]; int dp[2][50][50][1<<10]; int d[5]={0,1,0,-1,0}; int main() { cin>>W>>H; queue<pair<pair<int,int>,pair<int,int> > >Q; for(int i=0;i<H;i++) { cin>>s[i]; for(int j=0;j<W;j++) { if(s[i][j]=='%') { Q.push(make_pai...
There are N towers in the town where Ikta lives. Each tower is given a different number from 0 to N-1, and the tower with number i is called tower i. Curious Ikta was interested in the height of the N towers and decided to make a table T showing the magnitude relationship between them. T has N × N elements, and each el...
#include <bits/stdc++.h> using namespace std; using ll = long long; constexpr ll M = 1e9 + 7; ll dp2[256][256][256]; int sz[256]; int dfs(int v, vector<vector<int>>& g, vector<vector<ll>>& dp) { if(g[v].size() == 0) { dp[v][1] = 1; return sz[v] = 1; } int sum = 1; for(auto ch : g[v])...
D: Myampus Sequence-Myampus Sequence- story Myanpasuu. I'm a first grader who goes to a school annex in the country. Well, today's class was programming. Everyone was having a hard time, but Matsun's Nini was typing with great momentum. As expected, it's Nakasan. Nini, the program was completed and I went somewhere...
#include<bits/stdc++.h> using namespace std; int N,M; int X[101]; int A[101],B[101],C[101]; int dp[111][111][11]; int solve(int l,int r,int x){ if( dp[l][r][x] != -1 ) return dp[l][r][x]; if( l == r && A[x] == X[l] ) return dp[l][r][x] = 1; for(int i=l;i<=r-1;i++){ if( solve(l,i,B[x]) == 1 && solve(i+1,r,C[...
problem $ M $ students will be tested in a classroom with $ N $ seats in a straight line. Seats are numbered $ 1 \ dots N $ from the front, and $ 1 $ per seat can seat $ 1 $ students. Now each student is sitting in the $ A_1, \ dots, A_M $ seats. To start the test, the following conditions must be met: * $ 1 \ dots...
#include <bits/stdc++.h> using namespace std; int n, m, cnt = 0; bool a[1005] = {0}; int main() { int i, x; cin >> n >> m; for(i = 0; i < m; ++i) { cin >> x; --x; a[x] = 1; } for(i = 0; i < m; ++i) if(!a[i]) ++cnt; cout << cnt << endl; return 0; }
Problem Given an undirected graph of $ N $ vertices $ M $ edges. Each vertex has a different number from $ 1 $ to $ N $. You want to start at vertex $ S $ at time $ 0 $ and move to vertex $ G $. Parameters $ a and b $ are set on each side, and if the time $ t $ starts from the vertex on one side of that side, the time...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; #define REP(i,n) for(int i=0;i<(int)(n);i++) #define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define FORR(i,a,b) for(int i=(int)(b)-1;i>=(int)(a);i--) #define CHMIN(a,b) (a)=min((a),(b)) #def...
Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue. Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to sat...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { new BinSearchTree1().run(); } } class BinSearchTree1 { Node root; public void run() { root = null; try (BufferedReader br = new BufferedReader(new In...
Print all combinations which can be made by $k$ different elements from $0, 1, ..., n-1$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a combination is calculated by bitwise OR of the selected elements. Constraints *...
from itertools import combinations n, k = map(int, input().split()) a = [i for i in range(n)] rs = [] for c in combinations(a, k): tmp = sum(1 << i for i in c) rs.append([tmp, *c]) for ans in sorted(rs): print(str(ans[0]) + ":", *ans[1:])
Given a sequence of natural numbers . Find it's N'th term. a1=3, a2=9, a3=30, a4=101, a5=358, a6=1443... ...,aN Input Single line containing a natural number N Output Print N'th term of the sequence modulo 10^9+7. Constraints 1 <= N <=100 Example Input: 5 Output: 358
import math n=input() s=math.factorial(n)+3**n-n print (s%(10**9+7))
These days a lot of new coders are emerging at RJIT. One of the many programmers in RJIT thought of making a program to find the weekday for any given date. He successfully builds it but there is one problem, his program prints the day of yesterday's date. Now he wonders whether he can find the next date given him the...
NonLeap_Months=[31,28,31,30,31,30,31,31,30,31,30,31] Leap_Months=[31,29,31,30,31,30,31,31,30,31,30,31] def is_leap(year): if(year%400==0): return 1 elif(year%100==0): return 0 elif(year%4==0): return 1 else: return 0 T=raw_input().strip('\n') T=int(T) for _ in xrange(T): Date=raw_i...
Throughout history there have been many different interesting numbers or types of numbers. One of these types is amicable numbers. Amicable numbers are a pair of numbers with the following property: the sum of all of the proper divisors of the first number (not including itself) exactly equals the second number while t...
import math def sumof(n): sq,su=int(math.sqrt(n)),0 for i in xrange (2,sq+1): if n%i==0: su+=i+((n/i) if i*i!=n else 0) else: continue return su+1 t=int(raw_input()) for i in xrange(t): n=int(raw_input()) s1=sumof(n) s2=sumof(s1) if s2==n: print 'Yes, amicable with %d' %s1 else: print 'No'
Vidhi went to a magic show last week where she was astounded by a magic trick performed by the great Mandwarf, the brown. His trick was as follows : Ask a volunteer from the audience to write down a list L of N integers. Ask another volunteer from the audience to provide three integers A, B, C A...
#!/usr/bin/env python # coding=utf-8 T = input() for _ in xrange(T): N = input() L = map(int, raw_input().split()) A, B, C = map(int, raw_input().split()) s = raw_input() revcnt = 0 slope = 1 D = 0 offset = 0 for i in xrange(N): if s[i] == 'R': revcnt = 1 - revcn...
You are given an array A of N integers. You are to fulfill M queries. Each query has one of the following three types: C d : Rotate the array A clockwise by d units. A d : Rotate the array A anticlockwise by d units. R d : Query for the value of the element, currently being the d-th in the array A. Input The first l...
n,m=map(int,raw_input().split()) a=map(int,raw_input().split()) r=0 for q in range(m): z,x=raw_input().split() x=int(x) if (z=='R'): print a[(x-1+r)%n] elif (z=='A'): r=(r-x) else: r=(r+x)
As you might remember, the collector of Siruseri had ordered a complete revision of the Voters List. He knew that constructing the list of voters is a difficult task, prone to errors. Some voters may have been away on vacation, others may have moved during the enrollment and so on. To be as accurate as possible, he e...
from sys import stdin,stdout def write(s): stdout.write(str(s)) stdout.write('\n') n1,n2,n3 = map(int,stdin.readline().split()) l1 = [] l2 = [] l3 = [] l = set() for _ in xrange(n1): l1.append(int(stdin.readline())) for _ in xrange(n2): l2.append(int(stdin.readline())) for _ in xrange(n3): l3.append(int(stdin.rea...
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they f...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 5; const long long mod = 1e9 + 7; long long p[maxn], bit[maxn], tol; struct node1 { long long l, r; } c[maxn]; bool cmp(node1 a, node1 b) { if (a.r != b.r) return a.r < b.r; return a.l < b.l; } long long sum(long long i) { long long s = 0; w...
You are given an undirected tree, consisting of n vertices. The vertex is called a leaf if it has exactly one vertex adjacent to it. The distance between some pair of vertices is the number of edges in the shortest path between them. Let's call some set of leaves beautiful if the maximum distance between any pair of...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast,unroll-loops") using namespace std; const int N = 1e6 + 2; vector<int> adj[N]; int k, ans = 1; int dfs(int u, int pai = -1) { bool leaf = true; vector<int> deps; for (int v : adj[u]) { if (v == pai) continue; int depth = dfs(v, u) + 1; deps.push_bac...
Consider some set of distinct characters A and some string S, consisting of exactly n characters, where each character is present in A. You are given an array of m integers b (b_1 < b_2 < ... < b_m). You are allowed to perform the following move on the string S: 1. Choose some valid i and set k = b_i; 2. Take ...
M=(119<<23)+1 n,m,a =[int(x)for x in raw_input().split()] b=[0]+[int(x)for x in raw_input().split()] r=pow(a,n-2*b[-1],M) for i in xrange(1,m+1): d=b[i]-b[i-1] r=r*((pow(a,2*d,M)+pow(a,d,M))%M*((M + 1)/2)%M)%M print r
You're given an array a of length n. You can perform the following operations on it: * choose an index i (1 ≤ i ≤ n), an integer x (0 ≤ x ≤ 10^6), and replace a_j with a_j+x for all (1 ≤ j ≤ i), which means add x to all the elements in the prefix ending at i. * choose an index i (1 ≤ i ≤ n), an integer x (1 ≤ x ≤...
#include <bits/stdc++.h> using namespace std; long long n; long long a[10002]; int32_t main() { cin >> n; cout << n + 1 << '\n'; for (long long i = 1; i <= n; i++) { cin >> a[i]; a[i] += 10 * n + 1; } cout << 1 << " " << n << " " << 10 * n + 1 << '\n'; for (long long i = 1; i <= n; i++) { cout <...
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons ...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); vector<long long> tmp; int n, k; cin >> n >> k; long long mas[n], ans = 0; for (int i = 0; i < (int)(n); ++i) cin >> mas[i]; vector<pair<long long, long long> > ext; string s; cin >> s; for (int i =...
Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task. Two matrices A and B are given, each of them has size n × m. Nastya can perform the following operation to matrix A unlimited number of times: * take any square square submatrix of A and...
import os from io import BytesIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline from collections import defaultdict def main(): n, m = map(int, input().split()) s1 = [defaultdict(int) for _ in range(n + m)] s2 = [defaultdict(int) for _ in range(n + m)] for s in (s1, s2): for i in r...
You are given an array a consisting of n integers a_1, a_2, ..., a_n. Your problem is to find such pair of indices i, j (1 ≤ i < j ≤ n) that lcm(a_i, a_j) is minimum possible. lcm(x, y) is the least common multiple of x and y (minimum positive number such that both x and y are divisors of this number). Input The fi...
#include <bits/stdc++.h> using namespace std; const int N = 10000001; int num[N], n; long long ans = LLONG_MAX; int t1, t2; int main() { ios::sync_with_stdio(false); cin >> n; int tmp; for (int i = 1; i <= n; i++) { cin >> tmp; if (num[tmp] && tmp < ans) { ans = tmp; t1 = num[tmp]; t2 ...
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to choose at most ⌊n/2⌋ vertices in this graph so each unchosen vertex is adjacent (in other words, connected by an edge) to at l...
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int n, m; vector<int> d; vector<vector<int>> g; void bfs(int s) { d = vector<int>(n, INF); d[s] = 0; queue<int> q; q.push(s); while (!q.empty()) { int v = q.front(); q.pop(); for (auto to : g[v]) { if (d[to] == INF) { ...
This problem differs from the next one only in the presence of the constraint on the equal length of all numbers a_1, a_2, ..., a_n. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too. A team of SIS students is going to make a trip on a submarine....
n = int(input().strip()) arr = input().strip().split() digs = [] l = len(str(arr[0])) ans = 0 m = 1 for i in range(l-1, -1, -1): total = 0 for j in range(n): total += int(arr[j][i]) ans += total*n*m + total*n*(m*10) m *= 100 print(ans%998244353)
You are given a string s consisting only of first 20 lowercase Latin letters ('a', 'b', ..., 't'). Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top". You can perform the followin...
#include <bits/stdc++.h> constexpr int ABC = 20; int mask_length(int mask) { int res = 0; while (mask) { mask &= mask - 1; ++res; } return res; } int main() { std::string s; std::cin >> s; int n = s.length(); std::vector<bool> seen(1 << ABC); seen[0] = true; std::vector<int> dp(1 << ABC); ...
The mayor of the Central Town wants to modernize Central Street, represented in this problem by the (Ox) axis. On this street, there are n antennas, numbered from 1 to n. The i-th antenna lies on the position x_i and has an initial scope of s_i: it covers all integer positions inside the interval [x_i - s_i; x_i + s_i...
#include <bits/stdc++.h> using namespace std; mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count()); const int MOD = 1e9 + 7, MAX = INT_MAX / 100; const long long INF = 1e18; const long double PI = 4 * atan((long double)1); int dp1[1000005], dp2[1000005], mindp[1000005]; int n, m; int s[1000005], x[1000...
Polycarp has n different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100". Polycarp wants to offer his set of n binary words to play a game "words". In this game, players name words and each next word (starting from the ...
import java.io.*; import java.util.*; public class A { static String rev(char[] a) { StringBuilder sb = new StringBuilder(); for (int i = a.length - 1; i >= 0; i--) sb.append(a[i]); return sb.toString(); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWr...
There are n cities in Treeland connected with n - 1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios. I...
#include <bits/stdc++.h> using namespace std; struct node { int t, next; } a[400010]; vector<int> v[200010]; pair<int, int> h[200010]; int num[200010]; int fa[200010][20], dep[200010]; int head[200010], dfn[200010], c[400010], n, m, cl, cnt, tot; inline int rd() { int x = 0; char ch = getchar(); for (; ch < '0'...
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one ...
import java.util.Scanner; public class CF { public static void main(String[] args) { Scanner scan = new Scanner(System.in); char[] in = scan.nextLine().toCharArray(); int from = 0; for (int i = 0; i < in.length; i++) { char c = in[i]; String bin = String.format("%08d", Integer.parseInt(Integer.toBina...
James Bond, Johnny's favorite secret agent, has a new mission. There are n enemy bases, each of them is described by its coordinates so that we can think about them as points in the Cartesian plane. The bases can communicate with each other, sending a signal, which is the ray directed from the chosen point to the ori...
#include <bits/stdc++.h> using namespace std; int n, k; priority_queue<double> q; struct Node { int x, y; double z; bool operator<(const Node &rhs) const { if (x != rhs.x) return x < rhs.x; if (y != rhs.y) return y < rhs.y; return z < rhs.z; } } a[1000010]; int gcd(int a, int b) { return b ? gcd(b, ...
After being discouraged by 13 time-limit-exceeded verdicts on an ugly geometry problem, you decided to take a relaxing break for arts and crafts. There is a piece of paper in the shape of a simple polygon with n vertices. The polygon may be non-convex, but we all know that proper origami paper has the property that an...
#include <bits/stdc++.h> using std::cin; using std::cout; const double eps = 1e-10; const int N = 200054; struct vec2 { double x, y; vec2(double x0 = 0.0, double y0 = 0.0) : x(x0), y(y0) {} inline friend std::istream &operator>>(std::istream &in, vec2 &B) { return in >> B.x >> B.y; } inline double operato...
You are given an array a of length 2^n. You should process q queries on it. Each query has one of the following 4 types: 1. Replace(x, k) — change a_x to k; 2. Reverse(k) — reverse each subarray [(i-1) ⋅ 2^k+1, i ⋅ 2^k] for all i (i ≥ 1); 3. Swap(k) — swap subarrays [(2i-2) ⋅ 2^k+1, (2i-1) ⋅ 2^k] and [(2i-1) ...
from sys import stdin REPLACE_ID = 1 REVERSE_ID = 2 SWAP_ID = 3 SUM_ID = 4 def main(): n, q = _read_ints() a = tuple(_read_ints()) requests = tuple(_read_ints() for _ in range(q)) for result in compute_requests_results(a, requests): print(result) def _read_ints(): return map(int, stdin...
While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book. After taking a deeper look into the contents of these pages, linguists t...
import os import sys from io import BytesIO, IOBase # region fastio 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.wri...
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved. You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the...
#include <bits/stdc++.h> using namespace std; vector<string> vec_splitter(string s) { for (char& c : s) c = c == ',' ? ' ' : c; stringstream ss; ss << s; vector<string> res; for (string z; ss >> z; res.push_back(z)) ; return res; } void debug_out(vector<string> args, int idx) { cerr << endl; } template ...
Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold: * All passages between two houses will be closed, if there are...
""" Python 3 compatibility tools. """ from __future__ import division, print_function import itertools import sys import os from io import BytesIO from atexit import register if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertool...
It is the hard version of the problem. The only difference is that in this version 3 ≤ k ≤ n. You are given a positive integer n. Find k positive integers a_1, a_2, …, a_k, such that: * a_1 + a_2 + … + a_k = n * LCM(a_1, a_2, …, a_k) ≤ n/2 Here LCM is the [least common multiple](https://en.wikipedia.org/wiki...
import java.io.*; import java.lang.*; import java.util.*; public class KLCMEASY { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0) { int n=s.nextInt(); int k=s.nextInt(); for(int i=0;i<k-3;i++) { Syst...
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numb...
#include <bits/stdc++.h> typedef struct { char m_Name[21]; int m_taxi, m_pizza, m_girl; } Preson_t; Preson_t P[100]; int main() { int N, M, a, b, c, Taxi, Pizza, Girl, i; char flag; scanf("%d", &N); for (i = 0; i < N; ++i) { scanf("%d %s", &M, P[i].m_Name); while (M--) { scanf("%d-%d-%d", &a, ...
A string s of length n (1 ≤ n ≤ 26) is called alphabetical if it can be obtained using the following algorithm: * first, write an empty string to s (i.e. perform the assignment s := ""); * then perform the next step n times; * at the i-th step take i-th lowercase letter of the Latin alphabet and write it eithe...
for _ in range(input()): s=raw_input() mx='a' for i in s: mx=max(mx,i) flag=1 start=0 end=len(s)-1 cur=mx while end>=start: if s[start]==cur: start+=1 elif s[end]==cur: end-=1 else: flag=0 break cur=c...
Life is not easy for the perfectly common variable named Vasya. Wherever it goes, it is either assigned a value, or simply ignored, or is being used! Vasya's life goes in states of a program. In each state, Vasya can either be used (for example, to calculate the value of another variable), or be assigned a value, or i...
#include <bits/stdc++.h> using namespace std; const long long int M = 5e5 + 5, LG = 17, inf = 1e18; int n, m; long long int f[M]; vector<long long int> g[M], h[M]; long long int c2[M]; long long int c1[M]; void dfs1(long long int x) { if (c1[x] == 1) return; c1[x] = 1; for (long long int y : g[x]) { dfs1(y); ...
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have ...
#include <bits/stdc++.h> using namespace std; inline int inn() { int x, ch; while ((ch = getchar()) < '0' || ch > '9') ; x = ch ^ '0'; while ((ch = getchar()) >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ '0'); return x; } inline int show(int len, char c) { for (int i = 1; i <= len; i++) prin...
The Bytelandian Institute for Biological Research (BIBR) is investigating the properties of two species of bacteria, named simply 0 and 1. Even under a microscope, bacteria of those two species are very difficult to distinguish. In fact, the only thing the scientists possess that is able to differentiate between them i...
#include <bits/stdc++.h> using namespace std; static const int INF = 500000000; template <class T> void debug(T a, T b) { for (; a != b; ++a) cerr << *a << ' '; cerr << endl; } int n, len; char s[1000005]; int var[1000005][4]; int cnt, ind; int parse() { if (s[ind] == '0') var[cnt][0] = 1; if (s[ind] == '1') va...
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want...
n = int(input()) segments = [] minl = 10**9 maxr = 1 for i in range(n): a, b = map(int, input().split()) segments.append((a, b)) if a<minl: minl = a if b>maxr: maxr = b if (minl, maxr) in segments: print(segments.index((minl, maxr))+1) else: print(-1)
Berland traffic is very different from traffic in other countries. The capital of Berland consists of n junctions and m roads. Each road connects a pair of junctions. There can be multiple roads between a pair of junctions. For each road we know its capacity: value ci is the maximum number of cars that can drive along ...
#include <bits/stdc++.h> using namespace std; const int N = 1e2 + 5, E = 5e3 + 5; const double eps = 1e-9; int link[N][N], X[E], Y[E], W[E]; int dad[N], n, m; int M[N][N]; double S[N][N]; int find(int u) { return u == dad[u] ? u : dad[u] = find(dad[u]); } void merge(int x, int y) { int fx = find(x), fy = find(y); i...
HAI I HAS A TUX GIMMEH TUX I HAS A FOO ITS 0 I HAS A BAR ITS 0 I HAS A BAZ ITS 0 I HAS A QUZ ITS 1 TUX IS NOW A NUMBR IM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0 I HAS A PUR GIMMEH PUR PUR IS NOW A NUMBR FOO R SUM OF FOO AN PUR ...
#include <bits/stdc++.h> using namespace std; int main() { int tux; cin >> tux; int foo = 0, bar = 0, baz = 0, quz = 1; while (tux-- != 0) { int pur; cin >> pur; foo += pur; bar++; if (max(foo * quz, bar * baz) == foo * quz) { baz = foo; quz = bar; } } cout << (float)baz ...
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another. (Cultural note: standing in huge and disorganized queues for hours is a native ...
#include <bits/stdc++.h> using namespace std; int f[1024], w[1024], front[1024], cntw, n, x; bool g[1024]; int getfa(int x) { if (!f[x]) return x; f[x] = getfa(f[x]); return f[x]; } int main() { cin >> n >> x; for (int i = 1; i <= n; ++i) { int y; scanf("%d", &y); front[i] = y; if (!y) continu...
Manao is solving a problem with the following statement: <image> He came up with a solution that produces the correct answers but is too slow. You are given the pseudocode of his solution, where the function getAnswer calculates the answer to the problem: getAnswer(a[1..n], b[1..len], h) ...
#include <bits/stdc++.h> using namespace std; const int INF = 2147483647; const long long LLINF = 9223372036854775807LL; const int cinf = 1000000010; const int maxn = 150010; int tmin[maxn * 4]; int tcnt[maxn * 4]; int tadd[maxn * 4]; void push(int v, int L, int R) { tmin[v] += tadd[v]; if (L != R) { tadd[v + v...
Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n. Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers ...
import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; imp...