input
stringlengths
29
13k
output
stringlengths
9
73.4k
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc...
import sys import math import itertools import collections def getdict(n): d = {} if type(n) is list or type(n) is str: for i in n: if i in d: d[i] += 1 else: d[i] = 1 else: for i in range(n): t = ii() if t in d...
Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss? Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs ...
#include <bits/stdc++.h> using namespace std; const int inf = 1e9 + 7; const long long big = inf * 1LL * inf; const int maxn = 1e6; vector<int> vert[100010], hori[100010]; int cntVert[100010], cntHori[100010], topBefore[100010]; struct Sofa { int x1, y1, x2, y2; Sofa() {} Sofa(int a, int b, int c, int d) : x1(a),...
You are given a weighted directed graph, consisting of n vertices and m edges. You should answer q queries of two types: * 1 v — find the length of shortest path from vertex 1 to vertex v. * 2 c l1 l2 ... lc — add 1 to weights of edges with indices l1, l2, ..., lc. Input The first line of input data contains i...
#include <bits/stdc++.h> using namespace std; const int MAXN = (int)1e5 + 5; const int MAXM = (int)1e6 + 5; const long long INF = (long long)1e18; vector<int> vec[MAXM]; pair<int, int> e[MAXN]; vector<int> adj[MAXN]; int w[MAXN]; long long dist[MAXN], dist2[MAXN], w2[MAXN]; int n, m, q; void dijkstraSlow() { priority...
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters. Let A be a set of positions in the string. Let's call it pretty if following conditions are met: * letters on positions from A in the string are all distinct and lowercase; ...
import java.io.*; import java.util.*; /* TASK: CF436A LANG: JAVA */ public class CF436A { static int n , c , max; static boolean[] seen; public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); n = in.nextInt(); String s = in.next();...
Vasya studies music. He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note aft...
import java.util.*; public class Main { static int check(int a, int b, int c) { if (b-a==4&&c-b==3) return 1; if (b-a==3&&c-b==4) return 2; return 0; } public static void main(String[] args) { String[] notes={"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "B", "H"}; Scanner cin ...
While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!). The gift bundle also includes a square scoop of size r × r, designed for fishing....
#include <bits/stdc++.h> using namespace std; const long long mod = 998244353; long long n, m, r, k, xx[] = {1, -1, 0, 0}, yy[] = {0, 0, 1, -1}, stx, sty, num; long long a[100005], b[100005]; long double ans; map<pair<int, int>, int> mp; priority_queue<pair<long long, pair<int, int> > > q; long long giv(long long x, lo...
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must. Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this... Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric...
#include <bits/stdc++.h> using namespace std; vector<long long> a; long long k, p; long long getNext(long long curr) { if (curr > 0) return -(curr / k); else { if (curr % k == 0) return -(curr / k); else return -(curr / k) + 1; } } int main() { scanf("%lld %lld", &p, &k); a.reserve(100...
You are given a directed graph with n nodes and m edges, with all edges having a certain weight. There might be multiple edges and self loops, and the graph can also be disconnected. You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are...
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; /* spar5h */ public class cf4 implements Runnable{ public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(); int m = s.nextInt(); TreeMap...
You are given k sequences of integers. The length of the i-th sequence equals to n_i. You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the...
#include <bits/stdc++.h> using namespace std; int main() { int k; cin >> k; map<int, vector<int>> a; vector<int> s(k); for (int i = 0; i < k; i++) { int n; cin >> n; a[i].assign(n, 0); int sum = 0; for (int j = 0; j < n; j++) { cin >> a[i][j]; sum += a[i][j]; } s[i] = s...
AltF4 and CtrlF4 again started playing games. This time they drew a N x N matrix and filled number in each of the cells randomly. The game is played in turns (AltF4 always starts first, as his name comes first alphabetically). In each turn, a player calls out a number in the range [1, N] which has not already been cal...
for mat_ in range(int(raw_input())): mat = {} N = int(raw_input()) row_weight = {} col_weight = {} for each_mat in range(N): elems = (str(raw_input())).split() elems = [int(i) for i in elems] mat[each_mat+1] = elems for index, elem in enumerate(elems): try: row_weight[each_mat+1] += elem except K...
Rajiv is given a problem in class. " Suppose N burnt candles together make a new candle. then how many new candles are created if we start with M candles" Please refer to similar MCQ Question for clarification. SAMPLE INPUT 121 SAMPLE OUTPUT 30
n = int(raw_input()) ans = n / 5 r = n % 5 + ans while r >= 5: ans += r / 5 r = r % 5 + r / 5 print ans
You are given N number of trophies. All trophies look similar. However, one of them is defective. All trophies except the defective one have same weight. The defective one has less weight compared to others. You are given a weighing balance. As you are extremely smart you will use the weighing balance optimally. What i...
from math import ceil,log def minCoins(coins): if coins==0: print 0 else: print int(ceil(log(coins,3))) n=int(raw_input()) for i in range(n): coins=int(raw_input()) minCoins(coins)
Dothraki are planning an attack to usurp King Robert's throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom. But, to lock the door he needs a key that is an anagram of a certain palindrome string. The king has a string composed of low...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' s = raw_input() n = len(s) d = {} for c in s: if c in d: d[c] += 1 else: d[c] = 1 nodd = 0 for key in d: if d[key] % 2 == 1: nodd += 1 if n%2 == 0 and nodd == 0: print "YES"...
Today RK has a special task for you. RK gives you a positive integer N. First you have to find all the sequences of length N consisting of characters 'O' and 'Z' only such that no two 'Z' are adjacent in any sequence. After finding all such sequences you have to find Kth sequence when all found sequences are sorted lex...
from sys import stdin fib = [1,2] ma = 10**19 while True: fib.append(fib[-1] + fib[-2]) if fib[-1] > ma: break t = int(stdin.readline()) for _ in xrange(t): n,k = map(int,stdin.readline().split()) ans = '' valid = 1 if n<len(fib) and fib[n] < k: valid = 0 for i in xrange(n): rem = n-1-i #print "rem are"...
Monk is standing at the door of his classroom. There are currently N students in the class, i'th student got Ai candies. There are still M more students to come. At every instant, a student enters the class and wishes to be seated with a student who has exactly the same number of candies. For each student, Monk shouts ...
t = int(raw_input()) for _ in xrange(t): n, m = map(int, raw_input().split()) students = map(int, raw_input().split()) seated = set(students[:n]) res = [] for student in students[n:]: res.append("YES" if student in seated else "NO") seated.add(student) print "\n".join(res)
Recently our Paroothi got a crush on a girl , as we all know he is not good with the girls so he asked Vikrant ( The stud ) for expert advise and he told him to take her to her favourite restaurant . It is known that there are K restaurants in the city numbered from 1 to K.Now Paroothi has a list which contains N integ...
A = [int(x) for x in raw_input().split(' ') if x!=''] a = [0]*A[1] b = [int(x) for x in raw_input().split(' ') if x!=''] for i in range(0,A[0]): a[b[i]-1] = a[b[i]-1]+1 max=0 k=0 for i in range(0,A[1]): if max<a[i]: max = a[i] k=i print k+1
Roy has N coin boxes numbered from 1 to N. Every day he selects two indices [L,R] and adds 1 coin to each coin box starting from L to R (both inclusive). He does this for M number of days. After M days, Roy has a query: How many coin boxes have atleast X coins. He has Q such queries. Input: First line contains N ...
n=int(raw_input()) arr=[0]*1000002 b=[0]*1000002 m=int(raw_input()) for i in range(m): l,r=map(int,raw_input().split()) arr[l]+=1 arr[r+1]-=1 for i in range(1,n+1): arr[i] += arr[i - 1] b[arr[i]]+=1 count=0 for i in range(1000000,0,-1): b[i] += b[i + 1] q=int(raw_input()) for i in range(q): qu=int(raw_input()) ...
Arpit thought AB De-villiers could do anything no matter what it is, however his brother didn’t believe him . To make his brother believe him he contacted AB and gave him a problem in which he gave him a two strings where the second string was the reverse of the first. He asked him to find the longest substring which i...
def computeLPSArray(txt, M, lps): lens = 0 lps[0] = 0 i = 1 while i < M: if txt[i] == txt[lens]: lens += 1 lps[i] = lens i += 1 else: if lens != 0: lens = lps[lens - 1] else: lps[i] = 0 ...
Utkarsh being a very talkative child, was scolded by his teacher multiple times. One day, the teacher became very angry and decided to give him a very rigorous punishment. He made him stand on the school field which is X axis. Utkarsh initially stood at X = 0. The teacher asked him to run to X = N. But, to make the ...
n,p = map(int,raw_input().split()) p = float(p) dp = [0] * (n+1) dp[0] = 1 dp[1] = 0 dp[2] = p/100 dp[3] = 1-p/100 for i in range(4,n+1): dp[i] = (p/100) * dp[i-2] + (1-p/100) * dp[i-3] print "%.6f"%dp[n]
We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i). Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there? We remind you that the distance between the origin and the point (p, q) can be represented as \...
#include <bits/stdc++.h> using namespace std; int main(){ int64_t n, d, ans=0; cin >> n >> d; int64_t x, y; for(int i=0; i<n; i++){ cin >> x >> y; if(x*x+y*y<=d*d) ans++; } cout << ans; return 0; }
We have an undirected graph G with N vertices numbered 1 to N and N edges as follows: * For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1. * There is an edge between Vertex X and Vertex Y. For each k=1,2,...,N-1, solve the problem below: * Find the number of pairs of integers (i,j) (1 \leq i...
import java.util.*; public class Main{ public static void main(String[] arg){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int x=sc.nextInt(); int y=sc.nextInt(); int dp[][]=new int[n+1][n+1]; dp[x][y]=1; for(int i=1;i<n;i++){ for(int j=i+1;j<=n;j++){ ...
This is an interactive task. We have 2N balls arranged in a row, numbered 1, 2, 3, ..., 2N from left to right, where N is an odd number. Among them, there are N red balls and N blue balls. While blindfolded, you are challenged to guess the color of every ball correctly, by asking at most 210 questions of the followin...
#include <bits/stdc++.h> using namespace std; int n; vector<int> v1,v2; char s[5],res[666]; inline char Q1(int l,int r) { printf("? "); for (int i=l;i<=r;++i) printf("%d%c",i,i==r?'\n':' '); fflush(stdout); char s[5];scanf("%s",s); return s[0]; } inline char Q2(vector<int> &vec) { printf...
The door of Snuke's laboratory is locked with a security code. The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same. You are given the current security code S. If S is hard to enter, print `Bad`; otherwise, print `Good`. Constraint...
s = raw_input() ans = 0 for i in range(3): if s[i]==s[i+1]: ans = 1 if ans == 1: print "Bad" else: print "Good"
There are N Snukes lining up in a row. You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is `0`; one red ball and one blue ball if the i-th character in S is `1`; two blue balls if the i-th character in S is `2`. Takahashi has a sequence that is initially ...
#include <bits/stdc++.h> #define mod 1000000007 #define sp ' ' #define intmax 2147483647 #define llmax 9223372036854775807 #define mkp make_pair typedef long long ll; using namespace std; int N, DP[4001][4001], R[2001], B[2001]; string S; int main() { cin >> S; N = S.size(); for (int i = 1; i <= N; ++i) { switc...
There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j. Snuke can repeatedly perform ...
#include <cstdio> #include <algorithm> using namespace std; const int N=100010; const int INF=1e9; const int MOD=1e9+7; int n,m; int a[N],b[N]; struct Point{ int x,y; friend bool operator == (const Point &a,const Point &b){ return a.x==b.x&&a.y==b.y; } }p[N]; int d[N],dcnt; int f[N]; void readData(){ scanf("%d%d"...
We have N cards. A number a_i is written on the i-th card. Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first. The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards...
input() card=sorted(map(int,input().split()))[::-1] print(sum(card[::2])-sum(card[1::2]))
We have an H-by-W matrix. Let a_{ij} be the element at the i-th row from the top and j-th column from the left. In this matrix, each a_{ij} is a lowercase English letter. Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A. Here, he wants to satisfy the following condition: * Every ro...
import java.io.*; import java.util.*; import java.math.*; import java.util.concurrent.*; class Main { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); ...
There are N cards. The two sides of each of these cards are distinguishable. The i-th of these cards has an integer A_i printed on the front side, and another integer B_i printed on the back side. We will call the deck of these cards X. There are also N+1 cards of another kind. The i-th of these cards has an integer C_...
#include <bits/stdc++.h> using namespace std; #define ref(i,x,y)for(int i=x;i<=y;++i) #define def(i,x,y)for(int i=x;i>=y;--i) #define pb push_back #define SZ(x) ((int)x.size()) #define mp make_pair #define fi first #define se second typedef vector<int> vint; typedef long long LL; typedef pair<int,int> PII; const int N=...
There are N towns in Takahashi Kingdom. They are conveniently numbered 1 through N. Takahashi the king is planning to go on a tour of inspection for M days. He will determine a sequence of towns c, and visit town c_i on the i-th day. That is, on the i-th day, he will travel from his current location to town c_i. If he...
#include <bits/stdc++.h> using namespace std; using ll = long long; constexpr ll kMod = 1e9 + 7; ll dp[301][301][301]; int main() { int n, m; cin >> n >> m; dp[0][n - 1][1] = 1; for (int i = 0; i < m; ++i) { for (int j = n; j >= 0; --j) { for (int k = 1; k <= n; ++k) { dp[i][j]...
When a boy was cleaning up after his grand father passing, he found an old paper: <image> In addition, other side of the paper says that "go ahead a number of steps equivalent to the first integer, and turn clockwise by degrees equivalent to the second integer". His grand mother says that Sanbonmatsu was standing ...
import math def calc(x, y, r, d, nd): x = x + r * math.cos(math.radians(d)) y = y + r * math.sin(math.radians(d)) d -= nd return x, y, d x = y = 0 d = 90 while True: r, nd = map(int, input().split(",")) if r == nd == 0: break x, y, d = calc(x, y, r, d, nd) print(int(x)) print(int(y))
In Group C of the 3rd year, we decided to use the "class flag" used at the sports festival on November 10, 2007 at future class reunions. So, in order to decide which students to keep the "class flag", I decided to play the following game using a large amount of candy that the teacher gave me the other day. * Each stu...
#include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<n;i++) using namespace std; typedef long long ll; int main() { int n; while (cin >> n) { if (!(n % 39))puts("3C39"); else printf("3C%02d\n", n % 39); } }
Today is the open campus of Z University. Every year during the lunch break on this day, many high school students line up for the school cafeteria. Therefore, the secretariat of Z University decided to predict the maximum distance of the procession. As a result of the preliminary survey, we know the following. * The ...
#include<bits/stdc++.h> using namespace std; struct edge { int u, v, cost; edge(int u, int v, int c) : u(u), v(v), cost(c) {} }; const int INF = 1 << 30; int main() { int N, C; int A[200], O[200], B[200], S[200], D[200]; auto bellman_ford = [&]() { vector< edge > edges; vector< int > v(N, INF)...
problem Hanako is playing with n (4 ≤ n ≤ 10) cards side by side. Each card has one integer between 1 and 99. Hanako chose k cards (2 ≤ k ≤ 4) from these cards and arranged them in a horizontal row to make an integer. How many kinds of integers can Hanako make in total? For example, consider that you are given five c...
#include<iostream> #include<cstdio> #include<string> #include<set> using namespace std; int n; int num[5]; int card[11]; set<string> ans; void serch(int m,int k,int now) { for(int i=0;i<m;i++) { for(int j=i+1;j<m;j++) { if(num[i]==num[j]) { return; } } } if(m==k) { string str; char c...
She is an apprentice wizard. She first learned the magic of manipulating time. And she decided to open a liquor store to earn a living. It has to do with the fact that all the inhabitants of the country where she lives love alcohol. Residents especially like sake that has been aged for many years, and its value increas...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; template<class t> using table = vector<vector<t>>; const ld eps = 1e-9; //// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_downl...
The city of Hakodate recently established a commodity exchange market. To participate in the market, each dealer transmits through the Internet an order consisting of his or her name, the type of the order (buy or sell), the name of the commodity, and the quoted price. In this market a deal can be made only if the pri...
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cc...
Example Input 3 3 0 1 Output 2
#include <bits/stdc++.h> #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) using namespace std; typedef long long ll; int main(void) { ll N; cin >> N; vector<ll> D(N); REP(i, 0, N) cin >> D[i]; vector<bool> ok(N * N + 1, true); REP(i, 0, N) { ll x = 0; REP(j, i, N) { x = x * 10 + ...
Background The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu-kun, one of the kindergarten children, loves drawing as much as programming. So far, Yu has drawn many pictures with circles, hexagons and arrows. One day Yu finds out that these pictures are...
#include <string> #include <vector> #include <algorithm> #include <numeric> #include <set> #include <map> #include <queue> #include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <ctime> #include <cstring> #include <cctype> #include <cassert> #include <limits> #include <functional> #define re...
Dance Dance Revolution is one of the most popular arcade games in Japan. The rule of this game is very simple. A series of four arrow symbols, up, down, left and right, flows downwards on the screen in time to music. The machine has four panels under your foot, each of which corresponds to one of the four arrows, and y...
#include <bits/stdc++.h> using namespace std; string str; bool sim(bool turn){ int n = str.size(); char pos = str[0]; for(int i=1;i<n;i++){ if(pos == str[i]) return 0; if(turn == 1 && str[i] == 'R') return 0; if(turn == 0 && str[i] == 'L') return 0; pos = str[i]; turn = !turn; } return 1...
Description KULASIS is the name of a system developed and operated by the Higher Education Research and Development Promotion Organization for the purpose of providing information on common subjects throughout the university on the Web, supporting students and faculty members, and improving services. KULASIS started w...
#include<bits/stdc++.h> #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) #define IINF (INT_MAX) #define LEN (1<<8) using namespace std; int G[7][5],dp[7][LEN]; int tmp_G[7][5]; inline int getCost(int x){ return ((x==3)?80:((x==2)?70:((x==1)?60:0))); } inline bool isValid(int x,int y){ return ( 0...
Rotation is one of several popular pocket billiards games. It uses 15 balls numbered from 1 to 15, and set them up as illustrated in the following figure at the beginning of a game. (Note: the ball order is modified from real-world Rotation rules for simplicity of the problem.) [ 1] [ 2][ 3] [ 4][ 5][ 6] [ 7][ 8][ 9]...
#include<iostream> #include<queue> #include<numeric> #include<cstdio> #include<queue> #include<cassert> #include<vector> #include<set> #include<map> using namespace std; #define REP(i,b,n) for(int i=b;i<n;i++) #define rep(i,n) REP(i,0,n) const int inf = 100; const int N = 5; const int dy[]={1,1,-1,-1}; const int dx[]...
J - Tree Reconstruction Problem Statement You have a directed graph. Some non-negative value is assigned on each edge of the graph. You know that the value of the graph satisfies the flow conservation law That is, for every node v, the sum of values on edges incoming to v equals to the sum of values of edges outgoing...
#include<bits/stdc++.h> using namespace std; struct edge{ int to,from; edge(int to,int from) : to(to), from(from) {} edge(){} }; int N,M; bool used[5000]; set<int> G[555]; vector<edge> E; int main(){ cin >> N >> M; for(int i=0;i<M;i++){ int s,t; cin >> s >> t; --s; --t; E.push_back( edg...
Example Input 9 0 0 v 1 0 > 2 0 Output 9
#include <bits/stdc++.h> #define N 3001 using namespace std; typedef pair<int,int> P; int W,H,n; char mp[N+100][N+100]; int compress(int *x1,int w){ vector <int>xs; for(int i=0;i<n;i++)xs.push_back(x1[i]); sort(xs.begin(),xs.end()); xs.erase(unique(xs.begin(),xs.end()),xs.end()); for(int i=0;i<n;i++) x1...
Japanese Animal Girl Library (JAG Library) is famous for a long bookshelf. It contains $N$ books numbered from $1$ to $N$ from left to right. The weight of the $i$-th book is $w_i$. One day, naughty Fox Jiro shuffled the order of the books on the shelf! The order has become a permutation $b_1, ..., b_N$ from left to r...
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<n;i++) #define repn(i,n) for(int i=1;i<=n;i++) #define pb push_back typedef long long ll; typedef pair<ll,ll>P; #define fi first #define sc second #define mp make_pair int n,c; vector<int>za[(1<<18)]; vector<ll>sum[(1<<18)]; vector<ll>num[(1<<...
Problem On a company's network, there are $ n $ computers and $ m $ communication cables that connect them. Computers are distinguished by identifiers from $ 0 $ to $ n -1 $, and communication cables also have identifiers from $ 0 $ to $ m -1 $. Any two different computers currently in the company can communicate wit...
#include <iostream> #include <algorithm> #include <vector> #include <cstdio> #include <cmath> constexpr double EPS = (1e-10); constexpr double INF = 252521; #define equals(a, b) (fabs(a - b) < EPS) std::vector<int> par, rnk; void init(int n) { par.resize(n); rnk.resize(n); for (int i = 0; i < n; i++) { ...
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network. Constraints * $2 \leq n \leq 100,000$ * $0 \leq m \leq 100,000$ * $1 \leq q \leq 10,000$ Input In the first line, two integer $n$ and $m$ are given. $n$ is the ...
#include<iostream> #include<vector> #include<stack> using namespace std; static const int MAX=100000; static const int NIL=-1; int n; vector<int> G[MAX]; int color[MAX]; void dfs(int r,int c){ stack<int> S; S.push(r); color[r]=c; while(!S.empty()){ int u=S.top(); S.pop(); int i; for(i=0;i<G[...
Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III. Constraints * $2 \leq n \leq 100$ * $0 \leq $ the integer assigned to a face $ \leq 100$ Input In the first line, the number of dices $n$ i...
#include<bits/stdc++.h> #include<vector> #include<algorithm> using namespace std; bool sol(vector<int>d1,vector<int>d2){ for(int i=0;i<4;i++){ int tmp1=d1[0]; d1[0]=d1[2], d1[2]=d1[5], d1[5]=d1[3], d1[3]=tmp1; for(int j=0;j<4;j++){ int tmp2=d1[0]; d1[0]=d1[1], d1[1]...
Given n numbers, you can perform the following operation any number of times : Choose any subset of the numbers (possibly empty), none of which are 0. Decrement the numbers in the subset by 1, and increment the numbers not in the subset by K. Is it possible to perform operations such that exactly n - 1 numbers becom...
import sys def Solve(k, ns): counts = {} for n in ns: r1 = n % (k+1) if r1 not in counts: if len(counts) == 2: print "NO" return else: counts[r1] = 1 else: counts[r1]=counts[r1]+1 if len(coun...
After coming to college, Harry decided to have a get together with friends. So he contacted Chahak who is a renowned event organiser. She is given the task of managing this lavish party. Harry is fond of eating and his friend Joseph is fond of cracking jokes. As per Harry’s demand, Chahak kept N food items in the party...
t = int (raw_input()) while(t>0): n,d = map(int,raw_input().split()) a =[] sum = 0 ans =0 mape = map(int,raw_input().split()) for i in mape: sum += i if(sum + (n-1)*10 >d): ans = -1; else: ans = (d- sum)/5 print ans t =t-1
Indian Institute of Technology, Banaras Hindu University is organizing an annual cultural festival. An organizing committee has been formed to get all the preprations done for the fest. The convener of the fest has decided to invite the American Band, Linkin Park to the institute. which in turn gets disadvantageous as ...
# your code goes here mod=1000000007 def power(A,B): res=1 while B>0: if B&1: res=(res*A)%mod A=(A*A)%mod B=B>>1 return res t=input() while t: A,B=raw_input().split(" ") A=int(A) B=int(B) print(power(A,B)) t-=1
The Little Elephant from the Zoo of Lviv currently is on the military mission. There are N enemy buildings placed in a row and numbered from left to right strating from 0. Each building i (except the first and the last) has exactly two adjacent buildings with indices i-1 and i+1. The first and the last buildings have j...
t = int(raw_input()) for _ in xrange(t): n = int(raw_input()) S = raw_input() count = 0 for i in xrange(1, n - 1): if S[i] == '0' and S[i - 1] == '0' and S[i + 1] == '0': count += 1 if n != 1: if S[0] == '0' and S[1] == '0': count += 1 if S[n - 1] == '...
You are given a transparent three-dimensional table, the height equals to H and the base is a two-dimensional table N∙M. The layers of the 3D table are numbered from 1 to H. Each layer is a two-dimensional table, the rows are numbered from 1 to N and the columns are numbered from 1 to M. A pair (i, j) (1 ≤ i ≤ N, 1 ≤ j...
#!/usr/bin/env python2.7 """painting.py: solution to http://www.codechef.com/problems/PNTNG""" import sys dimensions = sys.stdin.readline().split(" ") n, m, h = int(dimensions[0]), int(dimensions[1]), int(dimensions[2]) a = n*m layers = [] maxsquares = 0 for i in xrange(0, h): layer = sys.stdin.readline().split...
You are given a character parenthesis array and an integer array. You need to find the maximum sum sub-array in the integer array such that the corresponding sub-array in the character array has balanced parenthesis. Formally, a balanced parentheses is subset of { [,],{,},<,>,(,) }∗ defined recursively as follows: ...
import sys for __ in range(input()) : n = input() ch = raw_input() ops = {')':'(','}':'{',']':'[','>':'<'} cls = ['}',')','>',']'] lists = map(int,sys.stdin.readline().split()) dp , res , temp = [0]*(n+1) , 0 , 0 for j,i in enumerate(lists) : dp[j] = dp[j-1]+i par_st , max_pr , is_empty = [] , [-1]*(n+1) , ...
Vasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there is ...
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &a) { T x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } a = x *...
Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called "massive refactoring", which can replace names of many variable in jus...
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numCha...
Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide. Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the ...
#include <bits/stdc++.h> using namespace std; int main() { long long n, a; map<long long, long long> m; scanf("%lld", &n); for (long long i = 0; i < n; ++i) { scanf("%lld", &a); ++m[a]; } vector<long long> v; for (auto e : m) { v.push_back(e.second); } sort(v.begin(), v.end()); reverse(v...
Vasya is a big fish lover, and his parents gave him an aquarium for the New Year. Vasya does not have a degree in ichthyology, so he thinks that filling a new aquarium with eels is a good idea. Unfortunately, eels are predators, so Vasya decided to find out how dangerous this idea was. Getting into one aquarium, eels ...
#include <bits/stdc++.h> using namespace std; long long sum[101]; multiset<int> s[101]; int main() { int Q; scanf("%d", &Q); while (Q--) { char c[10]; int x; scanf("%s%d", c, &x); int i = 0; for (; (1 << (i + 1)) <= x; i++) ; if (c[0] == '+') sum[i] += x, s[i].insert(x); el...
Pavel has several sticks with lengths equal to powers of two. He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be ...
#include <bits/stdc++.h> using namespace std; int main() { long long n; cin >> n; long long x, ans = 0, remaining = 0; for (int i = 0; i < n; i++) { cin >> x; long long cur = min(remaining, x / 2); ans += cur; x -= 2 * cur; remaining -= cur; ans += x / 3; x %= 3; remaining += x; ...
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
t=raw_input() l=(len(t)+t.count('a'))//2 print((':(',t[:l])[t.replace('a','')==t[l:]*2])
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m...
import java.util.*; import java.io.*; import java.text.*; public class E1207 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int[] arr = new int[100]; for (int i = 0; i < 100; i++) { arr[i] = (i + 1) << 7; }...
After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells. Polycarp draws snakes with lowercase Latin letters. ...
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { if (a < b) swap(a, b); if (b == 0) return a; while ((a = a % b) != 0) { swap(a, b); } return b; } long long modpow(long long x, int y) { long long res = 1; while (y > 0) { if (y & 1) res = res * x % 1000000007; y = y >> 1; ...
The main characters have been omitted to be short. You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}. Define the sequence v_1, v_2, …, v...
from collections import deque n = int(input()) graph = [list(map(lambda bit: bit == '1', list(input()))) for _ in range(n)] m = int(input()) way = list(map(lambda i: int(i) - 1, input().split())) #print(graph) def dfs(start): queue = deque([start]) d = [-1] * n d[start] = 0 while len(queue) != 0: ...
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
q=int(input()) for i in range(q): n=int(input()) lst2=[] lst1=list(map(int,input().split())) for i in range(len(lst1)): if lst1[i]<=2048: lst2.append(lst1[i]) sum1=sum(lst2) if sum1>=2048: print("YES") else: print("NO")
Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order. The tree in question is a rooted tree with n vertices labelled with distinct integers from 0 to n - 1. The vertex ...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; ...
Bob is playing with 6-sided dice. A net of such standard cube is shown below. <image> He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice. Fo...
import java.io.*; import java.math.*; import java.util.*; import java.util.Arrays; public class Test2{ public static void main(String args[])throws IOException{ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(--t>=0) { long a=sc.nextLong(); long c...
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i. <image>Illustration for the second example, the first...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class CF1287D { int ok = 1; int[] c = ...
Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day. The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he h...
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return a==0?b:gcd(b%a,a);...
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as foll...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ pub...
Slime has a sequence of positive integers a_1, a_2, …, a_n. In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}. In this problem, for the integer multiset s, the median of s is equal to th...
#include <bits/stdc++.h> using namespace std; int n, m, k, l, r, t, qq; int a[1000009]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> qq; while (qq--) { cin >> n >> k; m = 0; for (int i = 0; i < n; ++i) { cin >> a[i]; if (a[i] == k) m = 1; if (a[i] >= ...
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved. This is an interactive problem. You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secre...
#include <bits/stdc++.h> using namespace std; const int INF = 2e9; const long long ML = 4e18; void query(vector<int>& a) { cout << "? " << a.size(); for (int i : a) cout << " " << i; cout << endl; fflush(stdout); } void solve() { int n; cin >> n; vector<vector<int>> edges(n + 1); for (int i = (0); i < (...
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling. Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t...
import java.util.*; import java.io.*; public class Codeforces { static int MAX = (int)1e5+1; static boolean leaf[]; static int count[],n; public static void main(String[] args) { Scanner input = new Scanner(System.in); int test = input.nextInt(); while(test-->0){ n = input.nextInt(); count = new int[n]...
You are given an array a, consisting of n integers. Each position i (1 ≤ i ≤ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearra...
import sys from sys import stdin import math import fractions #Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1)) def iinput(): return int(input()) def minput(): return map(int,input().split()) def linput(): return list(map(int,input().split())) def fiinput(): return int(stdin.readline()) def fminput(...
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl...
#import numpy as np #import collections #import sys # ============================================================================= #def get_primeFactor(n): # res=[1] # x=2 # while x*x<=n: # while n%x==0: # res.append(x) # n//=x # x+=1 # if n>1:res.append(n) # return r...
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has an array a of n integers. The numbers in the array are numbered starting from 1. Unfortu...
#include <bits/stdc++.h> using namespace std; map<int, vector<int> > mm; int a[100005]; int li[100005]; long long ans; int n, m; int islucky(int x) { for (; x > 0; x /= 10) if ((x % 10) != 4 && (x % 10) != 7) return false; return true; } long long work() { int i, j, k, up_k, x; long long sum; set<int> vis...
You are given an array of integers b_1, b_2, …, b_n. An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≤ i ≤ n) at least one of these conditions is true: * b_i = a_i, or * b_i = ∑_{j=1}^{i} a_j. Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should pri...
#include <bits/stdc++.h> using namespace std; template<class t> inline t read(t &x){ char c=getchar();bool f=0;x=0; while(!isdigit(c)) f|=c=='-',c=getchar(); while(isdigit(c)) x=(x<<1)+(x<<3)+(c^48),c=getchar(); if(f) x=-x;return x; } template<class t> inline void write(t x){ if(x<0) putchar('-'),wr...
Market stalls now have the long-awaited game The Colder Scrools V: Nvodsk. The game turned out to be difficult as hell and most students can't complete the last quest ("We don't go to Nvodsk..."). That threatened winter exams. The rector already started to wonder whether he should postpone the winter exams till April (...
#include <bits/stdc++.h> using namespace std; char s[155]; const int INF = 1e9; int a[155], best[155][155], f[155][155][155], flag, l, r, L, i, j, k, p, m, n; void upd(int x) { if (x > f[i][j][k]) f[i][j][k] = x; } int main() { scanf("%d", &n); for (i = 1; i <= n; i++) { scanf("%d", &a[i]); if (a[i] == -1...
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me. It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h...
#include <bits/stdc++.h> using namespace std; /*string::npos*/ int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a); } int main(){ int t; cin>>t; while(t--) {int n; cin>>n; string str; cin>>str; int arr[26]={0}; int c=0; for(int i=0;i<str.length();i++){ arr[str[i]-97]++;...
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the s...
#include <bits/stdc++.h> using namespace std; string s, t; int dp[5005][5005]; int get(int i, int j) { if (dp[i][j] != -1) return dp[i][j]; if (i >= s.size() or j >= t.size()) return 0; int ret = get(i, j + 1); if (s[i] == t[j]) ret = (ret + 1 + get(i + 1, j + 1)) % 1000000007; return dp[i][j] = ret; ; } in...
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates....
#include <bits/stdc++.h> using namespace std; int f[1000001]; vector<pair<int, int> > v; int main() { int n, m, i, j, k; cin >> n >> m; for (i = 0; i < m; i++) { cin >> j >> k; v.push_back(make_pair(j, k)); } for (i = 0; i < m; i++) { int64_t x1 = v[i].first, y1 = v[i].second; for (j = i + 1; ...
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows. Initially, the ...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:60000000") using namespace std; template <class T> T sqr(T x) { return x * x; } double const pi = 3.1415926535897932384626433832795; int const inf = (int)1e9; long long const inf64 = (long long)4e18; const string name = "b"; const int NMAX = 10010; int n, num, ...
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To cyclically shift a table row one cell to the right means to move the valu...
import static java.lang.Math.*; import java.io.*; import java.math.BigInteger; import java.util.*; public class aaa { public static void solve() { int n = nextInt(), m = nextInt(); int inf = Integer.MAX_VALUE / 2; int arr[][] = new int[n][m]; for (int i = 0; i < n; i++) { char ch[] = nextLine().toCharArr...
Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy. We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right f...
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class ProblemB { public static void main(String[] args) throws IOException { ProblemB...
The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a m...
#include <bits/stdc++.h> using namespace std; bool solve(const vector<vector<int> > &v, bool *visited, int s, int q) { if (visited[s]) return false; visited[s] = true; for (int i = 1; i <= v.size(); i++) { if (v[s][i] == 1) { if (i == q) return true; if (solve(v, visited, i, q)) return true; }...
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: * Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). * The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + a...
import sys from collections import defaultdict, Counter from itertools import permutations, combinations from math import sin, cos, asin, acos, tan, atan, pi sys.setrecursionlimit(10 ** 6) def pyes_no(condition, yes = "YES", no = "NO", none = "-1") : if condition == None: print (none) elif condition : pri...
You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest. The forest The Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant....
import java.io.*; import java.util.*; import com.sun.org.apache.regexp.internal.RE; public class D { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.i...
On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored. The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds...
//package e; import java.util.*; public class Main { public void run() throws Exception{ Scanner in = new Scanner(System.in); int n = in.nextInt(); double t = in.nextDouble(); double x[] = new double[n]; double m[] = new double[n]; double v[] = new double[n]; for(int i=0;i<n;i++){ x[i] = in.nextDo...
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b. Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said h...
#include <bits/stdc++.h> using namespace std; const int INF = ~0u >> 1; int main() { int n, m, i, j, a, b; cin >> n >> m >> i >> j >> a >> b; int num = 10000000; if ((i + a <= n || i - a >= 1) && (j + b <= m || j - b >= 1)) { int cnta = i - 1; int cntb = j - 1; if (cnta % a == 0 && cntb % b == 0 && ...
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1. Initially all vertices contain number 0. Then come q queries, each query has one of the two types: * The format of the query: 1 v x k. In response to the query, you need to add to the number at vert...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 100, md = 1e9 + 7; long long add[maxn * 4], seg[maxn * 4], lazy1[maxn * 4], lazy2[maxn * 4]; vector<int> adj[maxn]; int hgt[maxn], ftm[maxn], stm[maxn], n, type, tm, q; void dfs(int v, int h) { stm[v] = tm++; hgt[v] = h; for (int i = 0; i < (int...
The Finals of the "Russian Code Cup" 2214 will be held in n hotels. Two hotels (let's assume that they are the main hotels), will host all sorts of events, and the remaining hotels will accommodate the participants. The hotels are connected by n - 1 roads, you can get from any hotel to any other one. The organizers wo...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5, Mod = 1e9 + 7, MAXN = 1e5, Lg = 27, M = 1e7 + 10, P = 727, Sq = 320; const long long inf = 3e18 + 10; int seg[4 * N], lz[4 * N], Par[N][Lg], St[N], Ed[N], H[N], Ans[N], Tim = 1, n, ...
DZY loves chemistry, and he enjoys mixing chemicals. DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pour...
#include <bits/stdc++.h> using namespace std; long long ans; int pa[55]; int r[55]; int findset(int x) { return pa[x] != x ? pa[x] = findset(pa[x]) : x; } int f[55] = {0}; long long mm[55]; void get_2() { mm[0] = 1; for (int i = 1; i < 55; i++) mm[i] = mm[i - 1] * 2ll; } int main() { get_2(); ans = 1; int n, ...
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work. Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2...
import java.io.*; import java.util.*; public class C_GeorgeAndJob { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader inp = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ...
The New Year celebrations in Berland last n days. Only this year the winter is snowless, that’s why the winter celebrations’ organizers should buy artificial snow. There are m snow selling companies in Berland. Every day the i-th company produces wi cubic meters of snow. Next day the snow thaws and the company has to p...
#include <bits/stdc++.h> using namespace std; int n, m, w[500000], c[500000], a[500000], W, s[500000]; double t[500000]; double r_fraction; long long r_integer; void take(int nr, int amount) { if (!amount) return; r_integer += (long long)amount * c[nr] / w[nr]; int p = (long long)amount * c[nr] % w[nr], q = w[nr]...
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation. In...
#include <bits/stdc++.h> using namespace std; int inversions(const vector<int> &p) { int cnt = 0; int n = p.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (p[i] > p[j]) { ++cnt; } } } return cnt; } double solve(vector<int> p, int k) { if (k == 0) { ...
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line...
import sys n = int(sys.stdin.readline ()) a= [int (x) for x in sys.stdin.readline ().split ()] assert len(a) == n b = [int (x) for x in sys.stdin.readline ().split ()] assert len(b) == n ans = [] for i in range (n): j = i; while b[j] != a[i] : j += 1 while j > i: ans += [(j, j + 1)] ...
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital. The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has th...
#include <bits/stdc++.h> using namespace std; vector<vector<long long> > dp; vector<vector<vector<long long> > > k; int n, m; void init() { dp.assign(2 * n + 1, vector<long long>(2 * n + 1, -1LL)); k.assign(2 * n + 1, vector<vector<long long> >(2 * n + 1, vector<long long>(5, 0LL))); } void in() { cin ...
Dasha decided to bake a big and tasty layer cake. In order to do that she went shopping and bought n rectangular cake layers. The length and the width of the i-th cake layer were ai and bi respectively, while the height of each cake layer was equal to one. From a cooking book Dasha learned that a cake must have a form ...
#coding:utf-8 n = int(raw_input()) cakes = [] for i in xrange(n): cakes.append(sorted(map(int, raw_input().split()))) #print cakes cakes.sort(key = lambda x:x[0]) ans = 0 w = [] for i in xrange(n-1,-1,-1): w.append(cakes[i][1]) w.sort() for j in xrange(len(w)): tmp = cakes[i][0]*w[j]*(len(w)-j)...
You are given a string s of length n, consisting of first k lowercase English letters. We define a c-repeat of some string q as a string, consisting of c copies of the string q. For example, string "acbacbacbacb" is a 4-repeat of the string "acb". Let's say that string a contains string b as a subsequence, if string ...
#include <bits/stdc++.h> using namespace std; inline int nn(char c) { return c - 'a'; } inline char cc(int n) { return (char)(n + 'a'); } struct info { char begin; char end; vector<int> transitions; info() : transitions(100, 0) {} info(char a, char b, vector<int> c) : begin(a), end(b), transitions(c) {} voi...
Petya has recently started working as a programmer in the IT city company that develops computer games. Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to pa...
#include <bits/stdc++.h> using namespace std; template <typename T> struct Pt { T x, y; Pt() {} Pt(T _x, T _y) : x(_x), y(_y) {} Pt(const Pt<T> &p) : x(p.x), y(p.y) {} Pt<T> operator+(const Pt<T> p) const { return Pt<T>(x + p.x, y + p.y); } Pt<T> operator-() const { return Pt<T>(-x, -y); } Pt<T> operator-...
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi. Today Vasily de...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3f; const int MAX = 1000011; int n; int h[MAX]; const int MOD = int(1e9) + 7; inline int add(const int a, const int b, const int mod = MOD) { return (a + b >= mod) ? (a + b - mod) : (a + b); } inline int s...
After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar. Alyona has her favourite positive integer k and because she is to...
#include <bits/stdc++.h> using namespace std; string s1, s2; int n, m; int dp[1001][1001][11][2]; int solve(int a, int b, int c, int d) { if (a == n || b == m || c == 0) return 0; if (dp[a][b][c][d] != -1) return dp[a][b][c][d]; int &r = dp[a][b][c][d]; if (d) { if (s1[a] == s2[b]) { r = max(r, 1 + so...
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are abou...
import collections import copy n, q = map(int, input().split()) Q = collections.deque() A = n * [0] B = copy.copy(A) L = [] s = n = 0 for _ in range(q): y, x = map(int, input().split()) if 2 > y: x -= 1 Q.append(x) B[x] += 1 A[x] += 1 s += 1 elif 3 > y: x -= ...