input
stringlengths
29
13k
output
stringlengths
9
73.4k
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side. One example of a grid path is (0, 0) β†’ (0, 1) β†’ (0, 2) β†’ (1, 2...
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 100; int n; char s1[N], s2[N]; int len, Next[N]; void getnext(char s[]) { Next[0] = -1; int j = -1, i = 0; while (i < n) { if (j == -1 || s[i] == s[j]) { i++; j++; Next[i] = j; } else j = Next[j]; } } int kmp(char ...
Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from 1 to n. All the corridors are bidirectional. Arnie wants the new house to look just like the previous one....
#include <bits/stdc++.h> using namespace std; int n, m; int a[2020]; int b[2020]; bool vis[128]; int e[2020]; vector<pair<int, int> > g[128]; void dfs(int v) { int i, u; for (i = 0; i < g[v].size(); i++) { if (e[g[v][i].second] != 0) continue; u = g[v][i].first; if (vis[u] == 0) { vis[u] = 1; ...
<image> You can preview the image in better quality by the link: [http://assets.codeforces.com/files/656/without-text.png](//assets.codeforces.com/files/656/without-text.png) Input The only line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be an alphanumeric character o...
#include <bits/stdc++.h> using namespace std; int main() { string str; int ans = 0; getline(cin, str); int len = str.length(); for (int i = 0; i <= len - 1; i++) { if (isupper(str[i])) { ans += str[i] - 64; } if (islower(str[i])) { ans -= str[i] - 96; } } cout << ans << endl; ...
You are given a sequence of balls A by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, B that suits you better. So, you allow yourself four operations: * You can insert any ball with any label into the sequence at any pos...
#include <bits/stdc++.h> using namespace std; const int maxn = 4111; const int maxm = 257; const int inf = 0x3f3f3f3f; int f[maxn][maxn]; char A[maxn], B[maxn]; int pos[2][maxm]; int t[5]; int n, m; bool get() { for (int i = 0; i < 4; ++i) if (1 != scanf("%d", t + i)) return 0; scanf("%s%s", A + 1, B + 1); re...
You are given n points on the straight line β€” the positions (x-coordinates) of the cities and m points on the same line β€” the positions (x-coordinates) of the cellular towers. All towers work in the same way β€” they provide cellular network for all cities, which are located at the distance which is no more than r from t...
#include <bits/stdc++.h> using namespace std; long long n, m, r; set<long long> np, vs; int main() { ios_base::sync_with_stdio(0); cin >> n >> m; for (int i = 0; i < n; i++) { long long t; cin >> t; np.insert(t); } for (int i = 0; i < m; i++) { long long t; cin >> t; vs.insert(t); } ...
You are given a string s, consisting of lowercase English letters, and the integer m. One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the chosen...
#include <bits/stdc++.h> using namespace std; int m; char s[120000]; int n; int us[120000]; int main() { scanf("%d", &m); scanf(" %s", s); n = strlen(s); for (int i = 0; i < 26; ++i) { for (int j = 0; j < n; ++j) if (s[j] == 'a' + i) us[j] = 2; int pr = -1; int lst = -m - 100; int fl = 0; ...
Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black. Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing...
n,k,a,b = [int(i) for i in input().split()] check = False if (a>b): a,b = b,a check = True res = "" cr = 1 cA = True while (a > 0 or b > 0): if (a==b): break #print(a,b) if (cr==1): if a <= b: u = min(k, b - a) b -= u res += u * '1' else:...
Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs ...
import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class D implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer t...
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office. The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lan...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOExcept...
A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed. To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long t...
#include <bits/stdc++.h> int cmp(const void *a, const void *b) { return *(int *)b - *(int *)a; } int main() { int n, m; scanf("%d %d", &n, &m); int a[n], b[m]; for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < m; i++) scanf("%d", &b[i]); qsort(b, m, sizeof(b[0]), cmp); for (int i = 0; i ...
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutel...
#include <bits/stdc++.h> using namespace std; bool is_prime(long long x) { if (x == 1) return false; for (int i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } bool is_palindrome(string s1) { int l = s1.length(); for (int i = 0; i < l / 2; i++) if (s1[i] != s1[l - i - 1]) return fal...
In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order. For each action several separate windows are...
#include <bits/stdc++.h> using namespace std; queue<int> waiting[3]; priority_queue<pair<long long, pair<int, int> > > q; long long c[100010]; long long maxx = -1; int main() { int i, n; int k[3] = {0}; int cnt[3] = {0}; long long t[3] = {0}; scanf("%d", &k[0]); scanf("%d", &k[1]); scanf("%d", &k[2]); s...
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research. First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes h...
/** * Created by tsiya on 11/12/2017. */ import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { HashMap<Integer, Integer> map = new HashMap(); Scanner read = new Scanner(System.in); int a = Integer.parseInt(re...
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be <image> of them. You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endp...
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws Exception { MyReader reader = new MyReader(System.in); // MyReader reader = new MyReader(new FileInputStream("input.txt")); MyWriter writer = new MyWriter(System.out); new Sol...
Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates x and y. The players take turn making moves, white starts. On each turn, a player moves all tokens of their color by 1 to up, down, left or right. B...
#include <bits/stdc++.h> using namespace std; template <typename T, typename U> std::istream& operator>>(std::istream& i, pair<T, U>& p) { i >> p.first >> p.second; return i; } template <typename T> std::istream& operator>>(std::istream& i, vector<T>& t) { for (auto& v : t) { i >> v; } return i; } templat...
It is now 125 years later, but humanity is still on the run from a humanoid-cyborg race determined to destroy it. Or perhaps we are getting some stories mixed up here... In any case, the fleet is now smaller. However, in a recent upgrade, all the navigation systems have been outfitted with higher-dimensional, linear-al...
#include <bits/stdc++.h> using namespace std; const long long mod = 1000000007; long long powmod(long long a, long long b) { long long res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) { if (b & 1) res = res * a % mod; a = a * a % mod; } return res; } long long gcd(long long a, long long b) { re...
For an array b of length m we define the function f as f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] βŠ• b[2],b[2] βŠ• b[3],...,b[m-1] βŠ• b[m]) & otherwise, \end{cases} where βŠ• is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, f(1,2,4,8)=f(1βŠ•2,2βŠ•4,4βŠ•8)=f(3,6,12)=f(3βŠ•6...
#include <bits/stdc++.h> using namespace std; const int N = 5000 + 7; const int M = 1e4 + 7; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; int f[N][N], a[N], n, dp[N][N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1;...
You are given an array S of N strings numbered from 0 to N-1. You build string sequence Ti by the following rules: T0 = S0 Ti = Ti-1 + reverse(Ti-1) + Si Now please answer M queries: by non-negative integer x output x-th character of the TN-1 in 0-based indexation. It's guaranteed that x-th character of the TN-1 exi...
t = int(raw_input()) for _ in xrange(t): n, m = [int(x) for x in raw_input().split()] s = [raw_input() for __ in xrange(n)] ans = '' arLen = sum(2 ** (len(s) - i - 1) * len(s[i]) for i in xrange(len(s))) for __ in xrange(m): req = int(raw_input()) curr = arLen last = len(s) -...
Little Bob comes to you for candies as you are his favorite coder! He wants X candies. You have N bags and the i^th bag contains A[i] candies. You can give him a set of one or more bags such that the sum of candies in those bags is EXACTLY equal to X. Bob wants to find smallest such set of bags. If there are multiple ...
def isLexiograficalSorted(best, current): best.sort() current.sort() if len(best) < len(current): return True if len(best) > len(current): return False # len is same for i in xrange(len(best)): if best[i] < current[i]: return True if best[i] > current...
The students of college XYZ are getting jealous of the students of college ABC. ABC managed to beat XYZ in all the sports and games events. The main strength of the students of ABC is their unity. The students of XYZ decide to destroy this unity. The geeks of XYZ prepared a special kind of perfume. Anyone who inhales...
from collections import Counter n=input() for i in xrange(0,n): x=input() boys={} girls={} boy_crush=[int(x) for x in raw_input().split()] girl_crush=[int(x) for x in raw_input().split()] boy_crush.insert(0,0) girl_crush.insert(0,0) for i in xrange(1,len(boy_crush)): temp=boy_cr...
Amer cabs has released a scheme through which a user gets a free drive when he shares a reference code with another Amer app user. Given N number of app users, output total number of free drives gained by all of them. Two same users cannot share reference code more than once. Input Format The first line contains th...
t = int(raw_input()) while(t): n = int(raw_input()) print(n*(n-1)//2) t -= 1
Kabra is a very good friend of JP. So JP has assigned him a task. Given an array, two operations can be performed on it. They are 1) L X : Rotate the array towards left by X. 2) R X : Rotate the array towards right by X. Now you will be given 2 arrays containing N unique elements. The first one is the inital array(A) a...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' N,M=map(int,raw_input().split()) inic=map(int,raw_input().split()) targ=map(int,raw_input().split()) done=False try: good=targ.index(inic[0]) except ValueError: print -1 done=True...
Milly is playing with an Array A of size N. She wants to convert this array into a magical array. This magical array satisfies the condition Ai-1 < Ai where i ∈ [2, N] . She can add a value X to any element of this array any number of times. Your task is to tell her the minimum number of such addition of X are required...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(input()) for ti in xrange(t): n, x = map(int, raw_input().split()) arr = map(int, raw_input().split()) elem = arr[0] count = 0 for i in xrange(1, len(arr)): if elem >= ar...
King Klee's kingdom is under attack. He leaves the task of protecting his kingdom to you as you are Now you are given N teams of soldiers. There are 3 gates --> Large, Larger, Largest. You need to form three teams from these N teams to send them to those three gates. But the order should follow certain conditions ...L...
arr = [] res = 0 for i in range(input()): arr.append(input()) res += arr[i] power = 1 n = len(arr) for i in range(n): power *= 3 for i in range(power): temp = i s1, s2, s3 = 0,0,0 for j in range(n): if temp % 3 == 0: s1+=arr[j] if temp % 3 == 1: s2+=arr[j] if temp % 3 == 2: s...
The Manager Manoj has thought of another way to generate revenue for his restaurant. He has a large oven to bake his goods, but he has noticed that not all of the racks are used all of the time. If a rack is not used, then the Manoj has decided to rent it out for others to use. The Manoj runs a very precise schedule; h...
def f(av,index): l1=[] l2=[] global l global m global n if(index==n): return 0 for i in range(0,m): l1.append(av[i]) l2.append(av[i]) boolean=True for i in range(l[index][0],l[index][1]): l1[i]-=1 if(av[i]<=0): boolean=False ...
After learning basics of arrays and strings, Dark started wondering that if we can sort the numbers then why not STRINGS? Deeply thinking and looking the various strings lying in the string pool, he decided to ascend or descend the string according to his wish. Ascending means strings having all the characters in a s...
import sys def main(): t=input() if t==20: while t: print "NULL" t=t-1 sys.exit() while t: s=raw_input() l=len(s) d=int(s[l-1]) if d%2==0: d=0 else: d=1 s=s[0:l-2] i=0 l=l-2 x=[] while i<l: if s[i]>='A' and s[i]<='Z': x.append(s[i]) i=i+1 x=sorted(x) if len(x)==0: ...
Peter visited Big Bazar and he was very delighted to know the Loot offer on marbles. The offer was that, If he buys a marble with price p', then he will get all other marbles whose price lies between [pβ€²,pβ€²+4] (both inclusive) in free of cost. Suppose there are N marbles and their prices are represented by an array P=[...
n=int(raw_input()) arr=map(int,raw_input().split()) arr=sorted(arr) count=1 start=arr[0] end=arr[0]+4 for i in range(1,n): if arr[i]<=end: continue start=arr[i] end=start+4 count+=1 print count
Given are N integers A_1,\ldots,A_N. Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7). Constraints * 2 \leq N \leq 2\times 10^5 * 0 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 \ldot...
s =0 r =0 n = int(input()) l = list( map( int , input().split() )) for e in l: r += e*s s += e mod =int(1e9+7) print( r %mod )
There are N cities numbered 1 to N, connected by M railroads. You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket. The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare....
n,m,s = map(int,input().split()) import collections g = [[] for _ in range(n+1)] dic = {} for _ in range(m): u,v,a,b = map(int,input().split()) g[u].append(v) g[v].append(u) dic[(u,v)]=(a,b) dic[(v,u)]=(a,b) arr = [[0,0]]+[list(map(int,input().split())) for _ in range(n)] cost =[[float('inf')]*2501 ...
We have N bricks arranged in a row from left to right. The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it. Among them, you can break at most N-1 bricks of your choice. Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of t...
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0; i<(n); i++) int n, a, c = 1; int main(){ scanf("%d", &n); rep(i,n){ scanf("%d", &a); if(a == c) c++; } printf("%d\n", c == 1 ? -1 : n-c+1); }
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2. Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r. Constraints * 1 \leq r \leq 100 * r is an integer. Input Input is given from Standard Input in the following format: r Output ...
x = int(input()) print(3*pow(x,2))
Takahashi likes the sound when he buys a drink from a vending machine. That sound can be heard by spending A yen (the currency of Japan) each time. Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time. How many times will he h...
A,B,C = map(int,input().split()) print(min((B//A),C))
You are given strings S and T consisting of lowercase English letters. You can perform the following operation on S any number of times: Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1. Determine if S and T can ...
#include<bits/stdc++.h> using namespace std; int fr1[150]; int fr2[130]; int main() { string s,t; cin>>s>>t;int y=1; map<char,int> mp; for(int i=0;i<s.size();i++) { fr1[s[i]]++; fr2[t[i]]++; if(fr1[s[i]]!=fr2[t[i]]) { y=0; break; } } if(y==0)...
We have an undirected weighted graph with N vertices and M edges. The i-th edge in the graph connects Vertex U_i and Vertex V_i, and has a weight of W_i. Additionally, you are given an integer X. Find the number of ways to paint each edge in this graph either white or black such that the following condition is met, mo...
import sys input=sys.stdin.readline def find_parent(x): y=parent[x] if y<0: return x parent[x]=find_parent(y) return parent[x] def connect(a,b): c=find_parent(a) d=find_parent(b) if c==d: return if parent[c]<parent[d]: parent[c]+=parent[d] parent[d]=c ...
We will say that two integer sequences of length N, x_1, x_2, ..., x_N and y_1, y_2, ..., y_N, are similar when |x_i - y_i| \leq 1 holds for all i (1 \leq i \leq N). In particular, any integer sequence is similar to itself. You are given an integer N and an integer sequence of length N, A_1, A_2, ..., A_N. How many ...
n = int(input()) a = list(map(int, input().split())) evens = len(list(filter(lambda x: x % 2 == 0, a))) print(3 ** n - 2 ** evens)
Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below: * Each person simultaneously divides his cookies in half and gives one half to each of the other two persons. This action will be repeated until there is a person ...
A, B, C = map(int, input().split()) if A == B == C: print(0 if A%2 else -1) else: cnt = 0 while A%2==0 and B%2==0 and C%2==0: A, B, C = (B+C)//2, (C+A)//2, (A+B)//2 cnt += 1 print(cnt)
Construct an N-gon that satisfies the following conditions: * The polygon is simple (see notes for the definition). * Each edge of the polygon is parallel to one of the coordinate axes. * Each coordinate is an integer between 0 and 10^9, inclusive. * The vertices are numbered 1 through N in counter-clockwise order. * ...
/** * author: tourist * created: 27.11.2019 08:48:17 **/ #include <bits/stdc++.h> using namespace std; struct Point { int x; int y; }; void MoveX(vector<Point>& p, int x) { for (auto& q : p) { if (q.x >= x) { ++q.x; } } } void MoveY(vector<Point>& p, int y) { for (auto& q : p...
Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L. She will concatenate all of the strings in some order, to produce a long string. Among all strings that she can produce in this way, find the lexicographically smallest one. Here, a string s=s_1s_2s_3...s_n is lexicographically sma...
print("".join(sorted([input()for _ in[""]*int(input().split()[0])])))
Create a program that takes two dates as input and outputs the number of days between the two dates. Date 1 (y1, m1, d1) is the same as or earlier than date 2 (y2, m2, d2). Date 1 is included in the number of days, not date 2. Also, take the leap year into account when calculating. The leap year conditions are as foll...
#include <iostream> #include <sstream> #include <vector> #include <list> #include <string> #include <set> #include <map> #include <stack> #include <queue> #include <algorithm> #include <numeric> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> using namespace std; int main() ...
Yuta is addicted to the popular game "Beat Panel" at a nearby arcade. The game consists of a total of 16 panel-type buttons, 4x4, arranged in a grid as shown. <image> As shown in the figure, the buttons are arranged in the order of button 1, button 2,…, button 16 from the upper left to the lower right. In the game, ...
#include<iostream> #include<algorithm> using namespace std; int dp[100][65536], c[30][16], d[30][16]; int n, m, p[16], q[16]; int _count() { int cnt2 = 0; for (int i = 0; i < 16; i++) { cnt2 += q[i] * (1 << i); }return cnt2; } int main() { while (true) { for (int i = 0; i < 100; i++) { for (int j = 0; j < 65536; ...
problem Create a program that counts the number of consecutive JOI or IOI characters in a given character string. The character string consists only of uppercase letters of the alphabet. For example, the character string "JOIOIOI" in the figure below contains JOI in one place and IOI in two places. <image> input ...
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string s, comp[2] = { "JOI", "IOI" }; while (cin >> s) { for (int k = 0; k < 2; ++k) { int ans = 0; for (int i = 0; (i = s.find(comp[k], i)) != string::npos; ++i) { ans++; } cout << ans...
Brave Ponta has finally arrived at the final dungeon. This is a dark wilderness in front of the fort of the evil emperor Boromos, with fairly strong monsters guarding their territories. <image> Figure 1: Wilderness As shown in Fig. 1, the wilderness is represented by a 4 Γ— 4 square region with the southwest as the ...
#include <bits/stdc++.h> using namespace std; #define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl #define repi(i,a,b) for(int i=int(a);i<int(b);i++) #define peri(i,a,b) for(int i=int(b);i-->int(a);) #define rep(i,n) repi(i,0,n) #define per(i,n) peri(i,0,n) #define all(c) begin(c),end(c) #define mp mak...
Don't Cross the Circles! There are one or more circles on a plane. Any two circles have different center positions and/or different radiuses. A circle may intersect with another circle, but no three or more circles have areas nor points shared by all of them. A circle may completely contain another circle or two circl...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> P; typedef pair<int,P> P1; typedef pair<P,P> P2; #define pu push #define pb push_back #define mp make_pair //#define eps 1e-7 #define INF 1000000000 #define fi first #define sc second #define rep(i,x) for(int i=0;i<x;i++) #define ...
Suppose that there are some light sources and many spherical balloons. All light sources have sizes small enough to be modeled as point light sources, and they emit light in all directions. The surfaces of the balloons absorb light and do not reflect light. Surprisingly in this world, balloons may overlap. You want th...
#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>...
Backgorund The super popular game "Puzzle & Hexagons" has finally been released. This game is so funny that many people are addicted to it. There were a number of people who were certified as addicted by doctors because of their excessive enthusiasm. Volunteers from around the world have created a "Puzzle & Hexagons" ...
#include <bits/stdc++.h> using namespace std; #define for_(i,a,b) for(int i=a;i<b;++i) #define for_rev(i,a,b) for(int i=a;i>=b;--i) #define rep(i,n) for(int i=0;i<(n);++i) #define allof(a) a.begin(),a.end() #define minit(a,b) memset(a,b,sizeof(a)) #define size_of(a) (int)a.size() typedef long long lint; typedef doubl...
The electronics division in Ishimatsu Company consists of various development departments for electronic devices including disks and storages, network devices, mobile phones, and many others. Each department covers a wide range of products. For example, the department of disks and storages develops internal and externa...
#include <stdio.h> #include <assert.h> #include <vector> #include <algorithm> #include <utility> using namespace std; #define rep(i, n) for (int i = 0; i < (int)(n); i++) #define mp make_pair #define NUM (120000) int N, M, Q, Y[NUM]; vector<int> ls[NUM]; pair<int, int> ord[NUM]; int hi[NUM], p[NUM], c[NUM], f[NUM], b[...
You survived several months of exam wars and were able to enter ICPC University on a sunny day. On the day of admission, there was an enthusiastic recruitment of circles on the campus of the university, and you received a large number of pamphlets and returned. When you return to your room, you find one of the pamphlet...
while True: N=int(input()) if(N==0): break ans=0 for i in range((N//2)+1,0,-1): SUM=i k=i-1 while SUM<=N and k>0: SUM+=k if SUM==N: ans+=1 k-=1 print(ans)
Time Limit: 8 sec / Memory Limit: 64 MB Example Input 100 A=malloc(10) B=clone(A) free(A) Output 0
#include <stdio.h> #include <cmath> #include <algorithm> #include <cfloat> #include <stack> #include <queue> #include <vector> #include <string> #include <iostream> #include <set> #include <map> #include <time.h> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 100000...
ICPC World Finals Day 6 Russian Constructivism is an art movement in the Soviet Union that began in the mid-1910s. Inspired by such things, Tee, who had been in Country R for a long time, decided to create a cool design despite the rehearsal of the ICPC World Finals. Mr. Tee says: "A circle and a line segment are enou...
#include <algorithm> #include <cstdlib> #include <iostream> #include <vector> using namespace std; template<class T> inline void chmax(T& a, const T& b) { if(b > a) a = b; } typedef int type; const type INIT = 0; class segment_tree { private: int n; vector<type> dat; inline type function(type a, type b) const { ...
Example Input 2 2 1 2 0 3 4 1 Output 2
#include<bits/stdc++.h> #include<unordered_map> using namespace std; const int N=1000100,P=1e9+9; #define X first #define Y second int a[18],b[18],c[18],dp[N]; unordered_map<int,int>f,sz; int main() { memset(dp,-1,sizeof(dp)); int n,m,ans=0; scanf("%d%d",&n,&m); dp[0]=1; for(int i=1;i<=n;i++)dp[i]=1ll*(3*i-1)*(3*i...
Hey! There is a new building with N + 1 rooms lined up in a row. Each room is a residence for one person, and all rooms are currently vacant, but N new people are scheduled to live here from next month. Therefore, when they start living, one room becomes vacant. As a landlord, you want to propose many room allocation...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; const int mod = 1000000007; struct Mod { public: int num; Mod() : Mod(0) { ; } Mod(long long int n) : num((n % mod + mod) % mod) { static_assert(mod<INT_MAX / 2, "mod is too big, please ma...
Problem Statement Recently, AIs which play Go (a traditional board game) are well investigated. Your friend Hikaru is planning to develop a new awesome Go AI named Sai and promote it to company F or company G in the future. As a first step, Hikaru has decided to develop an AI for 1D-Go, a restricted version of the ori...
#include <bits/stdc++.h> using namespace std; int main(){ int L; string S; cin >> L >> S; S = "." + S + "."; int ans = 0; for(int i=1; i<=L; i++){ if(S[i] != '.') continue; bool ng = true; for(int d : {-1, 1}) for(int j=i+d; ; j+=d){ if(S[j] == 'B'){ ...
Does the card fit in a snack? (Are Cards Snacks?) square1001 You have $ N $ cards. Each of these cards has an integer written on it, and the integer on the $ i $ th card is $ A_i $. square1001 Your random number today is $ K $. square1001 You want to choose some of these $ N $ cards so that they add up to $ K $. E8...
#include <bits/stdc++.h> using namespace std; typedef long long ll; //#include <boost/multiprecision/cpp_int.hpp> //typedef boost::multiprecision::cpp_int ll; typedef long double dd; #define i_7 (ll)(1E9+7) //#define i_7 998244353 #define i_5 i_7-2 ll mod(ll a){ ll c=a%i_7; if(c>=0)return c; return c+i_7; }...
Constraints * 1 ≀ |V| ≀ 100 * 0 ≀ |E| ≀ 9900 * -2 Γ— 107 ≀ di ≀ 2 Γ— 107 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E). |V| |E| s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named wi...
# -*- coding: utf-8 -*- import sys import os import pprint """???????????Β£????????????????????Β¨??????""" MAX = 100 d = [[None for i in range(MAX)] for j in range(MAX)] for i in range(MAX): for j in range(MAX): if i == j: d[i][j] = 0 else: d[i][j] = float('inf') #fd = os...
Given an array A[1..N] of N non-negative integers, you need to find the median of the array. The median of an array is the middle element in its sorted order. If N is even, choose the (N/2)^th element in the sorted order. Input The first line contains N, the number of integers in the array. The next line has N integer...
n=int(input()) a=raw_input().split() l=[0]*n l=[int(i) for i in a] l.sort() #print l if not n%2: j=n/2 print l[j-1] else: print l[(n/2)]
Problem description. Chef decides to distribute fancy stationary among kids. Chef has collection of erasers and pencils . Each kid needs to be given a pencil and eraser. Your job is to help find Chef how many kids can get the stationary and how many min pencils or erasers the chef will need to clear the stock that is l...
t = int(raw_input()) for i in range(0, t): string = raw_input() e = 0 p = 0 for j in range(0, len(string)): if string[j] == 'E': e += 1 else: p += 1 print min(e, p), max(e, p) - min(e, p)
A holiday weekend is coming up, and Hotel Bytelandia needs to find out if it has enough rooms to accommodate all potential guests. A number of guests have made reservations. Each reservation consists of an arrival time, and a departure time. The hotel management has hired you to calculate the maximum number of guests t...
t = input() for i in range(0,t): n = input() l1 = raw_input() l1 = l1.split() for j in range(0,n): l1[j] = int(l1[j]) l2 = raw_input() l2 = l2.split() for j in range(0,n): l2[j] = int(l2[j]) l = [0]*1001 for j in range(0,n): for k in range(l1[j],l2[j]): ...
You are standing near a very strange machine. If you put C cents in the machine, the remaining money in your purse will transform in an unusual way. If you have A dollars and B cents remaining in your purse after depositing the C cents, then after the transformation you will have B dollars and A cents. You can repeat t...
cases = int(raw_input()) for _ in xrange(cases): A, B, C = map(int, raw_input().split()) maxValue = A * 100 + B maxSteps = 0 steps = 0 while steps < 10000: if B < C: A -= 1 B = 100 + B - C else: B -= C if A < 0: break ...
Alice and Bob play the following game : There are N piles of stones with Si stones in the ith pile. Piles are numbered from 1 to N. Alice and Bob play alternately, with Alice starting. In a turn, the player chooses any pile i which has atleast i stones in it, and removes exactly i stones from it. The game ends when ...
for i in range(input()): j=input() a=map(int,raw_input().split()) b=[int(a[j]/(j+1)) for j in range(len(a))] if sum(b)%2==0: print "BOB" else: print "ALICE"
These days, Sid and Jake are learning about number theory. They have just visited the zoo and during the visit they have counted(yes, they are superb at counting :) ) the number of animals at the zoo. Now, after visiting the zoo, Sid is saying that f is a factor of the total number of animals at the zoo and Jake is say...
t=raw_input() t=int(t) while t>0: f,m=raw_input().split() f=int(f); m=int(m); if m%f==0: print "CORRECT" else: print "WRONG" t=t-1
Notice: unusual memory limit! After the war, destroyed cities in the neutral zone were restored. And children went back to school. The war changed the world, as well as education. In those hard days, a new math concept was created. As we all know, logarithm function can be described as: $$$ log(p_1^{a_1}p_2^{a_2}......
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const long long INF = 0x3f3f3f3f3f3f3f3fLL; const double pi = acos(-1.0); const int maxn = 100000 + 10; const int mod = 1e9 + 7; inline char _getchar() { static const int BUFSIZE = 100001; static char buf[BUFSIZE]; static char *psta = buf, ...
Recently Monocarp got a job. His working day lasts exactly m minutes. During work, Monocarp wants to drink coffee at certain moments: there are n minutes a_1, a_2, ..., a_n, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). ...
#Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): ...
Colossal! β€” exclaimed Hawk-nose. β€” A programmer! That's exactly what we are looking for. Arkadi and Boris Strugatsky. Monday starts on Saturday Reading the book "Equations of Mathematical Magic" Roman Oira-Oira and Cristobal Junta found an interesting equation: a - (a βŠ• x) - x = 0 for some given a, where βŠ• stands for...
def countSetBits(n): if(n==0): return(0) else: return((n&1)+countSetBits(n>>1)) t=int(input()) for _ in range(0,t): a=int(input()) x=countSetBits(a) print(pow(2,x))
Petya collects beautiful matrix. A matrix of size n Γ— n is beautiful if: * All elements of the matrix are integers between 1 and n; * For every row of the matrix, all elements of this row are different; * For every pair of vertically adjacent elements, these elements are different. Today Petya bought a b...
#include <bits/stdc++.h> using namespace std; long long n, mat[2021][2021], dp[2021], f[2021][2021]; long long fac[2021], sum[2][2021], vis[2021], vis2[2021]; void read(long long& x) { x = 0; char c = getchar(); for (; c > '9' || c < '0'; c = getchar()) ; for (; c >= '0' && c <= '9'; c = getchar()) x = x * ...
Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle. Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequen...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast", "unroll-loops", "omit-frame-pointer", "inline") #pragma GCC option("arch=native", "tune=native", "no-zero-upper") #pragma GCC target("avx2") using namespace std; const int INF = 0x3f3f3f3f; const int N = 110; int g[N][N]; int ans, cnt[N], n, m, vis[N]; map<string, ...
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha...
s=input() h1=int(s[:2]) m1=int(s[3:]) s=input() h2=int(s[:2]) m2=int(s[3:]) #print(h1,m1,h2,m2) m=(m2-m1)+(h2-h1)*60; ma=(m1+m/2)%60; ha=(h1+(m1+m/2)/60); print('0'*(2-len(str(int(ha))))+str(int(ha))+':'+'0'*(2-len(str(int(ma))))+str(int(ma)))
Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree. A tree is a connected graph without cycles. A rooted tree has a special vertex ca...
#include <bits/stdc++.h> using namespace std; const long long mod = 100000007700000049; const long long MAXN = 3e5 + 5; int op[MAXN]; vector<int> son[MAXN]; int val[MAXN]; int dfs(int pos) { int ans, i; if (val[pos] != -1) return val[pos]; if (op[pos] == 0) { ans = 0; for (i = 0; i < son[pos].size(); i++)...
At first, there was a legend related to the name of the problem, but now it's just a formal statement. You are given n points a_1, a_2, ..., a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible. The function f_k(x) can be described in the following way: ...
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): for _ in range(read_int()): n, k...
You are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting...
for _ in range(int(input())): n,m=map(int,input().split()) g=[input() for _ in range(n)] a=[0]*n b=[0]*m for i in range(n): for j in range(m): if '*'==g[i][j]: a[i]+=1 b[j]+=1 ans=0 for i in range(n): for j in range(m): ans=max(ans,a[i]+b[j]-(g[i][j]=='*')) print(n+m-...
This is a harder version of the problem. In this version, n ≀ 7. Marek is working hard on creating strong test cases to his new algorithmic problem. Do you want to know what it is? Nah, we're not telling you. However, we can tell you how he generates test cases. Marek chooses an integer n and n^2 integers p_{ij} (1 ≀...
import java.io.*; import java.util.*; public class F2 { int mod = 1000000007; int[][] prob; public static int invInt(int a, int mod) { int res = 1; int b = mod - 2; while (b > 0) { if ((b & 1) != 0) { res = (int) ((long) res * a % mod); } ...
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out. You are given two strings s and t of the same length n. Their characters are numbered from 1 to n from left to right (i.e. from...
#include <bits/stdc++.h> using namespace std; bool check(string a, string b) { sort(a.begin(), a.end()); sort(b.begin(), b.end()); return a == b; } int main() { long long int t, i, j, k, l, n, m, a, b, c, x, y; cin >> t; while (t--) { cin >> n; string s, p; cin >> s >> p; if (!check(s, p)) {...
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ...
#include <bits/stdc++.h> using namespace std; const int max_n = 200111, inf = 1000111222; string s; char buf[max_n]; string read_str() { scanf("%s", buf); return buf; } int main() { int t; cin >> t; while (t--) { s = read_str(); vector<int> ans; for (int i = 0; i < s.size(); ++i) { if (i + 4...
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≀ x ≀ s, buy food that costs exactly x burles and obtain ⌊x/10βŒ‹ burles as a cashback (in other words, Mishka ...
#1296B for i in range(int(input())): n=input() b=0 z=0 while (len(n)>1): b=int(n[0])*(10**(len(n)-1)) z+=b n=str(int(n[1:])+b//10) z+=int(n) print(z)
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≀ ti ≀ 10). Of course, one number can be assigned to any number of cust...
#include <bits/stdc++.h> using namespace std; map<int, int> mp; int a[100100]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i], mp[a[i]]++; long long Ans = 0; for (int i = 0; i < n; i++) { mp[a[i]]--; Ans += mp[a[i] * -1]; } cout << Ans; return 0; }
You have a tree of n vertices. You are going to convert this tree into n rubber bands on infinitely large plane. Conversion rule follows: * For every pair of vertices a and b, rubber bands a and b should intersect if and only if there is an edge exists between a and b in the tree. * Shape of rubber bands must be ...
#include <bits/stdc++.h> using namespace std; const int MN = 100005, inf = 1000000005, mod = 1000000007; const long long INF = 1000000000000000005LL; int dp[2][MN]; pair<int, int> naj[4][MN]; vector<int> G[MN]; int ans; void dfs_pre(int x, int p) { int sons = G[x].size() - (p != 0); for (auto v : G[x]) if (v !=...
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not. You are given an array a of n (n is even) positive in...
for i in range(int(input())): k=int(input()) a=list(map(int,input().split())) a.sort() c,d=0,0 i=1 e=0 for j in range(len(a)): if(a[j]%2==0): c+=1 else: d+=1 if(c%2==0 and d%2==0): print("YES") else: c,d=0,0 while(i<len(...
There are n warriors in a row. The power of the i-th warrior is a_i. All powers are pairwise distinct. You have two types of spells which you may cast: 1. Fireball: you spend x mana and destroy exactly k consecutive warriors; 2. Berserk: you spend y mana, choose two consecutive warriors, and the warrior with gr...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] ...
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that: * 1 ≀ i < j < k < l ≀ n; * a_i = a_k and a_j = a_l; Input The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. The first line of each test case contains a single integer n (4 ≀ n ≀ ...
#include <bits/stdc++.h> using namespace std; int main() { int t, n; cin >> t; while (t--) { cin >> n; int arr[n]; vector<vector<int>> v(n + 1, vector<int>()); for (int i = 0; i < n; i++) { cin >> arr[i]; v[arr[i]].push_back(i); } long long ans = 0; for (int i = 1; i < n; i...
Mark and his crew are sailing across the sea of Aeolus (in Greek mythology Aeolus was the keeper of the winds). They have the map which represents the NxM matrix with land and sea fields and they want to get to the port (the port is considered as sea field). They are in a hurry because the wind there is very strong and...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); } return x * f; } const int N = 2e2 + 10, M = 2...
This is an interactive problem. You are given a tree β€” connected undirected graph without cycles. One vertex of the tree is special, and you have to find which one. You can ask questions in the following form: given an edge of the tree, which endpoint is closer to the special vertex, meaning which endpoint's shortest ...
#include <bits/stdc++.h> using namespace std; const int Maxn = 100; int n; bool t[Maxn + 5], vis[Maxn + 5]; struct Bit { bitset<Maxn + 5> a; int id; friend bool operator<(Bit a, Bit b) { for (int i = n; i >= 0; i--) { if (a.a[i] != b.a[i]) { return a.a[i] < b.a[i]; } } return 0; ...
// We decided to drop the legend about the power sockets but feel free to come up with your own :^) Define a chain: * a chain of length 1 is a single vertex; * a chain of length x is a chain of length x-1 with a new vertex connected to the end of it with a single edge. You are given n chains of lengths l_1,...
#include<bits/stdc++.h> #define ll long long const int inf=1e9; using namespace std; int v[200005],aux[200005]; int main() { //freopen(".in","r",stdin); //freopen(".out","w",stdout); int n,k; scanf("%d%d",&n,&k); int i; for(i=1;i<=n;i++) scanf("%d",&v[i]); sort(v+1,v+n+1); revers...
On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper. A permutation p is written from left to right on the paper. First Qingshan chooses an integer index x (1≀ x≀ n) and tells it to Daniel. After that, D...
#include <bits/stdc++.h> #define pb push_back #define fst first #define snd second #define fore(i,a,b) for(int i=a,ggdem=b;i<ggdem;++i) #define SZ(x) ((int)x.size()) #define ALL(x) x.begin(),x.end() #define mset(a,v) memset((a),(v),sizeof(a)) #define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0) using namespace st...
At the foot of Liyushan Mountain, n tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky. The i-th tent is located at the point of (x_i, y_i) and has a weight of w_i. A tent is important ...
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for(int i = a; i < (b); ++i) #define trav(a, x) for(auto& a : x) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<pii> vpii; ...
Note that the differences between easy and hard versions are the constraints on n and the time limit. You can make hacks only if both versions are solved. AquaMoon knew through foresight that some ghosts wanted to curse tourists on a pedestrian street. But unfortunately, this time, these ghosts were hiding in a barrie...
#include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> #include <cstring> #include <list> #include <cassert> #include <climits> #inclu...
This problem is about imaginary languages BHTML and BCSS, which slightly resemble HTML and CSS. Read the problem statement carefully as the resemblance is rather slight and the problem uses very simplified analogs. You are given a BHTML document that resembles HTML but is much simpler. It is recorded as a sequence of ...
#include <bits/stdc++.h> using namespace std; ifstream fin("input.in"); ofstream fout("output.out"); stack<bool> S; pair<string, bool> P[1000005]; string str; int pind; void add(string str) { if (str[0] == '/') { str = str.substr(1); P[++pind] = make_pair(str, 0); } else if (str[str.size() - 1] == '/') { ...
You've gotten an n Γ— m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected. A set of painted squares is called connected, if for every two s...
#include <bits/stdc++.h> using namespace std; vector<int> adj[2505]; bool visited[2505]; set<int> a_points; int tin[2505]; int low[2505]; int timer; void dfs(int u, int p) { visited[u] = true; tin[u] = low[u] = timer++; int child = 0; for (int v : adj[u]) { if (p == v) { continue; } else if (visit...
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves...
n = int(input()) g = [] for i in range(n): t = input().split() g.append([ int(t[0]), int(t[1]), False ]) def visita(i): g[i][2] = True for j in range(n): if g[j][2] == False and (g[i][0] == g[j][0] or g[i][1] == g[j][1]): visita(j) cnt = -1 for i in range(n): if g[i][2] == Fals...
Overall there are m actors in Berland. Each actor has a personal identifier β€” an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information fo...
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { @SuppressWarnings("unchecked") private void solve() throws IOException { int m = nextInt(); int ...
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good. Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions: * The sequence is strictly increasing, i.e. xi < xi + 1 f...
//package CF; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws Exc...
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≀ pi ≀ n). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou...
#include <bits/stdc++.h> using namespace std; const int maxn = 1020; const int maxx = 10000; const int MOd = 1e9 + 7; const int K = 750; int n, k; int dn[maxn][maxn]; int mul(int a, int b) { return (long long)a * b % MOd; } int main() { scanf("%d %d", &n, &k); int t = k; for (int i = 1; i <= n - k; i++) t = mul(t...
Sereja placed n points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the Ox axis at an angle of 45 degrees and the maximum distance from the points to the straight lines were minimum. In this problem we consider the di...
#include <bits/stdc++.h> using namespace std; long long n; struct node { long long x, y; } d[100005]; bool cmp(node x, node y) { return x.x < y.x; } long long a[100005][15]; long long chk(long long x) { for (long long i = 1, j = 1; i <= n; i++) { while (j < n && d[j + 1].x - d[i].x <= x) j++; if (max(a[i - ...
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
n,m = map(int,input().split()) f = list(map(int,input().split())) f.sort() a = [] for i in range(m-n+1): a.append(f[i+n-1]-f[i]) print(min(a))
After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it N rows with M trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the j-th tree in the i-th row would have the coordinates of (i, j). However a terrible thing happened and...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedR...
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of mi...
#include <bits/stdc++.h> using namespace std; long long n, a, t, sum; void output(long long x) { if (x < 0) { putchar('-'); x = -x; } long long len = 0, data[10]; while (x) { data[len++] = x % 10; x /= 10; } if (!len) data[len++] = 0; while (len--) putchar(data[len] + 48); putchar('\n');...
You have two rooted undirected trees, each contains n vertices. Let's number the vertices of each tree with integers from 1 to n. The root of each tree is at vertex 1. The edges of the first tree are painted blue, the edges of the second one are painted red. For simplicity, let's say that the first tree is blue and the...
#include <bits/stdc++.h> using namespace std; template <class C> void mini(C &a4, C b4) { a4 = min(a4, b4); } template <class C> void maxi(C &a4, C b4) { a4 = max(a4, b4); } template <class T1, class T2> ostream &operator<<(ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second ...
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
#!/usr/bin/env python3 a=list(map(int,input().split())) s=input() print(a[0]*s.count('1') + a[1]*s.count('2') + a[2]*s.count('3') + a[3]*s.count('4'))
Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. <im...
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.*; public class C { private static final int mod = (int)1e9+7; final Random random = new Random(0); final IOFast io = new IOFast(); /// MAIN CODE int n, m; int[] times; SimpleAdjListGraph g; int[] path; int[] depth; ...
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
#include <bits/stdc++.h> using namespace std; int main() { int m, n, i, x; cin >> n >> m; if (n < m) { cout << -1; return 0; } if (n == m) { cout << n; return 0; } if (n % 2 == 0) { x = n / 2; if (x % m == 0) { cout << x; return 0; } for (i = x + 1; i <= n; i++)...
Vasya studies positional numeral systems. Unfortunately, he often forgets to write the base of notation in which the expression is written. Once he saw a note in his notebook saying a + b = ?, and that the base of the positional notation wasn’t written anywhere. Now Vasya has to choose a base p and regard the expressio...
#include <bits/stdc++.h> using namespace std; template <typename T, typename T1> ostream &operator<<(ostream &out, pair<T, T1> obj) { out << "(" << obj.first << "," << obj.second << ")"; return out; } template <typename T, typename T1> ostream &operator<<(ostream &out, map<T, T1> cont) { typename map<T, T1>::cons...
A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network. We know that each server takes one second to recompress a one ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map.Entry; import java.util.TreeMap; public class VK_2015_Q2_D { static TreeMap<Long, Integer> runningJobs = new TreeMap<>(); static int[][] videos; static int serversCnt; static int videosCnt; static in...