input
stringlengths
29
13k
output
stringlengths
9
73.4k
In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission. The resolution #666 says that a white ...
#include <bits/stdc++.h> using namespace std; const int MAX = 1e6 + 10; const long long MOD = 1e9 + 7; const int INF = 0x3f3f3f3f; const long long LLINF = 0x3f3f3f3f3f3f3f3f; const long double EPS = 1e-7; const long double PI = acos(-1); bool eq(long double a, long double b) { return fabsl(a - b) <= EPS; } struct point...
Btoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt ...
#!/usr/bin/env python #-*- coding:utf-8 -*- import sys, math, random, operator from string import ascii_lowercase from string import ascii_uppercase from fractions import Fraction, gcd from decimal import Decimal, getcontext from itertools import product, permutations, combinations from Queue import Queue, PriorityQue...
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k). For example, if n = 5, a possible A is {5, 1, 4...
#include <bits/stdc++.h> using namespace std; int main() { int n, k; int a[1001]; int b[1001]; cin >> n >> k; for (int i = 1; i <= n; i++) cin >> b[i]; for (int i = 1; i <= n; i++) a[i] = i; int p = n; for (int x = n - k; x > 0; x--) { while (b[x]) { for (int y = 1; y < n; y++) if (a[y...
You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x). Input The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers ...
# @oj: codeforces # @id: hitwanyang # @email: 296866643@qq.com # @date: 2020-08-20 23:46 # @url:https://codeforc.es/problemset/problem/702/B import sys,os from io import BytesIO, IOBase import collections,itertools,bisect,heapq,math,string from decimal import * # region fastio BUFSIZE = 8192 BUFSIZE = 8192 class Fa...
There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes. At...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); const int MOD = 1000 * 1000 * 1000 + 7; const int MAX = 100017; int n, m, k; int x, y; long long gcd(long long a, long long b, long long& x, long long& y) { if (a == 0) { x = 0; y = 1; return b; } long long x1, frgrwegreg; l...
The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s. Igor is at the point x1. He should reach the point...
#include <bits/stdc++.h> using namespace std; int main() { int n, x1, x2, t1, t2, p, d; scanf("%d%d%d%d%d%d%d", &n, &x1, &x2, &t1, &t2, &p, &d); int man = abs(x2 - x1) * t2, s = 0, ans = 0; if (d > 0) { if (p <= x1 && x1 < x2) s = x2 - p; else if (x1 <= p && p <= x2) s = 2 * (n - p) + 2 * p ...
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. In...
#include <bits/stdc++.h> using namespace std; const int dx[4] = {1, 0, 0, -1}, dy[4] = {0, -1, 1, 0}; int n, m, k, sti, stj, d[1001][1001]; string s[1001], add = "DLRU"; bool valid(int x, int y) { return (x >= 0 && x < n && y >= 0 && y < m && s[x][y] != '*'); } int main() { ios::sync_with_stdio(false); cin.tie(0)...
Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them. The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located i...
#include <bits/stdc++.h> using namespace std; double INF = 1e100; double EPS = 1e-12; struct PT { double x, y; PT() {} PT(double x, double y) : x(x), y(y) {} PT(const PT &p) : x(p.x), y(p.y) {} PT operator+(const PT &p) const { return PT(x + p.x, y + p.y); } PT operator-(const PT &p) const { return PT(x - p...
You are given an undirected graph consisting of n vertices. Initially there are no edges in the graph. Also you are given q queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the g...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; map<pair<int, int>, int> ma; int n, q; int f[N], d[N], st[N], top, str[N], ran[N]; inline int read() { char ch = getchar(); int x = 0, f = 1; while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' &...
There are n castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself. Sir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has k...
#include <bits/stdc++.h> using namespace std; int adj[42][42]; int dp[1 << 21]; int c1[42], c2[42], c3[43]; int max_count; int n1, n2, n; int count_bit(int b) { int c = 0; for (int i = b; i; i -= (i & -i)) c++; return c; } int main() { int k, v; scanf("%d %d", &n, &k); for (int i = 0; i < n; i++) { for ...
We all know the problem about the number of ways one can tile a 2 × n field by 1 × 2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes. You are given a 4 × n rectangular fie...
#include <bits/stdc++.h> int main() { int n; scanf("%d", &n); if (n & 1) { int l = (n - 1) / 2; printf("a"); for (int i = 0; i < l; i++) printf(i & 1 ? "bb" : "cc"); puts(""); printf("a"); for (int i = 0; i < l; i++) printf(!(i & 1) ? "bb" : "cc"); puts(""); for (int i = 0; i < l; ...
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams. After practice competition, participant number i got a score of ai. Team s...
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import s...
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person. You are given the first and ...
s=input().split(" ") m=s[0] j=s[1] list=[] for x in range(len(m)): p=m[0:x+1] p=p+j[0] list.append(p) list.sort() print(list[0])
Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor ...
#include <bits/stdc++.h> #pragma GCC optimize("O3") using namespace std; inline long long getint() { long long _x = 0, _tmp = 1; char _tc = getchar(); while ((_tc < '0' || _tc > '9') && _tc != '-') _tc = getchar(); if (_tc == '-') _tc = getchar(), _tmp = -1; while (_tc >= '0' && _tc <= '9') _x *= 10, _x += (_...
The Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independent...
#include <bits/stdc++.h> using namespace std; int n; pair<int, int> inp[210000]; int a, b, c; char t; map<pair<int, int>, int> arr; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { cin >> t >> a >> t >> b >> t >> t >> c; int gd = gcd(a ...
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction. A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction ...
s0 = raw_input() n = int(s0) for i in xrange(n): s = raw_input() sa = s.split() x, y, b = int(sa[0]), int(sa[1]), int(sa[2]) pb = b for k in range(7): pb = (pb * pb) % y if (x * pb) % y == 0: print "Finite" else: print "Infinite"
Dilku was thinking about the first time he met his girl... It was indeed a walk to remember. The romantic weather and her silly talks. He was completely mesmarized. Those were the days!.. Today is his girl's birthday and he wants to make it special for her. He wants to again take her on a "special walk" that they ...
Graph = {} N, M = map(int, raw_input().split()) for i in xrange(1, N+1): Graph[i] = [] for i in xrange(M): u, v = map(int, raw_input().split()) Graph[u].append(v) marked = set() visit_stack = [] visit_index = {} parent = {} dfsPos = 1 finishingTime = 1 dfsNum = {} finsihTime = {} oReps = [] oNodes =...
Andi and Bob were friends since childhood days. But, as they grew up Bob started behaving weird and this used to irritate Andi. Once, while Andi took a break after typing a large program Bob came from nowhere and swapped some alphabet keys on Andi's keyboard. Andi got very angry on seeing this and decided to end their...
no_of_replace_chars =int(raw_input()) replace_strings = list() for x in range(no_of_replace_chars): replace_strings.append(raw_input()) s = raw_input() d = dict() for key, value in enumerate(s): if d.has_key(value): d[value].append(key) else: d[value] = [key] temp = "temp" for r_str in replace_strings: r_s = ...
Little Deepu and Little Kuldeep are world renowned criminals. But, they are not bad people at heart. (Oh, they are...) Anyway, their occupation is to smuggle drugs from one place to another. And both of them are partners in this occupation of theirs. But, now Little Deepu is an amateur drug seller, while Little Kuld...
T= int(raw_input()) for _ in xrange(T): N = int(raw_input()) dic={} for __ in xrange(N): box = int(raw_input()) if box in dic: dic[box]+=1 else: dic[box]=1 key,val = max(dic.iteritems(),key=lambda x:x[1]) print val
Rahul has recently been obsessed with mathematics, and spends most of his time reading the research notes of his equally eccentric math professor. On one of the pages of the research notes, Rahul finds a scribble that says, " the number of ways to represent a number as sum of four squares would be the ultimate answer t...
import math def evennum(x): div= getAllDivisors(x) nfs = sum(div) print nfs*24 def oddnum(x): divisor = getAllDivisors(x) nfs = sum(divisor) print 8*nfs def getAllDivisors(x): sqrot = long(math.sqrt(x)) divi = [] for i in range(1, sqrot + 1): if n%i == 0: if(...
Josh owns a hotel, there are X rooms in the hotel and every room can be allocated to maximum 1 person at a time. If a customer arrives and there are no rooms available, the customer will leave the hotel without staying, thus causing loss to his hotel. Input consists of a sequence of uppercase letters ,followed by a po...
s=raw_input() while(s!='0'): x=input() #a=input() #print s list_ok=[] list_nok=[] booked_room=0 count=0 l=len(s) for i in range(0,l): if s[i] in list_ok: booked_room-=1 else: if booked_room < x: booked_room+=1 list_ok.append(s[i]) else: if s[i] in list_nok: pass el...
Milly and her classmates are standing in a queue to attend the morning assembly of her school. According to the rule any student should stand in his/her proper place in order to make the queue completely visible till the end. Milly being the class monitor is required to make this queue such that students should be stan...
def test(N): previous = 0 for i in N: if i < previous: return False else: previous = i return True tc=int(raw_input()) while tc: tc=tc-1 n=input() N=map(int,raw_input().split()) if test(N): print -1,-1 else: start=end=0 fo...
You have been given an integer array A and a number K. Now, you need to find out whether any two different elements of the array A sum to the number K. Two elements are considered to be different if they lie at different positions in the array. If there exists such a pair of numbers, print "YES" (without quotes), else ...
l=[int(x) for x in raw_input().split()] l1=[int(y) for y in raw_input().split()] l2=[] l3=[] l1.sort() for i in range(0,len(l1)): if(l1[i]>=l[1]/2.0): l2.append(l1[i]) else: l3.append(l1[i]) if(l[1]==2000000): print('NO') elif(len(l2)>1): if(l2[0]+l2[1]==l[1]): print('YES') else: try: for j in range(0,l...
Kirti likes 8. Kirti's restaurant has many menus whose prices are multiples of 8. Now, Kirti has some digits written on a wooden board, and she'd like to cut the board to display prices in a new menu. In how many ways can Kirti choose consecutive digits from the board which denote integer multiples of 8? In this probl...
S = raw_input() #first look at 3s. if you find a hit, can do all prefixes of it N = len(S) ans = 0 for i in xrange(N-2): if int(S[i:i+3])%8 == 0: ans += i+1 - S[:i+1].count('0') #Now look at twos only for i in xrange(N-1): if int(S[i:i+2])%8 == 0 and S[i]!='0': ans += 1 ans += S.count('8')+S.count('0') print ans
Little Ashish got a lot of strings as his birthday gift. He does not mind getting so many strings for free; in fact, he loves them. But, on noticing all the strings he received as a gift, Little Ashish, who's also a snob and a bit OCD kind of a guy, realizes that he does not like the way in which the strings are arrang...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(raw_input()) while t: t-=1 s = raw_input().strip() d = {} for i in s: d[i] = d.get(i, 0) + 1 l = list(d.items()) for i, v in enumerate(l): v = list(v) v[0]...
Walter White is on a tour to sell meth. There are N cities. Each city has a id between 1 and N (both inclusive). You are given cost matrix. In cost matrix, the j\;th element in the i\;th row denotes the cost of travelling between cities with id i and j. cost[i][j]=cost[j][i] and cost[i][i]=0 Given the path taken b...
di1 = {} di2 = {} ct1 = raw_input() ct = int(ct1) ct2 = int(ct1) cnt = 0 while ct!=0: ct_name = raw_input() di1[ct_name] = cnt cnt = cnt + 1 ct = ct - 1 cnt1 = 0 while ct2 !=0: st = raw_input() s = st.split(' ') di2[cnt1] = s cnt1 = cnt1 + 1 ct2 = ct2 -1 t1 = raw_input() t = int(t1)...
Given are two strings S and T. Let us change some of the characters in S so that T will be a substring of S. At least how many characters do we need to change? Here, a substring is a consecutive subsequence. For example, `xxx` is a substring of `yxxxy`, but not a substring of `xxyxx`. Constraints * The lengths of ...
#include<bits/stdc++.h> using namespace std; int main(){ string s,t; cin >> s >> t; int i,j; int ans=10000; for(i=0;i<s.size()-t.size()+1;i++){ int x=0; for(j=0;j<t.size();j++){ if(s[i+j]!=t[j]){ x++; } } ans=min(ans,x); } cout << ans << endl; }
Given is a string S consisting of digits from `1` through `9`. Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition: Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019. Constraints * 1 ≤ |S| ≤ 200000 * S is a string c...
#include<bits//stdc++.h> using namespace std; #define rrep(i,n) for(int i = n -1;i >= 0;i--) typedef long long int ll; ll ans = 0, h = 1, now = 0; int main() { string s; cin >> s; vector<int> as(2020, 0); as[0]++; rrep(i, s.size()) { now = (now + (s[i] - '0') * h) % 2019; h = h * 10 % 2019;...
Takahashi is organizing a party. At the party, each guest will receive one or more snack pieces. Takahashi predicts that the number of guests at this party will be A or B. Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted. We assume that a piece cannot be ...
import math A,B=map(int,input().split()) print(int((A*B)/math.gcd(A,B)))
Given is an integer N. How many permutations (P_0,P_1,\cdots,P_{2N-1}) of (0,1,\cdots,2N-1) satisfy the following condition? * For each i (0 \leq i \leq 2N-1), N^2 \leq i^2+P_i^2 \leq (2N)^2 holds. Since the number can be enormous, compute it modulo M. Constraints * 1 \leq N \leq 250 * 2 \leq M \leq 10^9 * All va...
#include<bits/stdc++.h> #define LL long long #define pb push_back #define mp make_pair #define pii pair<int,int> using namespace std; inline int read(){ int v=0,f=1; char c=getchar(); while (c<'0' || c>'9'){ if (c=='-') f=-1; c=getchar(); } while (c>='0' && c<='9'){ v=v*10+c-'0'; c=getchar(); } return v*...
Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks. There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each. What is the minimum amount of money with which he can bu...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { static class Data { public final long cost; public final long count; public Data(long cost, long count) { this.cost = cost; this.count = count; } } public static void main(String... args...
Our world is one-dimensional, and ruled by two empires called Empire A and Empire B. The capital of Empire A is located at coordinate X, and that of Empire B is located at coordinate Y. One day, Empire A becomes inclined to put the cities at coordinates x_1, x_2, ..., x_N under its control, and Empire B becomes incli...
N,M,X,Y=map(int,input().split()) x=list(map(int,input().split())) y=list(map(int,input().split())) if max(max(x),X)<min(min(y),Y): print('No War') else: print("War")
You are given two integers A and B. Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section: * Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100. * The set of the squares painted white is ...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int mod=1e9+7; char ans[105][105]; int main() { int a,b; cin>>a>>b; for(int i=0;i<100;i++) { for(int j=0;j<100;j++) { if(i<50) ans[i][j]='#'; else ans[i][j]='.'; } } for(int i=0;i<a-1;i++) ans[i/50*2][i%50*2]='.'; for(in...
Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the ...
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; string s; int main() { cin >> s; cout << (s.find("AC") == string::npos ? "No" : "Yes") << endl; return 0; }
There is a directed graph with N vertices and M edges. The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i. We will play the following single-player game using this graph and a piece. Initially, the piece is placed at vertex 1, and the score of the player is set to 0. The player can move t...
import java.io.*; import java.util.*; class Graph { //開始,ゴール,頂点,辺 int s, g, n, e; //無向の場合もコンストラクタでうまくやってくれるはず int[] f, t; long[] c; long d[];/*sからの最短距離*/ long d2[][];/*2点間の最短距離*/ public Graph(int s, int N, int[] f, int[] t, long[] c) { this.s = s; this.n = N; ...
Snuke received N intervals as a birthday present. The i-th interval was [-L_i, R_i]. It is guaranteed that both L_i and R_i are positive. In other words, the origin is strictly inside each interval. Snuke doesn't like overlapping intervals, so he decided to move some intervals. For any positive integer d, if he pays d...
#include<bits/stdc++.h> #define X first #define Y second #define pb emplace_back #define FOR(i,a,b) for(int (i)=(a);i<(b);++(i)) #define EFOR(i,a,b) for(int (i)=(a);i<=(b);++(i)) #define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X)) #define REP rep #define rrep(X,Y) for (int (X) = (Y)-1;(X) >=0;--(X)) #define all(X) (X).b...
Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order. To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of...
import java.util.*; class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int a= sc.nextInt(); int b=sc.nextInt(); int c = sc.nextInt(); if(a+b+c ==17) { System.out.println("YES"); } else { System.out.println("NO"); } ...
There are league games and tournament games in sports competitions. In soccer league games, points are given to each of the wins, losses, and draws, and the rankings are competed based on the points. The points are win (3 points), negative (0 points), and draw (1 point), respectively. Enter the number of teams and the...
// 2011/02/02 Tazoe #include <iostream> #include <string> using namespace std; struct score{ string nam; int win; int los; int drw; int ord; int pnt; }; int main() { bool flg = false; while(true){ int n; cin >> n; if(n==0) break; if(flg) cout << endl; else flg = true; struct score tem...
Taro made a sugoroku so that everyone can play at the children's association event. In order to make the game interesting, I wrote instructions such as "advance 6" and "back 5" in some of the sugoroku squares other than "Furidashi" and "Agari". Turn the roulette wheel to advance as many times as you can, and if an inst...
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> using namespace std; #define rep(i,n) for(int i=0; i<(n); ++i) #define outl(x) cout<< (x) << '\n' #define fi first #define se second using pii = pair<int,int>; using ll = long long; #define LIM 256 vector<int> G[LIM], R[LIM...
problem Taro often shop at JOI general stores. At JOI general stores, there are enough coins of 500 yen, 100 yen, 50 yen, 10 yen, 5 yen, and 1 yen, and we always pay the change so that the number of coins is the smallest. Create a program to find the number of coins included in the change you receive when Taro goes sh...
import java.util.*; class Main { public static void main(String args[]){ Scanner in = new Scanner(System.in); while(true){ int n = 1000 - in.nextInt(); if(n==1000) return ; int cnt = 0; if(n>=500){ cnt++; n -= 500; } if(n>=100){ cnt += n/100; n %= 100; } if(n>=50){ cnt+...
Kotoko, a housewife, was enthusiastic about keeping food costs down during this recession. Be sure to check the newspaper advertisement every morning. Make a good list of what to buy and the cheapest-selling shops, and go shopping by riding a bicycle in a combat style called apron sandals while walking through the shop...
#include<iostream> #include<string> #include<queue> #include<map> #include<vector> #include<algorithm> #include<set> #include<functional> #define MAX_ITEM 256 using namespace std; const int infty = 1<<27; class Node{ public: vector<int> con; vector<int> cost; int item_num; pair<int,int> shop[MAX_ITEM]; }; t...
A Die Maker The work of die makers starts early in the morning. You are a die maker. You receive orders from customers, and make various kinds of dice every day. Today, you received an order of a cubic die with six numbers t1, t2, ..., t6 on whichever faces. For making the ordered die, you use a tool of flat-board s...
#include <bits/stdc++.h> using namespace std; const string D = "ENSW"; const int f[] = {2, 4, 5, 3}; int t[6]; int p, q; int L; bool ok(int a, int b, int c) { return (a <= b + c) && (b <= 1 + c + a) && (c <= 1 + a + b); } int main() { while(1) { for (int i = 0; i < 6; ++i) { cin >> t[i]; } L = ...
In a laboratory, an assistant, Nathan Wada, is measuring weight differences between sample pieces pair by pair. He is using a balance because it can more precisely measure the weight difference between two samples than a spring scale when the samples have nearly the same weight. He is occasionally asked the weight dif...
#include <bits/stdc++.h> using namespace std; #define int long long template <typename T> struct WeightedUnionFind{ int n; T d; vector<int> r,p; vector<T> ws; WeightedUnionFind(){} WeightedUnionFind(int sz,T d_): n(sz),d(d_),r(n,1),p(n),ws(n,d){iota(p.begin(),p.end(),0);} int find(int x){ if(x...
Background The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves treasure as much as programming. Yu will continue to explore the cave today in search of treasure. So Yu decided to write a program to find the walkin...
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pa...
National Association of Tennis is planning to hold a tennis competition among professional players. The competition is going to be a knockout tournament, and you are assigned the task to make the arrangement of players in the tournament. You are given the detailed report about all participants of the competition. The ...
#include <iostream> #include <cstring> using namespace std; static int mem[16][1<<16][5]; int vs[16][16]; int lg[16] = {1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4}; int search(int win, int lose, int cnt, int n){ if(~mem[win][lose][cnt]) return mem[win][lose][cnt]; if(!lose) return mem[win][lose][cnt] = 1; if(...
Natsume loves big cats. On Natsume's school road, there is a house commonly known as a cat mansion. The house is famous for having a lot of cats, and Natsume often encountered her cats in front of this house on her way to school and played with them. One day, Natsume learned a shocking fact. It was that the owner of th...
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> #include <queue> #include <string> #include <map> #include <set> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; static const dou...
Time Limit: 8 sec / Memory Limit: 64 MB Example Input 10 10 .....#.... .....#.... .....#.... ######.... .......... ####...... ....###... t..#..#### ...##..... ....#...## 3 0 3 0 5 4 6 Output 2
#include<iostream> #include<vector> #include<cstdlib> #include<algorithm> #include<queue> #include<cstring> #include<map> #include<iostream> using namespace std; typedef pair<int,int> Pt; typedef pair<int,Pt> P; #define fr first #define sc second Pt gl; int h,w,d[]={0,1,0,-1}; bool used[1000][1000]; char mas[1000][1000...
There was a girl who had a hobby of Othello. I enjoy Othello with my family when I have time. One day, the girl tried to play Othello as usual. However, everyone was so busy that no one played. So I came up with a game that can be played by one person using Othello's board and spinning top. problem Othello pieces ar...
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2530 // http://drken1215.hatenablog.com/entry/2019/03/20/164100 #include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <iostream> #include <map> #include <queue> #include <unordered_map> #include <vector> #include <string.h> usin...
Example Input 2 1 1 2 1 2 1 1 Output 1/2
#include <bits/stdc++.h> using namespace std; using ll = __int128_t; using ld = long double; constexpr int INF = 1 << 30; vector<int> F, C; class CostFlow { public: struct Edge { int from, to, revind, capacity, flow, cost; bool reversed; }; CostFlow(const int v) : V{v}, edge(v), dist(v),...
Matryoshka Matryoshka is a famous Russian folk craft doll. Matryoshka can be divided into upper and lower parts, and when opened, there is another smaller doll inside. The nesting structure is such that when the small doll that appears is opened, a smaller doll is contained. <image> You found an unusually shaped ma...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; typedef long long Weight; struct Edge { int src, dest; int cap, rev; Weight weight; bool operator < (const Edge &rhs) const { return weight > rhs.weight; } }; const int V = 4000; typedef ve...
G: Treasure Hunter problem There are N treasure trove, each of which is numbered from 1 to N. A treasure of value p_i lies in the i-th mountain, and this treasure can be obtained when you visit the mountain. Once you get the treasure, you can only get the treasure once, because the treasure will disappear from the mo...
#include<bits/stdc++.h> #define rep(i,a,b) for(int i=a;i<b;i++) #define rrep(i,a,b) for(int i=a;i>=b;i--) #define fore(i,a) for(auto &i:a) #define all(x) (x).begin(),(x).end() //#pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } typedef long ...
Cutlet Sandwich In some worlds, there are $ X $ types of "sandwiches", $ Y $ types of "cutlets", and $ Z $ types of "curry" foods. There is a $ N $ type of "cutlet sandwich" in this world, and the $ i $ type of cutlet sandwich is made from the $ A_i $ type of sand and the $ B_i $ type of cutlet. There is also a $ M ...
#pragma GCC optimize("Ofast", "unroll-loops") #include <bits/stdc++.h> using namespace std; #define ll long long #define ld long double /* グラフGの頂点sからすべての頂点への最短距離をDijkstra法により求める. */ template<typename T> vector<T> dijkstra(int s, vector<vector<pair<int, T>>>& G) { const int n = G.size(); vector<T> d(n, numeric_li...
Constraints * 1 ≤ |V| ≤ 1000 * 0 ≤ |E| ≤ 2000 * -10000 ≤ di ≤ 10000 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E) and the source r. |V| |E| r 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 verti...
import collections import sys sys.setrecursionlimit(100000) # ---- belmann-ford ----- V_num, E_num, r = [int(ele) for ele in input().split()] adjc_list = [] edges = [] for _ in range(V_num): adjc_list.append([]) for _ in range(E_num): src, dst, w = [int(ele) for ele in input().split()] adjc_list[src].appe...
Chef is playing a game with his friend Misha. They have a pile containg N coins. Players take alternate turns, removing some coins from the pile. On each turn, a player can remove either one coin or coins equal to some prime power (i.e. p^x coins, where p - prime number and x - positive integer). Game ends when the pil...
for i in range(int(raw_input())): n = int(raw_input()) if n % 6 == 0: print "Misha" else: print "Chef"
Devu has an array A consisting of N positive integers. He would like to perform following operation on array. Pick some two elements a, b in the array (a could be same as b, but their corresponding indices in the array should not be same). Remove both the elements a and b and instead add a number x such that x lies be...
inputstr = raw_input() n,q = inputstr.split() n = int(n) q = int(q) a = map(int, raw_input().split()) minn = min(a) maxn = max(a) for i in range(q): t = int(raw_input()) if((t >= minn)&(t <= maxn)): print('Yes') else: print('No')
Sumo was travelling alone at night, suddenly he saw a spaceship and out of it came an alien named KK. Obviously, the alien had a different language and thus couldn't communicate readily. After some psycho-telepathic talk, Sumo realised that KK's language has M distinct characters. And a valid word in his language satis...
#Anwesh Mohanty mod=10**9+7 t=input() while t>0: n,m=map(int,raw_input().split()) if n==1: print m%mod elif n==2: print m*(m-1) else: print (m*(m-1)*pow(m-2,n-2,mod)%mod) #nPm t-=1
Did you ever hear about 'crossing the bridge noodle' ? Let me tell you that it's not some kind of bridge made of noodles. It's a dish, a kind of rice noodle soup. Mr.Ping makes the best noodle soup and his son Po is eagerly waiting for the user reviews in his father's blog. Users can vote with a (+) or a (-) and accord...
while 1: n = raw_input() if n == '': continue n = int(n) if n == 0: break users = 0 for i in xrange(0 , n): vote , score = raw_input().split() score = int(score) if vote == 'P': vote = 1 else: vote = -1 score -= vo...
Given an array A of N numbers, find out the minimum number of elements to be changed to ensure that the new array becomes a consecutive sequence of numbers. For example, given A = {2, 3, 6, 7, 8} where N = 5, it is obvious that we can change the first two elements in A to get the new array A' = {4, 5, 6, 7, 8}. (Note: ...
times=input() while times: times-=1 n=input() l=[int(x) for x in raw_input().split()] i=0 maxi=-23 while i<n: j=i+1 count=0 while j<n: if(l[j]-l[i]-(j-i)==0): count+=1 j+=1 if(count+1>maxi): maxi=count+1 ...
Given an integer N, Chef wants to find the smallest positive integer M such that the bitwise XOR of M and M+1 is N. If no such M exists output -1. Input The first line of input contain an integer T denoting the number of test cases. Each of the following T lines contains an integer N for that test case. Output For ea...
T = input() for t in range(T): N = input() if N==1: print 2 elif (N&(N+1))==0: print ((N+1)/2) - 1 else: print -1
Initially there was an array a consisting of n integers. Positions in it are numbered from 1 to n. Exactly q queries were performed on the array. During the i-th query some segment (l_i, r_i) (1 ≤ l_i ≤ r_i ≤ n) was selected and values of elements on positions from l_i to r_i inclusive got changed to i. The order of t...
#include <bits/stdc++.h> using namespace std; template <int MAXN> struct segtree_lazy { struct updater { int x; updater(int x = 0) : x(x) {} updater& operator+=(const updater& other) { x = other.x; return *this; } operator bool() const { return x != 0; } }; struct node_t { int ...
You are given an n × m grid. Each grid cell is filled with a unique integer from 1 to nm so that each integer appears exactly once. In one operation, you can choose an arbitrary cycle of the grid and move all integers along that cycle one space over. Here, a cycle is any sequence that satisfies the following condition...
#include <bits/stdc++.h> using namespace std; const int N = 30; struct nd { int x, y; }; nd operator+(nd a, nd b) { return {a.x + b.x, a.y + b.y}; } nd operator-(nd a, nd b) { return {a.x - b.x, a.y - b.y}; } nd rt(nd a) { return {a.y, -a.x}; } int n, m, a[N][N]; int in(nd a) { return a.x >= 1 && a.x <= n && a.y >= 1...
Ivan plays some computer game. There are n quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has 3 parameters a_{i}, b_{i}, p_{i}: reward for completing quest before upgrade, reward for completing quest after upgrade (a_{i} < b_{i}) and probability of successf...
#include <bits/stdc++.h> using namespace std; vector<vector<double>> IDENT() { vector<vector<double>> A(3, vector<double>(3)); for (int i = 0; i < 3; i++) A[i][i] = 1; return A; } vector<vector<double>> mul(vector<vector<double>> A, vector<vector<double>> B) { vector<vector<double>> C(A.size(), vector<double>(B...
Tattah's youngest brother, Tuftuf, is new to programming. Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava. Today, Tuftuf was introduced to Gava's unsigned integer datatypes. G...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * Date 25.11.2011 * Time 20:43:22 * Author Woodey * $ */ public class B108 { final int INF = Integer.MAX_VALUE; private void Solution() throws IOExcept...
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
def main(): n = int(input()) arr = list(map(int,input().split())) pref = [None]*(n+1) pref[0] = 0 pref[1] = arr[0] funny = 0 for i in range(1,n): pref[i+1] = pref[i]^arr[i] even = dict() odd = dict() even[0] = 1 for i in range(1,n+1): if i&1: if od...
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symb...
#include <bits/stdc++.h> using namespace std; string add(string one, string two) { int carry = 0; string s; for (int i = two.size() - 1; i >= 0; i--) { int o = one[i] - 'a'; int t = two[i] - 'a'; int sum = carry + o + t; char ans = 'a' + sum % 26; carry = sum / 26; s.push_back(ans); } ...
You have a bag which contains n cards. There is a number written on each card; the number on i-th card is a_i. You are playing the following game. During each turn, you choose and remove a random card from the bag (all cards that are still left inside the bag are chosen equiprobably). Nothing else happens during the f...
#include <bits/stdc++.h> using namespace std; template <class T> void _R(T &x) { cin >> x; } void _R(int &x) { scanf("%d", &x); } void _R(long long &x) { scanf("%lld", &x); } void _R(double &x) { scanf("%lf", &x); } void _R(char &x) { scanf(" %c", &x); } void _R(char *x) { scanf("%s", x); } void R() {} template <clas...
Warning: This problem has an unusual memory limit! Bob decided that he will not waste his prime years implementing GUI forms for a large corporation and instead will earn his supper on the Stock Exchange Reykjavik. The Stock Exchange Reykjavik is the only actual stock exchange in the world. The only type of transactio...
#include <bits/stdc++.h> using namespace std; inline char gc() { static char buf[100000], *p1 = buf, *p2 = buf; return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++; } inline long long read() { long long x = 0; char ch = getchar(); bool positive...
There are n pillars aligned in a row and numbered from 1 to n. Initially each pillar contains exactly one disk. The i-th pillar contains a disk having radius a_i. You can move these disks from one pillar to another. You can take a disk from pillar i and place it on top of pillar j if all these conditions are met: ...
n=int(input()) ar=list(map(int,input().split())) m=max(ar) ind=-1 for i in range(n): if(ar[i]==m): ind=i ans="YES" a1=[] a2=[] for i in range(ind): a1.append(ar[i]) a2.append(ar[i]) a2.sort() for i in range(ind): if(a1[i]!=a2[i]): ans="NO" a3=[] a4=[] for i in range(ind+1,n): a3.ap...
Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from i...
import java.math.*; import java.text.*; import java.util.*; public class CompleteSearch { public static Scanner in =new Scanner(System.in); int n; public static void main(String[] args){ int n=in.nextInt(); String a=in.next(); Stack stack=new Stack(); for(int i=0...
Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree. The depth of a vertex is the number o...
#include <bits/stdc++.h> using namespace std; const int MOD = 119 << 23 | 1; const int FFTMOD = 119 << 23 | 1; const int INF = (int)1e9 + 23111992; const long long LINF = (long long)1e18 + 23111992; const long double PI = acos((long double)-1); const long double EPS = 1e-9; inline long long gcd(long long a, long long b...
This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems. Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes o...
#include <bits/stdc++.h> using namespace std; long long n; vector<long long> v; long long solve(long long x) { long long sol = 0, cnt = 0; for (long long i = 0; i < n - 1; i++) { cnt += v[i]; sol += min(cnt % x, x - cnt % x); } return sol; } int main() { ios_base::sync_with_stdio(false); cin.tie(NUL...
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids. Santa is really busy, so he wants the ...
#include <bits/stdc++.h> using namespace std; void my_dbg() { cout << endl; } template <typename Arg, typename... Args> void my_dbg(Arg A, Args... B) { cout << ' ' << A; my_dbg(B...); } using ll = long long; using vi = vector<int>; using vl = vector<ll>; const int inf = INT_MAX; const int ninf = INT_MIN; const int ...
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the f...
from collections import defaultdict n, m = [int(y) for y in input().split()] d=defaultdict(list) for i in range(m): a, b = [int(y) for y in input().split()] d[a].append(b) d[b].append(a) cnt=0 while True: f=0 vis=[False]*n for k, v in d.items(): if len(v)==1 and not vis[k-1]: ...
Berland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is n mountain peaks, located on one straight line and numbered in order of 1 to n. The height of the i-th mountain top is a_i. "Median mountain range" is famous...
#include <bits/stdc++.h> using namespace std; const int MAXN = 500000; const int MAXL = 19; int a[MAXN + 5], b[MAXN + 5], res[MAXN + 5]; int Min[MAXN + 5][MAXL + 5], Max[MAXN + 5][MAXL + 5]; pair<int, int> get(int left, int right) { int len = right - left; int bin = b[len]; return make_pair(min(Min[left][bin], Mi...
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He w...
#include <bits/stdc++.h> using namespace std; const long long int MOD = 1e9 + 7; inline long long int gcd(long long int a, long long int b) { return b ? gcd(b, a % b) : a; } inline long long int lcm(long long int a, long long int b) { return a * b / gcd(a, b); } inline long long int add(long long int a, long long i...
This is an interactive problem. Ayush devised a new scheme to set the password of his lock. The lock has k slots where each slot can hold integers from 1 to n. The password P is a sequence of k integers each in the range [1, n], i-th element of which goes into the i-th slot of the lock. To set the password of his loc...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const double pi = acos(-1), eps = 1e-8; const int maxn = 1 << 17; const int N = 1e6 + 10, M = N << 2, mod = 1e9 + 7; int n, k; int ans[N]; vector<int> s[N]; int pos, num; int p[N]; void dfs(int l, int r, int mx) { if (l == r) { if (p[l] == ...
Koa the Koala has a directed graph G with n nodes and m edges. Each edge has a capacity associated with it. Exactly k edges of the graph, numbered from 1 to k, are special, such edges initially have a capacity equal to 0. Koa asks you q queries. In each query she gives you k integers w_1, w_2, …, w_k. This means that ...
#include <bits/stdc++.h> #pragma GCC optimize(2, 3, "Ofast") const int maxn = 1e4 + 5, maxk = 1101; const int inf = 25; template <typename T> inline T min(const T &a, const T &b) { return a < b ? a : b; } struct IO { IO(){}; char c; inline char gc() { static char buf[maxn], *p1 = buf, *p2 = buf; return ...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Let p be any permutation of length ...
# Om Namh Shivai # Jai Shree Ram # Jai Hanuman # Jai Shree Krishna # Radhe-Krishna # Jai Maa Kali # Jai Maa Durga # Jai Maa Burithakran for i in range(int(input())): n = int(input()) arr = list(map(int, input().split())) if(n%2 == 0): arr_res = list(reversed(arr)) else: arr_res = list(r...
Initially, you have the array a consisting of one element 1 (a = [1]). In one move, you can do one of the following things: * Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); * Append the copy of some (single) element of a to the end of the array...
from math import ceil for _ in range(int(input())): n = int(input()) b = ceil(pow(n, 0.5)) a = ceil(n / b) ans = a + b - 2 print(ans)
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at...
import java.awt.Point; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Meeting { public void solve() throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new Buffere...
Let's define a multiplication operation between a string a and a positive integer x: a ⋅ x is the string that is a result of writing x copies of a one after another. For example, "abc" ⋅~2~= "abcabc", "a" ⋅~5~= "aaaaa". A string a is divisible by another string b if there exists an integer x such that b ⋅ x = a. For e...
import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = sc.nextInt(); ...
You are given three positive (greater than zero) integers c, d and x. You have to find the number of pairs of positive integers (a, b) such that equality c ⋅ lcm(a, b) - d ⋅ gcd(a, b) = x holds. Where lcm(a, b) is the least common multiple of a and b and gcd(a, b) is the greatest common divisor of a and b. Input Th...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 2e7 + 123; const int mod = 1e9 + 9; string s; int c, d, x; int dp[maxn]; int D[maxn]; bool is_prime(int x) { return D[x] == x; } void precalc() { for(int i = 2; i < maxn; i++) D[i] = i; for(int i = 2; i * i < maxn; i++) {...
Nastia has received an array of n positive integers as a gift. She calls such an array a good that for all i (2 ≤ i ≤ n) takes place gcd(a_{i - 1}, a_{i}) = 1, where gcd(u, v) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers u and v. You can perform the op...
import java.io.*; import java.util.*; public class B { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st ...
You are given a string s of length n consisting only of the characters 0 and 1. You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For...
import java.util.*; public class HelloWorld { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t,ans=0; t=sc.nextInt(); while(t>0) { int n = sc.nextInt(); int a = sc.nextInt(); ...
This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out n villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall...
#include <bits/stdc++.h> using namespace std; int N, dad[110000][20], num[110000], cnt, F[110000]; int d[110000], Q, ccnt, B[110000], E[110000]; pair<int, int> seg[110000 * 5]; long long D[110000], len[110000][20], res; vector<pair<int, int> > v[110000]; void dfs(int x, int parent, long long l, int depth) { dad[x][0]...
You are given two polynomials: * P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and * Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm. Calculate limit <image>. Input The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The seco...
from math import gcd def polynomials(): n, m = map(int, input().strip().split()[:2]) if n > 100 or m > 100 or n < 0 or m < 0: print() else: ap1 = list(map(int, input("").split()[:n+1])) aq1 = list(map(int, input("").split()[:m+1])) if ap1[0] == 0 or aq1[0] == 0: ...
The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj. The distance between permutations a and b is the minimum absolute value of the dif...
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010; int n, a[MAXN], b[MAXN], ia[MAXN], ans[MAXN]; priority_queue<pair<int, int> > pq1, pq2; int main() { if (fopen("input.txt", "r")) { freopen("input.txt", "r", stdin); } scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i])...
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's c...
#include <bits/stdc++.h> const int N = 100100; std::vector<int> G[N], comm; int n, m, h, t; int app[N], atop; bool com[N]; bool ok(int u, int v) { atop++; for (int j = G[u].size() - 1; j >= 0; j--) if (G[u][j] != v) app[G[u][j]] = atop; int cnt = 0; for (int j = G[v].size() - 1; j >= 0; j--) if (G[v][j]...
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. One day Johnny got bracket sequence. He decided to remove some...
s=raw_input() A=0 r=0 for x in s: if x=='(': A+=1 else: if(A>0): A-=1 r+=2 print r
We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the co...
#include <bits/stdc++.h> const int maxn = 11111; struct dsu { int f[555]; int c; void init() { int i; c = 0; for (i = 1; i <= 505; i++) f[i] = i; } int find(int a) { return f[a] == a ? a : f[a] = find(f[a]); } void Union(int x, int y) { x = find(x), y = find(y); if (x != y) f[x] = y, c++...
Smart Beaver became interested in drawing. He draws suns. However, at some point, Smart Beaver realized that simply drawing suns is boring. So he decided to design a program that will process his drawings. You are given a picture drawn by the beaver. It will have two colors: one for the background and one for the suns ...
#include <bits/stdc++.h> using namespace std; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; struct Point { int x, y; } Q[2000 * 2000], P, np; int n, m; int b[2000][2000]; int mark[2000][2000], T; int L[2000 * 2000]; int flag[2000][2000]; bool out(int x, int y) { return x < 0 || y < 0 || x >= n || y ...
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class MaximalAreaQuadrilateral { public static void main(String[] args) { MyScanner sc = new MyScanner(); int N = sc.nextInt(); int[] X = n...
A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them. The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles. In total, the boys' shared budget is a rubles. Besides, each of them has his own pe...
#include <bits/stdc++.h> using namespace std; long long perso[100010], bike[100010], n, m, a; pair<int, int> check2(long long k, long long s) { long long count = 0, sum = 0; for (int i = n - k, j = 0; j < k and i < n; j++, i++) { if (perso[i] >= bike[j]) { count++; sum += bike[j]; } else { ...
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static boolean prefixCompare(char[] a,int i,int j) { if(i > j-i+1)return tr...
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products. There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p...
num_cashiers = int(input()) queue_sizes = list(map(lambda x: int(x) * 15, input().split())) items = [] for i in range(num_cashiers): items_list = sum(map(lambda x: int(x) * 5, input().split())) items.append(items_list) min_time = min(change + groceries for change, groceries in zip(queue_sizes, items)) print(...
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer. Help Pasha count the maximum number he can get if he has the time to make at most k sw...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import math import itertools #10**9+7 mod=1000000007 #start = time.clock() n1,k=map(str,raw_input().split()) k=int(k) ans=chk=0 n=[int(x) for x in n1] l=len(n) #先頭から交換可能範囲により大きい数がないかチェック for i in range(l-1): if k==chk: break en=k-chk h=min(l+1,i+en+1) ...
The game of bingo is played on a 5 × 5 square grid filled with distinct numbers between 1 and 75. In this problem you will consider a generalized version played on an n × n grid with distinct numbers between 1 and m (m ≥ n2). A player begins by selecting a randomly generated bingo grid (generated uniformly among all ...
#include <bits/stdc++.h> using namespace std; double szh[100100]; double szz[500]; int numx; int maxz; int len; int main() { double ans; int f1; int f2; scanf("%d%d%d", &len, &maxz, &numx); szh[numx] = 0; for (f1 = numx - 1; f1 >= 0; f1--) szh[f1] = szh[f1 + 1] + log(maxz - f1) - log(numx - f1); szz[0...
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the resul...
//import com.sun.java_cup.internal.runtime.Scanner; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author islam */ public class Coins { p...
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation <image>, where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order. For example, Perm(0) = (0, 1, ..., n...
#include <bits/stdc++.h> const long long OO = 1000000007; const int MAXN = 100005; using namespace std; int n; vector<int> a(200000), b(200000), c(200000); vector<int> ina(200000, 0), inb(200000, 0), inc(200000, 0); bool used[200000]; void add(int cur, int val, vector<int>& ina) { while (cur < n) { ina[cur] += va...
The project of a data center of a Big Software Company consists of n computers connected by m cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is n...
#include <bits/stdc++.h> void read(int &a) { a = 0; char c = getchar(); while (c < '0' || c > '9') { c = getchar(); } while (c >= '0' && c <= '9') { a = (a << 1) + (a << 3) + (c ^ 48); c = getchar(); } } const int Maxn = 100000; const int Maxm = 300000; int num; bool vis[Maxm << 1 | 5]; int head...