input
stringlengths
29
13k
output
stringlengths
9
73.4k
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (the...
#include <bits/stdc++.h> using namespace std; const int N = 100005; vector<pair<int, int> > adj[N]; int ass[N]; int ans = 500000004; void dfs(int s, int as) { if (ass[s]) { if (ass[s] != as) ans = 0; return; } ass[s] = as; for (auto it : adj[s]) { if (it.second == 1) dfs(it.first, as); els...
Chris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece — "A Road to the Sun". The building stands on cubical stones of the same size. The foundation divides the entire "road" into cells, into which the cubical stone...
#include <bits/stdc++.h> long long k, n, m, i, ans, j, d, a[100009], b[100009], c[100009]; int main() { scanf("%I64d%I64d%I64d", &n, &m, &k); for (i = 0; i < m; i++) scanf("%I64d%I64d%I64d", &a[i], &b[i], &c[i]); for (i = 0; i < k; i++) { scanf("%I64d", &d); for (j = 0; j < m; j++) if (a[j] <= d && ...
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
#created by Кама Пуля n,m=map(int,input().split()) L=[[] for i in range(n+1)] for i in range(m) : a,b=map(int,input().split()) L[a].append(b) L[b].append(a) if n not in L[1] : l=[1] D=[-1 for i in range(n+1)] D[1]=0 while len(l)>=1 : t=l[0] del(l[0]) for x in L[t] : ...
A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. n friends came by, and after a typical party they decided to play blind man's buff. The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several ro...
#include <bits/stdc++.h> using namespace std; const int N = 110; double p[N]; int n; struct P { long double qk; int id; inline P(long double qk = 0.0, int id = 0) : qk(qk), id(id) {} inline long double calc() const { return (1 - qk * (1 - p[id])) / (1 - qk); } inline bool operator<(const P& o) const { return ...
In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied. ...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; public class DynamicProgramming { public static void main(String[] args) throws IOException { File file = new File("in"); BufferedReader in = new BufferedReader(file.exists(...
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to...
s='#' for i in range(1,1001): x=i s0="" while x>0: s0=s0+str(x%10) x=x/10 length=len(s0) for j in range(0,length): s=s+s0[length-j-1] #print s x=input() print s[x]
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two...
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int q = sc.nextInt(); Map<Long, HashMap<Long, Long>> map = new HashMap<Long, HashMap<Long, Long>>(); for(int i=0;i<q;i++){ int type = s...
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after th...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class CTask { public static void main(String[] args) throws IOException { MyInputReader in = new MyInputReader(System...
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so ...
I=lambda: map(int,input().split()) x,y,z,k=I() a1,a2,a3,q=0,0,0,0 while q<3: q=0 if a1+a2+a3==k: break if a1<x-1: a1+=1 if a1+a2+a3==k: break else: q+=1 if a2<y-1: a2+=1 if a1+a2+a3==k: break else: q+=1 if a3<z-1: a3+=1 if a1+a2...
In the lattice points of the coordinate line there are n radio stations, the i-th of which is described by three integers: * xi — the coordinate of the i-th station on the line, * ri — the broadcasting range of the i-th station, * fi — the broadcasting frequency of the i-th station. We will say that two ra...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; vector<int> v[N]; int n, k, b[N], rot[N], tot; long long ans; int lson[N * 20], rson[N * 20], s[N * 20]; struct node { int xi, ri, fi; } a[N]; bool cmp(node A, node B) { return A.ri > B.ri; } int lp(int x) { return lower_bound(b + 1, b + 1 + n, x) ...
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the oth...
#include <bits/stdc++.h> using namespace std; void c_p_c() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); } long long dp[7000][2]; long long cnt[7000][2]; vector<long long> moves[2]; void dfs(long long i, long long j, long long n) { if (dp[i][j] == 0) { for (long long ele : moves[1 ^ j]) { l...
In the country of Never, there are n cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as <image> roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered ...
#include <bits/stdc++.h> using namespace std; bool was[2010]; long long n, ans, minEdge = 1e9; long long toPer[2010], a[2010][2010]; signed main() { ios_base::sync_with_stdio(0); cout.tie(0); cin.tie(0); cin >> n; for (long long i = 1; i <= n; ++i) { for (long long j = 1; j <= n - i; ++j) { cin >> a...
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends. Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players tak...
import java.util.Scanner; public class R425P1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(), k = scan.nextLong(); if((n/k)%2==0) System.out.println("NO"); else System.out.println("YES"); } }
The citizens of BubbleLand are celebrating their 10th anniversary so they decided to organize a big music festival. Bob got a task to invite N famous singers who would sing on the fest. He was too busy placing stages for their performances that he totally forgot to write the invitation e-mails on time, and unfortunatel...
#include <bits/stdc++.h> using namespace std; const int maxn = 201, maxm = 51; const long long INF = 0x3f3f3f3f3f3f3f3fLL; int n, m, qtot, etot; struct Point { int x, y; void read() { scanf("%d%d", &x, &y); } bool operator<(Point const& t) const { return x < t.x || (x == t.x && y < t.y); } Point operator-...
Slava plays his favorite game "Peace Lightning". Now he is flying a bomber on a very specific map. Formally, map is a checkered field of size 1 × n, the cells of which are numbered from 1 to n, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies ...
#include <bits/stdc++.h> using namespace std; int n; int main() { ios_base::sync_with_stdio(0); cin >> n; vector<int> ans; if (n == 1) { cout << "2\n1 1"; return 0; } for (int i = 2; i <= n; i += 2) ans.push_back(i); for (int i = 1; i <= n; i += 2) ans.push_back(i); for (int i = 2; i <= n; i += ...
Count the number of distinct sequences a1, a2, ..., an (1 ≤ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and <image>. As this number could be large, print the answer modulo 109 + 7. gcd here means the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Input Th...
#include <bits/stdc++.h> using namespace std; const long long maxn = 1e6 + 500; const long long mod = 1e9 + 7; const long long inf = 1e9 + 500; long long dp[maxn]; int alii = 0; long long poww(long long a, long long b) { long long ans = 1; alii++; while (b > 0) { alii++; if (b & 1) { alii++; a...
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden. Each day, every pile w...
#include <bits/stdc++.h> using namespace std; long long n, x; multiset<long long> sets; vector<long long> v(200200); long long ans = 0; signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (long long i = 1; i <= n; i++) cin >> v[i]; long long sum = 0; for (long long i = 1; i...
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that i...
#include <bits/stdc++.h> using namespace std; const int N = 1e5; int main() { long long int n, q; cin >> n >> q; while (q--) { long long int x; cin >> x; long long int ans; int flag = 1; for (int i = 64; i >= 1; i--) { long long int temp = pow(2, i); long long int r1 = (x - 2 * n +...
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n. There are three values about each exam: * s_i — the day, when questions for the i-th exam will be published, * d_i — t...
#include <bits/stdc++.h> using namespace std; long long int INF = 1e9 + 5; long long int mod = 998244353; int main() { long long int m, n, i, j; cin >> n >> m; vector<long long int> days(m + 1, 0), ans(n + 1, 0); vector<set<pair<long long int, long long int>>> tasks(n + 1); long long int x, y, c; for (i = 1...
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k. Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic...
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); int x = 0; for (int i = 0; i < n; i++) { if (arr[i] <= k) ...
Naruto is a fan of numbers, he likes to play with them. This time he decided to multiply numbers and produce output. After every k elements he decides to find x^m, where x is the multiplication till k elements and m is a random number that naruto takes. Help naruto find the output. As answer could be large, help him,...
def power1(x,n,MOD): if(n==0): return 1 ret=1 while(n): if(n&1): ret*=x ret%=MOD x*=x x%=MOD n>>=1 return ret T=input() while(T): T-=1 N,K,M,W=map(int,raw_input().split()) L=map(int,raw_input().split()) prod=1 for x in xrange(N): prod=prod*L[x]%W if((x+1)%K==0): prod=power1(prod...
Our Earth is so beautiful due to the various amazing colours it contains. Now on Earth day we invited Species from Mars (called Martian) Planet to celebrate it with us and to let them know our Earth. Martians got so much attracted with the beauty of our Earth and invited people of Earth to visit their Planet Mars. Bu...
for t in range(input()): colors=map(int,raw_input().split()) martian=[] for color in colors: martian.append(hex(color)[2:].upper()) result=[] for mc in martian: current_clr="" if len(mc)<2: current_clr+='0' for letter in mc: if ord(letter)>=ord('A'): current_clr+=chr(ord(letter)+20) else: ...
As a programmer, you sometimes have to deal with some math and this is the time to do it. You are given a list of binary relations, equalities and inequalities, like a = b, a != d, b = c etc. Your task is to output YES if you can assign integers to input variables in such a way, that you can satisfy all equalities and ...
from sys import setrecursionlimit from collections import defaultdict, deque def dfs(elem, visited, Graph): cola = deque(Graph[elem]) while cola: elem = cola.pop() if visited[elem - 1]: continue visited[elem - 1] = True cola += Graph[elem] def solve(): unequal = [] positions = {} Graph = defaultdict(...
After Joeffrey chocked to death, Cercei blamed Tyrian for his death. After seeing his love, Shae betrayed him, he demanded trial by combat. Now this combat is not with swords but with logic and problem solving. Tywin will ask Tyrian questions and he have to answer them correctly. Tywin asks him this question: There are...
t = int(raw_input()) while t!= 0 : t-=1 n,h = map(int,raw_input().split()) seq = map(int,raw_input().split()) final = list() preseq = list() x = len(seq) for i in range(h) : final = [0] * x if seq[1] == 1 : final[0] = 1 if seq[x-2] == 1 : final[x-1] = 1 for j in range(1,x-1) : if seq[j-1] == 1 ...
One day alice and bob were playing with their old toys , they had moved all the rakes and drawers to in the pursuit of their childhood toys. Finally they found bunch of cubes ,with letters and digits written on it ,which they recalled they used to make words from. They have already come up with a word they would li...
a,b=map(str,raw_input().split()) fnd=[] f=0 for i in range(int(b)): l=list(map(str,raw_input().split())) for i in range(len(a)): if i not in fnd: if a[i] in l: fnd.append(i) break if len(fnd)==len(a): f=1 break if(f): print 'YES' else: ...
Seeing the fame received by the Fibonacci numbers, the other Natural Numbers were feeling jealous. Therefore, to give them their shot at glory Mr. Non-Fibo now wants you to tell him the N^th- Non Fibonacci Number. Input: First line contains T which is the number of test cases. T lines follow each with an integer N. O...
''' # 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 = int(raw_input()) while T>0: T-=1 N = int(raw_input()) a = 1 b = 1 while N>0: c = a + b N -= c-b-1 a = b b = c print c+N-1
Quantum love solving mathematical problems. One day his teacher give him problem on divisibility to check his mathematical skills. He give him four numbers a,b,c,d and asked him to check whether (a^b) is divisible by (c^d) or not. As the constrains are high, so quantum need your help to answer the query. INPUT First ...
P=[1]*100001 p=[] for i in range(2,100001): if P[i]: p.append(i) for j in range(i<<1,100001,i): P[j]=0 for t in range(input()): a,b,c,d=map(int,raw_input().split()) ap=[] ae=[] cp=[] ce=[] if d==0: print "Divisible" continue for x in p: if a%x==0: cnt=0 while a%x==0: a/=x cnt+=1 ...
Shil is your new boss and he likes palindromes very much. Palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. (ex. madam , aabaa, racecar) Given a string S , beautiful Palindrome is a lexicographical minimum palindrome that can be form...
s = raw_input() alphabet = [chr(i + ord('a')) for i in xrange(26)] f = dict(zip(alphabet, [0]*26)) for c in s: f[c] += 1 output = '' for c in alphabet: while f[c] > 1: output += c f[c] -= 2 mid = [] for k, v in f.iteritems(): if v == 1: mid.append(k) if len(mid) > 1: print -1 else: ...
Given a word consisting of lowercase English letters, write a program to remove duplicates from the word. The characters in the output must preserve the same order, as their first appearance in the original word. Input Format The input consists of several test cases. The first line of the input file contains a positi...
t=input() for x in range(t): s=raw_input() str='' for i in s: if i not in str: str+=i print str
Ram was busy calclutaing the factorials of some numbers. He saw a pattern in the number of zeros in the end of the factorial. Let n be the number and Z(n) be the number of zeros in the end of the factorial of n then for x < y Z (x) ≤ Z(y) i.e. the function never decreases. He is solving a problem and wants to calcu...
def sum_to(n): return n * (n-1) / 2 def count_zeros(lo, hi): S = 0 for pow5 in (5**i for i in xrange(1,9)): #print pow5 S += pow5 * (sum_to(hi//pow5) - sum_to(lo//pow5)) #print S S += (hi % pow5 + 1) * (hi // pow5) - (lo % pow5) * (lo // pow5) #print S return S ...
In this problem, we use the 24-hour clock. Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.) He has decided to study for K consecutive minutes while he is up. What is the length of the period in which he can start studying? Constraint...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int H1 = sc.nextInt(); int M1 = sc.nextInt(); int H2 = sc.nextInt(); int M2 = sc.nextInt(); int K = sc.nextInt(); sc.close(); int...
Given is a positive integer N. Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition: * When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B. Con...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long ans = 0; for (int i=0;i<10;i++){ for (int j=0;j<10;j++){ int cij = 0; int cji = 0; ...
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}. Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2. Find the inversion number of B, modulo 10^9 + 7. Here the inversion number of B is defined as the number of o...
#include <bits/stdc++.h> using namespace std; int main() { long long int mod = 1000000007; long long int n, k; long long int ans = 0LL; //long long int scnt = 0LL; //long long int lcnt = 0LL; long long int a[2005]; cin >> n >> k; for(int i=0;i<n;i++){ cin >> a[i]; } for(int i=0;i<n;i++){ for(int j=i+1;j<n...
You are given N integers. The i-th integer is a_i. Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied: * Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area...
M=998244353 N,*A=open(0) d=[0]*90001 d[0]=1 e=[0]*90001 e[0]=1 z=1 s=0 for a in A: i=s;a=int(a);s+=a;z*=3 while~i:d[i+a]+=d[i]%M;d[i]*=2;e[i+a]+=e[i]%M;i-=1 i=s while i*2>=s:z=(z-d[i]*3)%M;i-=1 print([(z+e[s//2]*3)%M,z][s%2])
In some other world, today is the day before Christmas Eve. Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan). He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 i...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int sum = 0; int max = 0; int pre[] = new int[N]; for(int i = 0; i < N; i++) { pre[i] = sc.nextInt(); if(max < pre[i]) { max = pre[i]; } ...
We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N. We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M). AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N)...
#include <bits/stdc++.h> using namespace std; int niz[300050]; vector<int> adj[300050]; int comp[300050]; int ind[100050]; void dfs(int x,int k) { comp[x]=k; for(auto y:adj[x]) if(!comp[y]) dfs(y,k); } int main() { int n,m; cin>>n>>m; for(int i=1;i<=n;i++) { ...
We have 2N pots. The market price of the i-th pot (1 ≤ i ≤ 2N) is p_i yen (the currency of Japan). Now, you and Lunlun the dachshund will alternately take one pot. You will go first, and we will continue until all the pots are taken by you or Lunlun. Since Lunlun does not know the market prices of the pots, she will a...
#include <iostream> #include <cstdio> #include <cmath> #include <ctime> #include <cstdlib> #include <cassert> #include <vector> #include <list> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <bitset> #include <string> #include <algorithm> #include <utility> #define llint long ...
Snuke is buying a lamp. The light of the lamp can be adjusted to m levels of brightness, represented by integers from 1 through m, by the two buttons on the remote control. The first button is a "forward" button. When this button is pressed, the brightness level is increased by 1, except when the brightness level is m...
n,m=map(int,input().split()) arr=list(map(int,input().split())) imos1=[0]*(m*2+2) imos2=[0]*(m*2+2) imos3=[0]*(m*2+2) for i in range(n-1): cost=(m+arr[i+1]-arr[i])%m if arr[i]<arr[i+1]: imos1[arr[i]]+=cost imos1[arr[i]+m]-=cost imos2[arr[i]+2]+=-1 imos2[arr[i+1]+1]+=1 imos3[arr[i+1]+1]+=cost-1 ...
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions: * Every group contains between A and B people, inclusive. * Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds. ...
import java.util.ArrayList; import java.util.Scanner; public class Main { static final long MOD = 1000000007; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); sc.c...
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively. <image> An example of a trapezoid Find the area of this trapezoid. Constraints * 1≦a≦100 * 1≦b≦100 * 1≦h≦100 * All input values are integers. * h is even. Input The input is given from Standard Input i...
a,b,h=[int(input()) for i in range(3)];print(int((a+b)*h/2))
<image> There used to be a game called Joseph's potatoes. Let's say n people are participating. Participants form a circle facing the center and are numbered starting from 1. One hot potato is given to participant n (the large number 30 inside the figure on the left). Participants who are given the potatoes will give...
while 1: n,m=map(int,input().split()) if n==0:break a=m-1 while a<(m-1)*n: a=m*a//(m-1)+1 a=n*m-a print(a)
At Aizu Riverside Hospital, inpatients walk twice a day for rehabilitation and health promotion. As the number of people trying to recover their physical strength by walking is increasing day by day in order to leave the hospital energetically, the director plans to give a present to the person who walked the longest d...
#include <cstdio> #include <vector> using namespace std; typedef struct P { int p, d; bool operator<(const P &r) { return d < r.d; } } P; int n;; int main(){ int p, d1, d2; while (true) { scanf("%d", &n); if (n == 0) break; P m = { 0,-1 }; P t; for (int i = 0; i < n; i++) { scanf("%d %d %d", &p, &...
I’m planning to have a party on my birthday. Many of my friends will come to the party. Some of them will come with one or more pieces of cakes, but it is not certain if the number of the cakes is a multiple of the number of people coming. I wish to enjoy the cakes equally among the partiers. So, I decided to apply th...
#include <bits/stdc++.h> #define rep(i,n) for (long long i = 0; i < (n); ++i) const int INF = 2147483647;//int max const long long int MOD = 1000000007; using namespace std; using ll = long long; using P = pair<int,int>; template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }...
Please find the greatest common divisor of two natural numbers. A clue is: The Euclid's algorithm is a way to resolve this task. Input The input file consists of several lines with pairs of two natural numbers in each line. The numbers do not exceed 100000. The number of pairs (datasets) is less than 50. Output ...
import sys def gcd(a,b): if(b): return gcd(b,(a%b)) else: return a List = [] for i in sys.stdin: List.append(i) for data in List: print(gcd(int(data.split()[0]),int(data.split()[1])))
At 17:00, special agent Jack starts to escape from the enemy camp. There is a cliff in between the camp and the nearest safety zone. Jack has to climb the almost vertical cliff by stepping his feet on the blocks that cover the cliff. The cliff has slippery blocks where Jack has to spend time to take each step. He also ...
import java.util.*; import java.awt.Point; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(true){ int w = sc.nextInt(), h = sc.nextInt(); if(w==0 && h==0) break; char[][] map = new char[h][w]; for(int i=0;i<h;i++){ String s = ""; for(int ...
Spinning tops are one of the most popular and the most traditional toys. Not only spinning them, but also making one’s own is a popular enjoyment. One of the easiest way to make a top is to cut out a certain shape from a cardboard and pierce an axis stick through its center of mass. Professionally made tops usually ha...
#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>...
Problem Let's implement a function of a popular smartphone game. The game is based on the following specifications. * 5 types of blocks are installed in 5 * 5 squares. * Scores are set for each type of block. * In addition to the block score, a bonus score is set for the score. The first bonus score is 1. * You can a...
#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <complex> #include <queue> #include <deque> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <iomanip> #include <assert.h> #include <array> #include <cstdio> #include <cstring> #include <random> ...
Mr. Yamada Springfield Tanaka was appointed as Deputy Deputy Director of the National Land Readjustment Business Bureau. Currently, his country is in the midst of a major land readjustment, and if this land readjustment can be completed smoothly, his promotion is certain. However, there are many people who are not hap...
#include <algorithm> #include <complex> #include <cstdio> #include <iostream> #include <vector> #include <utility> using namespace std; #define X real() #define Y imag() #define EPS (1e-10) typedef complex<double> P; typedef pair<P, P> L; namespace std{ bool operator<(const P& a, const P& b){ return a.X != b.X ?...
Adam Ivan is working as a system administrator at Soy Group, Inc. He is now facing at a big trouble: a number of computers under his management have been infected by a computer virus. Unfortunately, anti-virus system in his company failed to detect this virus because it was very new. Adam has identified the first comp...
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct State{ int t, s, d; State(int t_, int s_, int d_){ t = t_; s = s_; d = d_; } State(){} }; bool operator<(const State &a, const State &b){ return a.t < b.t; } int main(){ int N, M; while( cin >> N >> M, N || M ){ vector<b...
Consider sets of natural numbers. Some sets can be sorted in the same order numerically and lexicographically. {2, 27, 3125, 9000} is one example of such sets; {2, 27, 243} is not since lexicographic sorting would yield {2, 243, 27}. Your task is to write a program that, for the set of integers in a given range [A,B] ...
#include <iostream> #include <sstream> #include <vector> #include <algorithm> #include <cstring> using namespace std; typedef long long ll; typedef pair<string,int> P; ll A, B, MOD; ll n; ll bit[1000000]; ll sum(int i){ ll res = 0; while(i > 0){ res += bit[i]; res %= MOD; i -= i & -i; } return re...
Problem B: Blame Game Alice and Bob are in a factional dispute. Recently a big serious problem arised in a project both Alice and Bob had been working for. This problem was caused by lots of faults of Alice's and Bob's sides; those faults are closely related. Alice and Bob started to blame each other. First, Alice cl...
#include <iostream> #include <vector> #include <cstring> #include <string> #include <algorithm> #include <iomanip> #include <cmath> #include <cassert> using namespace std; struct BipartiteMatching { int V; vector<vector<bool> > G; vector<int> match; vector<bool> used; BipartiteMatching(int v) { V = v; G = ve...
Sunuke came up with a pun called "s de t t", but forgot it. Sunuke remembers the following. * The length of s is N. * The length of t is M. * t is a substring of s. (There is a part of consecutive M characters of s that matches t.) Divide the number of possible combinations as (s, t) by 1,000,000,007 to find the re...
#include<cstdio> #include<vector> #include<algorithm> using namespace std; const long long mod = 1000000007; struct UnionFind{ vector<int> par; void init(int N){ par.clear(); for(int i = 0; i < N; ++i){ par.push_back(i); } } int find(int x){ if(x == par[x]) return x; return par[x] = find(par[x]); }...
Example Input 1 5 1 Output 11111
#include<bits/stdc++.h> using namespace std; using Int = long long; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} template<typename T,T MOD = 1000000007> struct Mint{ T v; Mint():v(0){} Mint(signed v):v...
L: Sugi (Demon's Cedar) Tsukinose decided to change the trees all over the city to sugi trees and annoy people with hay fever in order to do something devilish. There are $ N $ types of trees. The heavenly rank of the $ i $ tree is $ A_i $, and the rank in the demon world is $ B_i $. Also, the $ 1 $ type of tree is S...
#include<iostream> #include<vector> #include<algorithm> #include<queue> using namespace std; typedef long long ll; typedef pair<int,int> pii; int main(){ int n; cin >> n; vector<pii> va, vb; for(int i = 0; i < n; i++){ int x; cin >> x; va.push_back({x, i}); } for(int i = 0; i <...
Problem One day, mo3tthi and tubuann decided to play a game with magic pockets and biscuits. Now there are $ K $ pockets, numbered $ 1,2, \ ldots, K $. The capacity of the $ i $ th pocket is $ M_i $, which initially contains $ N_i $ biscuits. mo3tthi and tubuann start with mo3tthi and perform the following series of o...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int grundy(ll n, ll m){ if(n==1){ return grundy(2,m) == 0; } ll l = m/2, r = m, cnt = 0, ev = m%2, od = (m+1)%2; while(l >= n){ r = l; l >>= 1; cnt++; if(r%2){ if(ev == 0){ ...
For given two circles $c1$ and $c2$, print the coordinates of the cross points of them. Constraints * The given circle have at least one cross point and have different center coordinates. * $-10,000 \leq c1x, c1y, c2x, c2y \leq 10,000$ * $1 \leq c1r, c2r \leq 10,000$ Input The input is given in the following format...
#include <iostream> #include <vector> #include <string> #include <cstring> #include <algorithm> #include <sstream> #include <map> #include <set> #include <cmath> #define REP(i,k,n) for(int i=k;i<n;i++) #define rep(i,n) for(int i=0;i<n;i++) #define INF 1<<30 #define pb push_back #define mp make_pair #define EPS 1e-8 #d...
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$ (0 or 1). * delete($x$): Delete $x$ from $S$. * dump($L$, $R...
//#define _GLIBCXX_DEBUG #include <bits/stdc++.h> #define rep(i, n) for(int i=0; i<n; ++i) #define all(v) v.begin(), v.end() #define rall(v) v.rbegin(), v.rend() using namespace std; using ll = int64_t; using ld = long double; using P = pair<int, int>; using vs = vector<string>; using vi = vector<int>; using vvi = vect...
Problem description. Chris brown and Rihanna are in a nxn grid(1 indexed). Chris brown want to reach Rihanna in minimum number of moves but the thing is he can move only diagonally and whatever may be the number of steps he takes it is considered as only one move unless he takes a turn. So in one move he can take as ma...
t=int(input()) for i in range(t): n=int(input()) [a,b,c,d]=map(int,raw_input().split()) if a==c and b==d: ans=0 elif (a+b)%2 == (c+d)%2: ac=max(a,c)-min(a,c) bd=max(b,d)-min(b,d) if (a+b)==(c+d) or ac==bd: ans=1 else: ans=2 else: ...
Given a string, count the number of aplhabets which are repeated   Input The first line contains a single integer T <= 40, the number of test cases. T test cases follow. The only line of each test case contains a non-empty text composed only of letters of English alphabet. The length of the text is less then 100. Ther...
n=input() for i in range(n): string1=raw_input().lower() count=0 for y in range (97,122): if string1.count(chr(y))>1: count+=1 print count
Ananya, is a class 12 student and is preparing for IIT-JEE examination to be held later this year out of the 3 subjects asked in IIT JEE , physics, chemistry and mathematics she only likes mathematics and is a virtuoso in mathematics seeing her mathematical skills her school math teachers built an inferiority complex ...
import sys T = int(raw_input()) while T : n , p = map(int,sys.stdin.readline().split()) x = pow(n,p) res = x sum = 0 while res : sum = sum + (res%10) res/=10 print x , sum T-=1 def pow(n,p) : if p == 0 : return 1 else : if p%2 : return n*pow(n,p-1) else : k = pow(n,p/2) ...
Chef is array maniac.He use to play with arrays.Chef's friend given him an array of size n-1 integers and these integers are in the range of 1 to n. There are no duplicates in array. One of the integers is missing in the array.Now chef has to write efficient code to find the missing integer.Please help him to find the ...
n=input() for i in range(n): a=input() f=map(int,raw_input().split()) for i in range(1,a+1): if i not in f: print i
You are provided with a set of numbers which is infinitely large. The numbers in this set are of the form :- { 2^2^n + 1 } where n is a positive integer. Now these set of numbers are kept in sorted order. Now queries are defined on this set such that given a range of terms [X...Y] you must calculate the sum of pairwis...
t = input() while t: t-=1 x,y = [int(x) for x in raw_input().split()] print( ( (y - x + 1) * (y - x) ) / 2 )
Given the list of numbers, you are to sort them in non decreasing order. Input t – the number of numbers in list, then t lines follow [t <= 10^6]. Each line contains one integer: N [0 <= N <= 10^6] Output Output given numbers in non decreasing order. Example Input: 5 5 3 6 7 1 Output: 1 3 5 6 7
x=int(raw_input()) a=[] for z in range(x): a.append(int(raw_input())) a.sort() for z in a: print z
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise...
n = int(input()) a = input() b = input() index = [] zeros = 0 ones = 0 for i in range(n): if b[i]=='0': index.append(i) if a[i]=='0': zeros += 1 else: ones += 1 ans = 0 interchange = 0 for i in index: if a[i]=='0': ans += ones zeros -= 1 else: ans += z...
This is an interactive problem. In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontr...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; const long long INF = 1000LL * 1000 * 1000 * 1000 * 1000 * 1000; const int inf = 1000...
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly k candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends i...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; const long long N = 2e3 + 10; const long long inf = 1e18 + 10ll; const long long mod = 1e9 + 7; const long long eps = 1e-9; mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); using namespace std; long long n, l, r, k; lo...
The Squareland national forest is divided into equal 1 × 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C i...
#include <bits/stdc++.h> #pragma warning(disable : 4996) #pragma comment(linker, "/STACK:16777216") using namespace std; int main() { ios::sync_with_stdio(false); vector<pair<int, int>> x(3, pair<int, int>{}); for (int i = 0; i < 3; i++) { cin >> x[i].first >> x[i].second; } sort(x.begin(), x.end()); co...
Salem gave you n sticks with integer positive lengths a_1, a_2, …, a_n. For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x. A stick length a_i is...
n = int(input()) a = [int(t) for t in input().split(' ')] mincost = 1000 * 100 + 1 best_t = None for t in range(1, 101): cost = 0 for x in a: cost += max(0, abs(x - t) - 1) if cost < mincost: mincost = cost best_t = t print(best_t, mincost)
Berland SU holds yet another training contest for its students today. n students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers! Let students be numbered from 1 to n. Laptop of the i-th student has charge a_i at the beginning of the contest and it uses b_i of char...
#include <bits/stdc++.h> using namespace std; template <class T1, class T2, class T3 = hash<T1>> using umap = unordered_map<T1, T2, T3>; template <class T> using uset = unordered_set<T>; template <class T> using vec = vector<T>; const long long infll = numeric_limits<long long>::max() >> 1; const long long inf = numeri...
This problem is same as the previous one, but has larger constraints. Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse. There are n planets in the Catniverse, numbered from 1 to n. At the beginning of the game, Aki chooses the planet whe...
#include <bits/stdc++.h> using namespace std; const int S = 16 * 13; const int Mod = 1e9 + 7; typedef class Matrix { public: int r, c; int a[S][S]; Matrix() {} Matrix(int r, int c) : r(r), c(c) {} Matrix operator*(Matrix b) { Matrix rt(r, b.c); for (int i = 0; i < r; i++) { for (int j = 0; j < ...
Let's define a function f(p) on a permutation p as follows. Let g_i be the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of elements p_1, p_2, ..., p_i (in other words, it is the GCD of the prefix of length i). Then f(p) is the number of distinct elements among g_1, g_2, ..., g_...
#include <bits/stdc++.h> using namespace std; const int NMAX = 1e6; const int LGMAX = 20; const int MOD = 1e9 + 7; int n; int dp[2][LGMAX + 1][2]; int main() { scanf("%d", &n); int lg2 = 0; while ((1 << lg2) <= n) { lg2++; } lg2--; dp[1][lg2][0] = 1; if (n >= 3 && (3 << (lg2 - 1) <= n)) { dp[1][lg...
You have been hired to supervise the project of a new amusement park. The park will have a special gimmick: directed slides that can get customers from one attraction to another quickly and in an entertaining way. The park owner has given you the current project: a list of planned attractions and a list of slides that...
#include <bits/stdc++.h> using namespace std; using LL = long long; namespace _buff { const size_t BUFF = 1 << 19; char ibuf[BUFF], *ib = ibuf, *ie = ibuf; char getc() { if (ib == ie) { ib = ibuf; ie = ibuf + fread(ibuf, 1, BUFF, stdin); } return ib == ie ? -1 : *ib++; } } // namespace _buff LL read() { ...
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him? You're given a tree — a connected undirected graph consisting of n vertices conne...
#include <bits/stdc++.h> #pragma gcc optimize("ofast") using namespace std; long long modexp(long long a, long long b, long long m) { long long r = 1; a = a % m; while (b > 0) { if (b & 1) r = (r * a) % m; b = b / 2; a = (a * a) % m; } return r % m; } const int MAXN = 100002; long long a[MAXN]; ve...
Dawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total? Note, that you can't keep bags for yourself or thro...
#include <bits/stdc++.h> using namespace std; int main() { long long int t, n, i, j, p = 0, x = 0, y = 0, x1 = 0, y1 = 0, k = 0, a = 0, b = 0, sum = 0, q = 0, r = 0, s = 0, l = 0, c = 0, odd = 0, even = 0; long long int array[5]; for (i = 0; i < 4; i++) { ...
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them! A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≤ a ≤ b ≤ n). For e...
n, k = [int(i) for i in input().split()] s = input() arr = input().split() subs = [0] for x in s: if(x in arr): subs[-1] += 1 else: subs.append(0) count = 0 for x in subs: count += x*(x+1)/2 print(int(count))
You are given two integers a and m. Calculate the number of integers x such that 0 ≤ x < m and \gcd(a, m) = \gcd(a + x, m). Note: \gcd(a, b) is the greatest common divisor of a and b. Input The first line contains the single integer T (1 ≤ T ≤ 50) — the number of test cases. Next T lines contain test cases — one pe...
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class ECF81d { public static void print(String str,int val){ System.out.println(str+" "+val); } public static long gcd(long a, long b) { if (b==0) return a; return gcd(b,...
Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n× n board. Rows and columns of this board are numbered from 1 to n. The cell on the intersection of the r-th row and c-th...
import java.util.*; import java.io.*; public class NashMatrix { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt...
This is an interactive problem. Yui is a girl who enjoys playing Mahjong. <image> She has a mysterious set which consists of tiles (this set can be empty). Each tile has an integer value between 1 and n, and at most n tiles in the set have the same value. So the set can contain at most n^2 tiles. You want to figure...
#include <bits/stdc++.h> struct MI { private: char bb[1 << 14]; FILE* f; char *bs, *be; char e; bool o, l; public: inline char get() { if (o) { o = 0; return e; } if (bs == be) be = (bs = bb) + fread(bb, 1, sizeof(bb), f); if (bs == be) { l = 1; return -1; }; ...
Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Pety...
#include <bits/stdc++.h> using namespace std; int n, m; int i, j, k, l; char s[1003][1003]; int u[1003][1003]; int v[1003][1003]; bool w[1003][1003]; int c; bool ok; int xc[1000006], yc[1000006], d; int ans; void dfs1(int x, int y) { u[x][y] = c; int i, j; for (i = -1; i < 2; i += 2) for (j = -1; j < 2; j += ...
Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Inn...
import static java.lang.Math.*; import java.util.*; import java.io.*; public class E { public void solve() throws Exception { String s = "."+nextLine().toLowerCase(); int n = s.length(); int[] score = new int[n]; for (int i=1; i<n; ++i) score[i] = score[i-1] +...
Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules: There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into ...
#include <bits/stdc++.h> using namespace std; const double PI = 3.141592653589793238462643383279502884197169399375105820974944; int n, m; int bl; int a[100005], nex[100005], steps[100005], b[100005]; int main() { scanf("%d%d", &n, &m); bl = sqrt(n); for (int i = 0; i < (n); i++) scanf("%d", &a[i]), b[i] = i /...
BubbleSquare social network is celebrating 13^{th} anniversary and it is rewarding its members with special edition BubbleSquare tokens. Every member receives one personal token. Also, two additional tokens are awarded to each member for every friend they have on the network. Yet, there is a twist – everyone should end...
#include <bits/stdc++.h> const int N = 2e5 + 10, M = 2e6 + 10; template <typename T = int> inline T read() { T x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f |= ch == '-', ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return f ? -x : x; } int tot, w[N], vis[N], d[N], u[...
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division. To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that: * p_i is divisible by x_i; * x_i is not divisible by q_i. ...
import java.io.*; import java.util.*; public class C { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st ...
Monocarp had a sequence a consisting of n + m integers a_1, a_2, ..., a_{n + m}. He painted the elements into two colors, red and blue; n elements were painted red, all other m elements were painted blue. After painting the elements, he has written two sequences r_1, r_2, ..., r_n and b_1, b_2, ..., b_m. The sequence ...
/* ------------------------------------------------------------ -- -- -- cccccc oooooooo ddddd eeeeee rrrrr -- -- cc oo oo dd dd ee rr rr -- -- cc oo oo dd dd eeeeee rrrrr -- -- cc ...
The Dogeforces company has k employees. Each employee, except for lower-level employees, has at least 2 subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employ...
#include <bits/stdc++.h> using namespace std; #define ll long long #define ff first #define ss second const int MX=200000+10; int V[MX], S[MX], a[555][555], vis[MX], T, K; vector<int>g[MX]; void dfs(int id, int n) { K=max(K, id); vector<int>v; for(int i=1; i<=n; i++) { if(vis[i]==id) v.push_...
Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it: Consider an n by n chessboard. Its rows are numbered from 1 to n from the top to the bottom. Its columns are numbered from 1 t...
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self...
Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied. In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if po...
#include <iostream> #include <string> #include <cmath> #include <vector> #include <algorithm> #include <utility> #include <bitset> #include <climits> #include <set> #include <map> #include <iomanip> #include <queue> #include <cstring> using namespace std; #define ll long long #define INF LONG_LONG_MAX #define pll pair<...
Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest comm...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string s[n + 10000]; vector<int> v; for (int i = 0; i < n; ++i) cin >> s[i]; for (int i = 0; i < s[0].size(); ++i) { int j = 0; int ans = 1; while (j <= n - 1) { if (s[j][i] == s[j + 1][i]) ++ans; ++j; } ...
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from ...
n = int(raw_input()) a = map(int,raw_input().split()) f = [1000 for i in range(0,n+3)] f[0] = 0 f[1] = a[0] for i in range(2,n+1): f[i] = max(f[i-1],f[i-2]) f[i] = min(f[i],a[i-1]) print f[n]
One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people. We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B ...
#include <bits/stdc++.h> using namespace std; int N, M; int p[101]; int e[101]; int res = 0; int FindSet(int x); int main() { cin >> N >> M; for (int i = 1; i <= N; i++) p[i] = i, e[i] = 1; int x, y; for (int i = 0; i < M; i++) { scanf("%d%d", &x, &y); int px = FindSet(x), py = FindSet(y); if ((px =...
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount of pe...
for i in range(int(input())): x = int(input()) print(max(0,x-2))
Squirrel Liss loves nuts. Liss asks you to plant some nut trees. There are n positions (numbered 1 to n from west to east) to plant a tree along a street. Trees grow one meter per month. At the beginning of each month you should process one query. The query is one of the following types: 1. Plant a tree of height h...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("O3") #pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") using namespace std; const long long inf = 0x3f3f3f3f3f3f3f3fll; char __wzp[1 << 15 | 1], *__S = __wzp + 32768; inline int read() { register int x =...
Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Polo the Penguin have two positive integers l and r (l < r), both of them are lucky numbers. Moreover, their lengths (that i...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; const int mod = 1e9 + 7; inline long long mul(long long x, long long y) { return x * y % mod; } int n; long long sum[N][2][2], sq[N][2][2], cnt[N][2][2]; char a[N], b[N]; int main() { scanf("%s %s", a + 1, b + 1); n = strlen(a + 1); for (int i =...
Ilya has recently taken up archaeology. He's recently found two numbers, written in the m-based notation. Each of the found numbers consisted of exactly n digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decypher it...
#include <bits/stdc++.h> using namespace std; long long n, m; multiset<long long> Nums, FG, SG; void input() { cin >> n >> m; for (long long i = 1; i <= n; i++) { long long a; cin >> a; FG.insert(a % m); } for (long long i = 1; i <= n; i++) { long long b; cin >> b; SG.insert(b % m); } ...
One beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), r...
import math def readInp(): m, R = map(int, raw_input().split(' ')) return m, R m, R = readInp() S = m + (m-1)*(2 + math.sqrt(2)*(m-1)) for i in range(1,(m+1)): S += (i-1)*(i-2) print '%.10f' % (2*R*S/(m*m))
Simon has a prime number x and an array of non-negative integers a1, a2, ..., an. Simon loves fractions very much. Today he wrote out number <image> on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: <image>, where number t equals xa1 + a2 + ... + an. Now ...
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; final static String IO = "_std"; final int mod = inf + 7; int modpow(int a, long p) { ...
Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers a, b, w, x (0 ≤ b < w, 0 < x < w) and Alexander took integer с. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number...
#include <bits/stdc++.h> using namespace std; int main() { long long int a, b, w, x, c; cin >> a >> b >> w >> x >> c; if (c <= a) printf("0\n"); else { long long int I = c - a; b -= (I - 1) * x; long long int J = ceill((double)(x - b) / (w - x)); cout << I + J; } return 0; }
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A sub...
import java.util.Scanner; import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Himalay(himalayjoriwal@gmail.com) */ public class Main { public static void main(String[] args) ...
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any p...
import java.lang.*; import java.util.*; import java.util.stream.Collectors; import java.io.*; public class Problem { public static int maxcancel(int[] ar, List<Integer> dblx, int x) { int max=0,pos=0,n=ar.length; while(pos<dblx.size()) { int st=dblx.get(pos); int end=st+1; pos++; int m...
You are given three strings (s1, s2, s3). For each integer l (1 ≤ l ≤ min(|s1|, |s2|, |s3|) you need to find how many triples (i1, i2, i3) exist such that three strings sk[ik... ik + l - 1] (k = 1, 2, 3) are pairwise equal. Print all found numbers modulo 1000000007 (109 + 7). See notes if you are not sure about some o...
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; import java.io.InputStream; /** * Built using CHel...