input
stringlengths
29
13k
output
stringlengths
9
73.4k
There is a plane like Figure 1 with 8 vertical and 8 horizontal squares. There are several bombs on that plane. Figure 2 shows an example (● = bomb). | □ | □ | □ | □ | □ | □ | □ | □ --- | --- | --- | --- | --- | --- | --- | --- □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □...
import java.util.Scanner; public class Main { boolean[][] map; void run() { Scanner sc = new Scanner(System.in); sc.next(); int t = 1; while (sc.hasNext()) { map = new boolean[8][8]; for (int y = 0; y < 8; y++) { St...
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift. Let's create a program for the oil tree shop that outputs the number of pa...
#include<iostream> using namespace std; int X,Y; int dp[20][20]; char maps[20][20]; int bun(int x,int y); int dx[3]={-1,0,1}; int main(){ while(1){ cin>>X>>Y; if(X==0&&Y==0){ break; } for(int i=1;i<=Y;i++){ for(int j=1;j<=X;j++){ cin>>maps[i][j]; dp[i][j]=0; } } int ans=0; ...
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the rig...
#include<iostream> #include<vector> #include<algorithm> using namespace std; typedef pair<int, int> P; int main() { int H, W, N; cin >> H >> W >> N; vector<P> px(N), py(N); for (int i = 0; i < N; i++) { int a, b; cin >> a >> b; px[i] = P(a, b); py[i] = P(b, a); } sort(px.begin(), px.end()); sort(py.b...
JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors. On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + ...
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAX_N = int(1e5 + 5); #define REP(i, n) for (int i = 0; i < n; i++) int main() { ll n, k, t[MAX_N], d[MAX_N], ans = 0; cin >> n >> k; REP(i,n){ cin >> t[i]; } REP(i,n-1){ d[i] = t[i+1] - t[i]; } so...
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template. A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from th...
import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); while(n != 0){ LinkedList<Line> smpl = new LinkedList<Line>(); Line line = new Line(); int m = sc.nextInt(); int ox = s...
You are constructing a triangular pyramid with a sheet of craft paper with grid lines. Its base and sides are all of triangular shape. You draw the base triangle and the three sides connected to the base on the paper, cut along the outer six edges, fold the edges of the base, and assemble them up as a pyramid. You are...
#include<bits/stdc++.h> #define EPS (1e-7) #define equals(a,b) (fabs((a)-(b)) < EPS) #define COUNTER_CLOCKWISE 1 #define CLOCKWISE -1 #define ONLINE_BACK 2 #define ONLINE_FRONT -2 #define ON_SEGMENT 0 #define REP(i,s,n) for(int i=s;i<n;i++) #define rep(i,n) REP(i,0,n) using namespace std; class Point{ public: dou...
Fun Region Dr. Ciel lives in a planar island with a polygonal coastline. She loves strolling on the island along spiral paths. Here, a path is called spiral if both of the following are satisfied. * The path is a simple planar polyline with no self-intersections. * At all of its vertices, the line segment directions ...
#include <bits/stdc++.h> using namespace std; mt19937 mt(48); #define rep(i, a, b) for(int i = a; i < (b); ++i) #define trav(a, x) for(auto& a : x) #define all(x) x.begin(), x.end() #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; using ld = long double; templa...
<!-- Problem D --> Tally Counters A number of tally counters are placed in a row. Pushing the button on a counter will increment the displayed value by one, or, when the value is already the maximum, it goes down to one. All the counters are of the same model with the same maximum value. <image> Fig. D-1 Tally Cou...
#include <iostream> using namespace std; int n,m,s[1000],a[1000],b[1000],ans,dp[1000][1001]; int main(void){ while(1){ cin>>n>>m; if(n==0&&m==0)return 0; ans=1e9; for(int i=0;i<n;i++)for(int j=0;j<=n;j++)dp[i][j]=1e9; for(int i=0;i<n;i++)cin>>a[i]; for(int i=0;i<n;i++)cin>>b[i]; for(int ...
Memory match is a single-player game which employs a set of 2M cards. Each card is labeled with a number between 1 and M on its face. For each number i (1 ≤ i ≤ M), there are exactly two cards which have the number i. At the start of the game, all cards are shuffled and laid face down on a table. In each turn you choos...
#include<cstdio> #define rep(i,n) for(int i=0;i<(n);i++) using namespace std; // dp[i][j] := ( i 組のカードがあり、そのうち j 種類の(片方の)場所がわかっている状態でのミスマッチ回数の期待値 ) double dp[501][501]; double dfs(int i,int j){ if(i==0) return 0; if(dp[i][j]!=-1) return dp[i][j]; // 一枚目を、まだ中身がわかっていない 2*i-j 枚の中から選ぶ // 確率 p=j/(2*i-j) で場所が知れているカー...
Saving electricity is very important! You are in the office represented as R \times C grid that consists of walls and rooms. It is guaranteed that, for any pair of rooms in the office, there exists exactly one route between the two rooms. It takes 1 unit of time for you to move to the next room (that is, the grid adja...
#include <cstdio> #include <algorithm> #include <cstring> #include <queue> #include <vector> using namespace std; #define foreach(i,v) for(int i=0;i<(int)v.size();i++) const int N=55; const int dx[]={0,1,0,-1}; const int dy[]={1,0,-1,0}; char mz[N][N]; int con[N][N],on[N][N],off[N][N]; int pre[N][N],dis[N][N]; int tl[...
Let f(x) = a0 + a1x + a2x2 + ... + adxd be the function where each ai (0 ≤ i ≤ d) is a constant integer (and ad is non-zero) and x is a variable. Your task is to write a program that finds all complex integer solutions of the equation f(x) = 0 for a given f(x). Here, by complex integers, we mean complex numbers whose r...
//Bairstow #include <cstdio> #include <iostream> #include <vector> #include <algorithm> #include <utility> #include <complex> #include <cmath> using namespace std; #define EPS_S 1e-9 #define EPS 1e-4 typedef complex<double> P; typedef pair<int,int> pii; void bairstow(double &p, double &q, vector<double> &a){ ...
Fox Ciel is developing an artificial intelligence (AI) for a game. This game is described as a game tree T with n vertices. Each node in the game has an evaluation value which shows how good a situation is. This value is the same as maximum value of child nodes’ values multiplied by -1. Values on leaf nodes are evaluat...
#include<bits/stdc++.h> using namespace std; using Int = long long; const Int inf = 1LL<<55; Int n; Int p[111]; vector<Int> graph[111]; map<Int, Int> mp; using Pi = pair<Int, Int>; Pi val[111][222][222]; Int dp_min[111][222][222]; Int dp_max[111][222][222]; bool visited[111][222][222]; Pi dfs(Int v, Int a, Int b)...
D: Complex Oracle --Complex Oracle- problem * This problem is a reactive problem. In other words, it is necessary to create a program that derives the correct answer by interactively responding to the program prepared on the server side. Also, since the program on the server side also shares computer resources, the s...
#include "bits/stdc++.h" #include<unordered_map> #include<unordered_set> #pragma warning(disable:4996) using namespace std; using ld = long double; const ld eps = 1e-9; //// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_...
You are given $N$ distinct points on the 2-D plane. For each point, you are going to make a single circle whose center is located at the point. Your task is to maximize the sum of perimeters of these $N$ circles so that circles do not overlap each other. Here, "overlap" means that two circles have a common point which ...
#include <cstdio> #include <cstdint> #include <cmath> #include <vector> #include <algorithm> #include <numeric> #include <utility> #include <tuple> #include <limits> template <typename Tp> class linear_program { // optimize given linear program (in a standard form) with simplex algorithm public: using size_type =...
Problem Given a convex polygon consisting of $ N $ vertices. When considering an equilateral triangle that includes all the vertices of the convex polygon, find the minimum value of the length of one side of the equilateral triangle. Constraints The input satisfies the following conditions. * $ 3 \ le N \ le 10000...
#include<iostream> #include<iomanip> #include<vector> #include<cmath> using namespace std; struct Point{ double x,y; }; int n; Point a[11111]; Point b[11111]; void conv(double theta) { double C=cos(-theta); double S=sin(-theta); for(int i=0;i<n;i++) { b[i].x=a[i].x*C-a[i].y*S; b[i].y=a[i].x*S+a[i].y*C; } } in...
For given two segments s1 and s2, print the coordinate of the cross point of them. s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. * The given segments have a cross point and are not in parallel. Input The...
#include<bits/stdc++.h> using namespace std; #define ldb double bool Bar; const ldb mi=1e-9; int n,mk; ldb q,w,a1,a2; int sign(ldb a) { if(abs(a)<mi)return 0; return a>0?1:-1; } struct Point { ldb x,y; ldb len() { return x*x+y*y; } int operator ==(const Point& a)const { return abs(x-a.x)<=mi&&abs(y-a.y)<=mi;...
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically. Constraints * $1 \leq n, m \leq 1,000$ * $0 \leq a_i, b_i \leq 1,000$ Input The input is given in the following format. $n$ $a_0 \; a_1, ..., \; a_{n-1}$ $m$ $b_0 \; b_1, ..., \; b_{m-1}$ The num...
#include <bits/stdc++.h> // clang-format off using Int = long long; #define REP_(i, a_, b_, a, b, ...) for (Int i = (a), lim##i = (b); i < lim##i; i++) #define REP(i, ...) REP_(i, __VA_ARGS__, __VA_ARGS__, 0, __VA_ARGS__) struct SetupIO { SetupIO() { std::cin.tie(nullptr), std::ios::sync_with_stdio(false), std::cout <...
Your friend Сhef has prepared a rectangular cake for you. Both of you want to divide the cake among yourselves. Your friend is generous enough to let you choose your share first. You have decided to take two pieces.For the first piece you make a rectangular cut (each side of this cut is parallel to the corresponding si...
for t in xrange(int(raw_input())): r1=map(int,raw_input().split()) r2=map(int,raw_input().split()) area1=(r1[2]-r1[0])*(r1[3]-r1[1]) area2=(r2[2]-r2[0])*(r2[3]-r2[1]) r3=[] r3.append(max(r1[0],r2[0])) r3.append(max(r1[1],r2[1])) r3.append(min(r1[2],r2[2])) r3.append(min(r1[3],r2[3])) area3=max(r3[2]-r3[0],0)*...
There are 100 houses located on a straight line. The first house is numbered 1 and the last one is numbered 100. Some M houses out of these 100 are occupied by cops. Thief Devu has just stolen PeePee's bag and is looking for a house to hide in. PeePee uses fast 4G Internet and sends the message to all the cops that a t...
t = int(input()) for test in xrange(t): chk = [1]*101 m,x,y = map(int,raw_input().split()) arr = map(int,raw_input().split()) for v in xrange(m): for e in xrange(arr[v]-(x*y),arr[v]+(x*y)+1,1): try: if e>=0: chk[e] = 0 except: ...
Prof. R.K.Vats of NIT Hamirpur has given a problem to the whole class and has imposed a condition that he won't give attendance to those who don't solve it within time. He gave the equation , ax+by=c where a, b, c are three positive integers. The problem is to determine if there exists at least one solution for some in...
from fractions import gcd t=int(raw_input()) counter=0 for i in range(t): counter+=1 a,b,c=map(int,raw_input().split()) gcdans=gcd(a,b) if c%gcdans==0: print "Case "+str(counter)+": Yes" else: print "Case "+str(counter)+": No"
Mason is yet again in danger. Consider an N digit number A. let the new number formed by reversing the digits of A be called B . Mason has to tell that how many N digit numbers A exist such that A + B = 10^N - 1 ? Note: A should not have any leading zeroes ! Quick. Help. over and out. Input First line will cont...
for x in range(input()): n = input() print "9".ljust(((n/2)),"0") if n%2==0 else "0"
You are in charge of painting the lanes on a 500 meter race track for a forthcoming amateur track event. There are 9 lanes in total which means you must paint 10 lines around the track to delimit these lanes. Fortunately, you have special equipment that will help you paint these lanes very quickly. This equipment has...
# code chef - easy - racing lanes - racelane.py t = int(raw_input()) RACELENGTH = 500 for iter in range(t): b = int(raw_input()) racetrack = [0]*(RACELENGTH+1) for bubble in range(b): s,e,l = map(int, raw_input().split()) mask = 1<<l # turn l into bit mask for i in range(s, ...
Problem description. One day Toretto wanted to make some extra money. We all know his obsession with cars so all he could manage to get hold of, was some information regarding the buying and selling prices of cars for the next N days. The buying and selling prices for one car on day i are same and equal to Pi where (...
t=int(raw_input()) while t>0: n,m=[int(x) for x in raw_input().split()] p=[int(x) for x in raw_input().split()] if n==1: print m else: ans=m for i in range (len(p)): if p[i]<=m: for j in range(i,n): if p[j]>p[i]: ...
Ivan has n songs on his phone. The size of the i-th song is a_i bytes. Ivan also has a flash drive which can hold at most m bytes in total. Initially, his flash drive is empty. Ivan wants to copy all n songs to the flash drive. He can compress the songs. If he compresses the i-th song, the size of the i-th song reduce...
n,m = input().split() n=int(n) m=int(m) songs=list() for i in range(n): songs.append([int(c) for c in input().split()]) def sumList(lista,inx): sum=0 for i in range(len(lista)): sum+=lista[i][inx] return sum songs=sorted(songs,key=lambda x: x[1]-x[0]) suma = sumList(songs,0) for i in ra...
There are two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route. At each station one can find a sorted list of moments of time when a...
#include <bits/stdc++.h> #pragma warning(disable : 4996) using namespace std; template <class T> inline void chkmin(T &a, T b) { if (a > b) a = b; } template <class T> inline void chkmax(T &a, T b) { if (a < b) a = b; } const int MAXN = 2e5 + 7; long long a[MAXN]; int x[MAXN]; long long b[MAXN]; int main() { ios_...
You are given an integer array a_1, a_2, …, a_n. The array b is called to be a subsequence of a if it is possible to remove some elements from a to get b. Array b_1, b_2, …, b_k is called to be good if it is not empty and for every i (1 ≤ i ≤ k) b_i is divisible by i. Find the number of good subsequences in a modulo...
#!/usr/bin/env python """ This file is part of https://github.com/Cheran-Senthil/PyRival. Copyright 2018 Cheran Senthilkumar all rights reserved, Cheran Senthilkumar <hello@cheran.io> Permission to use, modify, and distribute this software is given under the terms of the MIT License. """ from __future__ import divisi...
Recently, the Fair Nut has written k strings of length n, consisting of letters "a" and "b". He calculated c — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time. Then, he lost his sheet with strings. He remembers that all written strings were lexicog...
#include <bits/stdc++.h> using namespace std; const int N = 5e5 + 1; int c[N]; int main() { int i, j, n, k; string s, t, s1, t1; ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k; cin >> s >> t; if (s == t || k == 1) { cout << n; return 0; } for (i = 0; i < s.size(); +...
You are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings. Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string ...
from bisect import bisect_left as bl, bisect_right as br, insort import sys import heapq # from math import * from collections import defaultdict as dd, deque def data(): return sys.stdin.readline().strip() def mdata(): return map(int, data().split()) # sys.setrecursionlimit(1000000) mod = 998244353 n=int(data()) s=da...
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled. Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at...
#include <bits/stdc++.h> using namespace std; long long n, m, k, t, i, j, sig = 0, h, num; long long a[5005]; long long dis[5005]; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); memset(a, 0, sizeof(a)); ; for (i = 1; i <= 5000; i++) dis[i] = 0x3f3f3f3f; cin >> n >> m; int x, y; for (i ...
Owl Pacino has always been into trees — unweighted rooted trees in particular. He loves determining the diameter of every tree he sees — that is, the maximum length of any simple path in the tree. Owl Pacino's owl friends decided to present him the Tree Generator™ — a powerful machine creating rooted trees from their ...
#include <bits/stdc++.h> using namespace std; int n, q; char s[200005]; struct SEGMENTTREE { int d, mx1, mx2, mx3, mx4, mx5; } t[200005 << 2]; void maintain(int u) { t[u].d = t[u << 1].d + t[u << 1 | 1].d; t[u].mx1 = max(t[u << 1].mx1, t[u << 1].d + t[u << 1 | 1].mx1); t[u].mx2 = max(t[u << 1].mx2, -2 * t[u << ...
Nauuo is a girl who loves traveling. One day she went to a tree, Old Driver Tree, literally, a tree with an old driver on it. The tree is a connected graph consisting of n nodes and n-1 edges. Each node has a color, and Nauuo will visit the ODT through a simple path on the tree in the old driver's car. Nauuo wants t...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; bool f = 0; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) f = (ch == '-'); for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48); return f ? -x : x; } const int maxn = 4e5 + 7; int n, m, c[maxn], fa[ma...
Tokitsukaze and CSL are playing a little game of stones. In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; int a[maxn], n, dui, tot; void over() { cout << "cslnb"; exit(0); } int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; sort(a + 1, a + 1 + n); for (int i = 2; i <= n; i++) { if (a[i - 1] == 0 && a[i] == 0) over(); ...
This is a harder version of the problem. The difference is only in constraints. You are given a rectangular n × m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a c...
#include <bits/stdc++.h> const int M = 15; const int N = 3005; const int S = 4505; using namespace std; int k; int T, s; int n, m; int dI[N]; int Id[S]; int val[N]; int sum[S]; int f[N][S]; int row[N][M]; const int I = 1000000007; void out_p(int x) { while (x) { if (x & 1) putchar('1'); else putch...
You have n × n square grid and an integer k. Put an integer in each cell while satisfying the conditions below. * All numbers in the grid should be between 1 and k inclusive. * Minimum number of the i-th row is 1 (1 ≤ i ≤ n). * Minimum number of the j-th column is 1 (1 ≤ j ≤ n). Find the number of ways to ...
def Solve(n,k): mod = 10**9+7 max_n = 10**4 #precalcular los factoriales fac = [1] + [0] * max_n fac_i = [1] + [0] * max_n for i in range(1,n+1): fac[i] = fac[i-1] * (i) % mod fac_i[i] = fac_i[i- 1] * pow(i,mod-2,mod) % mod #calculo de las combinaciones con factorial inverso def...
You are given a set of n≥ 2 pairwise different points with integer coordinates. Your task is to partition these points into two nonempty groups A and B, such that the following condition holds: For every two points P and Q, write the [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) between them o...
#include <bits/stdc++.h> using namespace std; int n, x[1005], y[1005], a[2][2]; int calc() { return (a[0][0] > 0) + (a[1][0] > 0) + (a[1][1] > 0) + (a[0][1] > 0); } int main() { scanf("%d", &n); bool flag = 0; int py = 1000000; for (int i = 1; i <= n; ++i) { scanf("%d%d", &x[i], &y[i]); x[i] += py; ...
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class A { // public static class Cell { int x; int y; public Cell(int x, in...
This is an easier version of the problem. In this version n ≤ 1000 The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company ...
import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import * from collections import defaultdict, deque, Counter import math, string from heapq import * from operator import add from itertools import accumulate BUFSIZE = 8192 sys.setrecursionlimit(10 ** 5) class FastIO(IOBase): ...
There is a rectangular grid of size n × m. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell (i, j) is c_{i, j}. You are also given a map of directions: for each cell, there is a direction s_{i, j} which is one of the four characters 'U', 'R', 'D' and 'L'. * If s_{i, j} is 'U' then t...
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; const long long inff = 0x3f3f3f3f3f3f3f3f; using namespace std; const int N = 1e6 + 8; int t, n, m, vis[N], VS[N], qw, ans, sz[N], ans1, VV[N]; pair<int, int> top[N]; string a[N], b[N]; vector<int> g[N]; int id(int x, int y) { return (x - 1) * m + y ...
During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: <image> The cell with coordinates (x, y) is at the intersection of x-th row ...
t = int(input()) for _ in range(t): x1, y1, x2, y2 = map(int, input().split()) print((x2-x1)*(y2-y1)+1)
You are given a permutation a_1, a_2, ..., a_n of numbers from 1 to n. Also, you have n sets S_1,S_2,..., S_n, where S_i=\\{a_i\}. Lastly, you have a variable cnt, representing the current number of sets. Initially, cnt = n. We define two kinds of functions on sets: f(S)=min_{u∈ S} u; g(S)=max_{u∈ S} u. You can obt...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; using vi = vector<int>; using vll = vector<ll>; const int nax = 3000 * 1007; int n, q; int tab[nax]; ll los[nax]; int m; pii cons[nax]; ll xo[nax]; map<pii, vi> pozy; map<pii, vll> hasze; unordered_map<ll, int> mapa; int wyn...
You are given a binary string s consisting of n zeros and ones. Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should no...
t=int(input()) for _ in range(t): n=int(input()) s=str(input()) arr=[] for i in range(n): arr.append(int(s[i])) ones=[] zeros=[] vals=[] k=0 for i in range(n): p=arr[i] if(p==0): if(ones==[]): zeros.append(k+1) vals....
In the Kingdom of Wakanda, the 2020 economic crisis has made a great impact on each city and its surrounding area. Cities have made a plan to build a fast train rail between them to boost the economy, but because of the insufficient funds, each city can only build a rail with one other city, and they want to do it toge...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using db = double; using str = string; using pi = pair<int, int>; using pl = pair<ll, ll>; using pd = pair<db, db>; using vi = vector<int>; using vb = vector<bool>; using vl = vector<ll>; using vd = vector<db>; using vs = vector...
You are given an array a_1, a_2, …, a_n of integers. This array is non-increasing. Let's consider a line with n shops. The shops are numbered with integers from 1 to n from left to right. The cost of a meal in the i-th shop is equal to a_i. You should process q queries of two types: * 1 x y: for each shop 1 ≤ i ≤ ...
#include <bits/stdc++.h> using namespace std; int n, q; int p[200005]; struct node { int l, r; long long sum; int Min, Max; long long lazy; } tree[200005 * 4]; void pushup(node& k, node& l, node& r) { k.sum = l.sum + r.sum; k.Min = min(l.Min, r.Min); k.Max = max(l.Max, r.Max); } void pushup(int x) { pushu...
Monocarp would like to open a bakery in his local area. But, at first, he should figure out whether he can compete with other shops. Monocarp plans that the bakery will work for n days. On the i-th day, a_i loaves of bread will be baked in the morning before the opening. At the end of the n-th day, Monocarp will sell ...
#include<bits/stdc++.h> #define ll long long #define pb push_back #define lowbit(x) ((x)&(-(x))) #define mid ((l+r)>>1) #define lson lc[rt], l, mid #define rson rc[rt], mid+1, r #define fors(i, a, b) for(int i = (a); i < (b); ++i) using namespace std; const int maxn = 2e5 + 5; const int lim = 1e9 + 7; const int inf = 0...
Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool. It takes the first swimmer exactly a minutes to swim across the entire pool and come back, exactly b minutes for the second swimmer and c minutes for the third. Hence, the first swimmer will b...
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--){ long long int a,b,c,p,m,a1,a2,a3; cin >> p >> a >> b >> c; a1=((p+a-1)/a)*a; a2=((p+b-1)/b)*b; a3=((p+c-1)/c)*c; if(a1<=a2 && a1<=a3){ m=a1-p; } ...
Phoenix is playing with a new puzzle, which consists of n identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below. <image> A puzzle piece The goal of the puzzle is to create a square using the n pieces. He is allowed to rotate and move the pieces around, but none of them can overlap an...
import math def issqr(x): root = int(math.sqrt(x)) return root*root == x for i in range(int(input())): n = int(input()) print("YES" if (n % 4 == 0 and issqr(n//4)) or (n % 2 == 0 and issqr(n//2)) else "NO")
You are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers. Determine if you can split it into exactly n pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1). Input The...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr); int t; cin >> t; while(t--) { int even = 0, odd = 0; int n; cin >> n; for(int i = 0; i < 2 * n; i++) { int x; cin >> x; even += x % 2 == 0; odd += x % 2 == 1; } if(even == odd) { cou...
According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'...
public class Main{ public static void main(String[]args){ java.util.Scanner input = new java.util.Scanner(System.in); String[] x = new String[input.nextInt()]; int l = input.nextInt(); boolean m = true; for(int i = 0; i < x.length; i++){ x[i] = input.next(); for(int j = 0 ; j < l-1 && l > 1; j++) i...
Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: * A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. * Bob won some programming competition and got a 2x MB memory ...
import java.math.BigInteger; import java.util.Scanner; /** * * @author Hoang Dai */ public class BoBSele { int N = 5007; BigInteger dp[] = new BigInteger[N]; int n; int st[] = new int[N]; int x[] = new int[N]; void solve(){ Scanner ac = new Scanner(System.in); n = ac.nex...
Furik loves painting stars. A star is a shape that results if we take a regular pentagon and paint all diagonals in it. <image> Recently he decided to teach Rubik to paint stars. After many years of training Rubik could paint stars easily. But now Furik decided to test Rubik and complicated the task. Rubik must pain...
#include <bits/stdc++.h> using namespace std; const double pi = acos(-1); pair<double, double> operator+(const pair<double, double>& a, const pair<double, double>& b) { return {a.first + b.first, a.second + b.second}; } pair<double, double> operator-(const pair<double, double>& a, ...
You've got a undirected tree s, consisting of n nodes. Your task is to build an optimal T-decomposition for it. Let's define a T-decomposition as follows. Let's denote the set of all nodes s as v. Let's consider an undirected tree t, whose nodes are some non-empty subsets of v, we'll call them xi <image>. The tree t i...
#include <bits/stdc++.h> using namespace std; const int MAX = 100000 + 5; vector<int> adj[MAX]; vector<pair<int, int> > edges, nodes; int n; int lst = 0; int solve(int cur, int par) { int lst = 0; for (int i = 0; i < adj[cur].size(); i++) { int t = adj[cur][i]; if (t == par) continue; nodes.push_back(ma...
Roma works in a company that sells TVs. Now he has to prepare a report for the last year. Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever...
''' Created on Jan 14, 2013 @author: orhan ''' line = raw_input() tokens = line.split(' ') n = int(tokens[0]) k = int(tokens[1]) arr = [0] * n line = raw_input() tokens = line.split(' ') for i in range(0, n): arr[i] = int(tokens[i]) index = 0 while index < k and index < n and arr[index] < 0: arr[index...
John Doe has found the beautiful permutation formula. Let's take permutation p = p1, p2, ..., pn. Let's define transformation f of this permutation: <image> where k (k > 1) is an integer, the transformation parameter, r is such maximum integer that rk ≤ n. If rk = n, then elements prk + 1, prk + 2 and so on are omi...
#include <bits/stdc++.h> using namespace std; const int di[] = {-1, 0, 1, 0}; const int dj[] = {0, 1, 0, -1}; const long long MOD = 1e9 + 7; const long long INF = 1e9; const double EPS = 1e-5; int main() { ios::sync_with_stdio(false), cin.tie(0); int n; cin >> n; deque<int> num(n); for (int i = 0; i < n; i++)...
Zxr960115 is owner of a large farm. He feeds m cute cats and employs p feeders. There's a straight road across the farm and n hills along the road, numbered from 1 to n from left to right. The distance between hill i and (i - 1) is di meters. The feeders live in hill 1. One day, the cats went out to play. Cat i went o...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 200; const int M = 1e5 + 100; template <class Ruby_Rose> inline void read(Ruby_Rose &x) { x = 0; char ch = getchar(), w = 0; while (!isdigit(ch)) w = (ch == '-'), ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getch...
Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a pl...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); const double EPS = 1e-10; inline int read() { static char ch; bool sgn = false; while (ch = getchar(), ch < '0' || ch > '9') if (ch == '-') sgn = true; int res = ch - 48; while (ch = getchar(), ch >= '0' && ch <= '9') res = res * ...
Xenia the coder went to The Olympiad of Informatics and got a string problem. Unfortunately, Xenia isn't fabulous in string algorithms. Help her solve the problem. String s is a sequence of characters s1s2... s|s|, where record |s| shows the length of the string. Substring s[i... j] of string s is string sisi + 1......
#include <bits/stdc++.h> using namespace std; int i, j, k, n, m, u, ty; int f[100010][20], s[100010][30]; long long h[100010], g[100010], sum, ans, an, v[100010]; char p[100010]; inline long long get(int l, int r) { return h[r] - h[l - 1] * g[r - l + 1]; } inline int cal(int l, int r, int x) { return s[r][x] - s[l - 1]...
When Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with M classrooms numbered from 1 to M, situated along it. All the students of Petya’s year are divided into N g...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:50000000") using namespace std; const long long MOD = 1000000007; int n, sum; long long A[100], B[100]; long long DP[102][1002]; long long C[2000][2000]; int F[2000]; long long P[2000]; int main() { cin >> n; for (int i = 0; i < n; i++) cin >> A[i]; for (in...
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j)....
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.InputMismatchException; import java.util.PriorityQueue; public class CF { static int cmp; public static void main(String[] args) { FasterScanner sc = new Faste...
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings s1 and s2 from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task. Now they are trying to find ...
import static java.lang.Math.* ; import static java.util.Arrays.* ; import java.util.*; import java.io.*; public class Main { void main() throws Exception { Scanner sc = new Scanner(System.in) ; PrintWriter out = new PrintWriter(System.out) ; char [][] s = new char[2][] ; s[0] ...
Jzzhu has invented a kind of sequences, they meet the following property: <image> You are given x and y, please calculate fn modulo 1000000007 (109 + 7). Input The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109). Output Output a single integer...
n,m=map(int,input().split()) k=int(input()) l=m-n s=[n,m,l] z=(k-1)//3 if(z%2==0): print((s[k%3-1])%1000000007) else: print((-1*s[k%3-1])%1000000007)
A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull. Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordina...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int i, n, k; vector<pair<string, string> > vec; cin >> n; string a, b; for (i = 0; i < n; i++) { cin >> a >> b; vec.push_back({a, b}); } vector<int> ind; for (i = 0; ...
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the ne...
#include <bits/stdc++.h> using namespace std; int a[100005]; int b[100005]; int ca[100005]; int cb[100005]; int ua, ub; int n; int f(int t) { int sa = 0, sb = 0; int p = 0; int pa, pb; while (1) { if (p + 2 * t - 1 >= n) { pa = ca[n] - ca[p]; pb = cb[n] - cb[p]; if (pa != t && pb != t) ret...
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String a = scanner.next().toLowerCase(); HashSet<String> w = new HashSet<>(); for (in...
Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are n kinds of beer at Rico's numbered from 1 to n. i-th kind of beer has ai milliliters of foam on it. <image> Maxim is Mike's boss. Today he told Mike to perform q queries. Initially the shelf is empty. In each request, Ma...
#include <bits/stdc++.h> using namespace std; int arr[1000000], val[1000000], mark[1000000]; int freq[1000000]; void sieve() { int i, j; for (i = 2; i * i <= 500000; ++i) { if (arr[i] == 0) { for (j = i + i; j <= 500000; j += i) { if (!arr[j]) arr[j] = i; } } } for (i = 2; i <= 50000...
Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record! For rolling a ball one gets a score — an integer (maybe negative) number of points. Score for i-th roll is multiplied by i and scores are summed up. So, for k rolls with scores s1, s2, ..., ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10, B = 350; const long long inf = 0x3f3f3f3f3f3f3f3f; int n, m, a[N], p[N], pos[N], L[N], R[N], size; long long f[N], ans; inline bool cmp(int i, int j) { return a[i] < a[j]; } struct block { int l, r, q[B]; long long k, b; inline long long calc(i...
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest. V...
#include <bits/stdc++.h> #pragma GCC optimization("unroll-loops") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4") using namespace std; int main() { int n; scanf("%d", &n); vector<int> x(n); for (int i = 0; i < n; ++i) { scanf("%d", &x[i]); } sort(x.begin(), x.end()); int a...
You are given n strings ti. Each string has cost ci. Let's define the function of string <image>, where ps, i is the number of occurrences of s in ti, |s| is the length of the string s. Find the maximal value of function f(s) over all strings. Note that the string s is not necessarily some string from t. Input The ...
#include <bits/stdc++.h> using namespace std; struct Node { int len, link; int nxt[26]; long long val; }; struct Automaton { int sz, last; Node s[200100 * 10]; void init() { sz = last = 0; s[0].len = 0; s[0].link = -1; s[0].val = 0; memset(s[0].nxt, 0, sizeof(s[0].nxt)); ++sz; } ...
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win...
#include <bits/stdc++.h> using namespace std; int main() { size_t n, ai; std::pair<int, int> *mas = new (std::pair<int, int>[1000001]); memset(mas, 0, sizeof(std::pair<int, int>) * 1000001); scanf("%d", &n); for (size_t i = 1; i <= n; i++) { scanf("%d", &ai); mas[ai].first++; mas[ai].second = i; ...
Buses run between the cities A and B, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city A departs every a minutes and arrives to the city B in a ta minutes, and a bus from the city B departs every b minutes and arrives to the city A in a tb minutes. The driver Simion...
a, ta = map(int, raw_input().split()) b, tb = map(int, raw_input().split()) hh, mm = map(int, raw_input().split(":")) _hh = hh _mm = mm tmp = ta while ( tmp >= 60 ): _hh += 1 tmp -= 60 _mm += tmp if _mm >= 60: _hh += 1 _mm -= 60 tot = int(1200.0/b) st = [(5,0)] h = _h = 5 m = _m = 0 tmp = tb while ...
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows? Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r...
#include <bits/stdc++.h> using namespace std; struct Segment_Tree { int mx[200003 << 2], mn[200003 << 2], a[200003]; int qmax(int nl, int nr, int l, int r, int u) { if (nl <= l && r <= nr) return mx[u]; int res = -0x3f3f3f3f, mid = (l + r) >> 1; if (nl <= mid) res = max(res, qmax(nl, nr, l, mid, (u << 1...
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell. Chris tried filling in ran...
lines = int(input()) if lines == 1: print(1) exit(0) grid = [] number_with_zero = set() impossible = False no_zero = -1 for x in range(lines): num = list(map(int, input().split())) grid.append(num) for line in grid: have_zero = False s = 0 for n in line: if n ==0: have_...
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a...
import math n,k=map(int,input().split()) l2=[] a=list(map(int,input().split())) for i in a: l2.append(i) i=1 l=[a[0]] while i<=n-1: if a[i]+a[i-1]<k: a[i]=k-a[i-1] l.append(k-a[i-1]) else: l.append(a[i]) i=i+1 print(sum(l)-sum(l2)) print(*l)
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing. Nikita made m operat...
#include <bits/stdc++.h> using namespace std; int mas[100100]; const int MAXN = 1 << 17; const int MAXN2 = MAXN * 2; int tree[MAXN2]; int treeres[MAXN2]; void adfsadsad(int idx, int L, int R, int pos, int val) { if (L == R) { tree[idx] = val; treeres[idx] = val; return; } int mid = (L + R) / 2; if (...
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashta...
#include <bits/stdc++.h> using namespace std; int n; vector<string> h; void solve() { cin >> n; h.resize(n); for (int i = 0; i < n; ++i) { cin >> h[i]; h[i].erase(h[i].begin()); } for (int i = n - 2; i >= 0; --i) { if (h[i] > h[i + 1]) { for (int j = 0; j < h[i].size(); ++j) { if (h[...
Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences. Input Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000. Output Same as the easy version. Examples Input 4 100...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; imp...
In Pavlopolis University where Noora studies it was decided to hold beauty contest "Miss Pavlopolis University". Let's describe the process of choosing the most beautiful girl in the university in more detail. The contest is held in several stages. Suppose that exactly n girls participate in the competition initially....
#include <bits/stdc++.h> using namespace std; const int N = 6005000; long long d[N]; int main() { srand(time(NULL)); long long t; int l, r; cin >> t >> l >> r; for (int i = 1; i <= r; i++) d[i] = 1e18; d[1] = 0; for (int i = 1; i <= r; i++) { for (int j = i + i; j <= r; j += i) { d[j] = min(d[j]...
The Berland's capital has the form of a rectangle with sizes n × m quarters. All quarters are divided into three types: * regular (labeled with the character '.') — such quarters do not produce the noise but are not obstacles to the propagation of the noise; * sources of noise (labeled with an uppercase Latin let...
#include <bits/stdc++.h> using namespace std; int dx[4] = {0, -1, 0, 1}; int dy[4] = {-1, 0, 1, 0}; int m, n, q, p, visit[300][300], val[300][300], A[300][300]; long long B[300][300]; void BFS(int s, int t, int cnt) { queue<pair<int, int> > que; que.push(make_pair(s, t)); B[s][t] += A[s][t]; val[s][t] = A[s][t]...
The fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor. The Cinderswarm Bee. Koyomi knows it. The bees, according to their nature, live in a tree. To be more specific, a complete binary tree with n nodes numbered from 1 to n. The node numbered 1 is the...
#include <bits/stdc++.h> using namespace std; const int p = 1000000007; map<int, int> M; int g[500], h[500], u[10], v[10], x[500], y[500]; bool b[500], z[10]; int i, j, k, m, n, s, w; inline int getsize(int x) { int l = x, r = x, t = 0; for (; l <= n; l = l << 1, r = min(r << 1 | 1, n)) t = t + r - l + 1; return ...
Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer. Two ways are considered different if sets of indexes of eleme...
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Stack; public class ROUGH{ public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (roo...
Why I have to finish so many assignments??? Jamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment (lower value means more important) so he can decide which he ne...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5, MaxStep = 30; const int maxnode = maxn * MaxStep * 4; int tot = 0, rot[maxn + 5]; int nx[maxnode + 5][2], cnt[maxnode + 5]; int Upd(int px, int vv, int pp, int del) { int x = ++tot; nx[x][0] = nx[px][0], nx[x][1] = nx[px][1], cnt[x] = cnt[px] + del...
You are given a multiset S consisting of positive integers (initially empty). There are two kind of queries: 1. Add a positive integer to S, the newly added integer is not less than any number in it. 2. Find a subset s of the set S such that the value <image> is maximum possible. Here max(s) means maximum value ...
#include <bits/stdc++.h> using namespace std; const int MOD = 1e9 + 7; void solve() { long long q; cin >> q; double ans = 0; queue<int> qu; long long last = -1, sum = 0, cnt = 1, num = 0; while (q--) { int a; cin >> a; if (a == 1) { long long b; cin >> b; num++; qu.push(b...
Arkady is playing Battleship. The rules of this game aren't really important. There is a field of n × n cells. There should be exactly one k-decker on the field, i. e. a ship that is k cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class Battleship { void solve() { int n = in.nextInt(), k = in.nextInt(); char[][] b = new char[n][]; f...
Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well. We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the [greatest commo...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHel...
Problem Description Lulu says "I love triangles. I love the alphabet, too. Today, I am feeling artsy and I want to mix up these two. Write me a program that draws left-aligned triangles using consecutive letters of the alphabet." Input Format Each line of input consists of an alphabetic character ch, either in upp...
while True: try: s = raw_input() except: break if len(s.rstrip().lstrip())==0: break si = s.split() startCh = ord(si[0]) offset = int(si[1]) if offset == 1: print "INVALID" print continue endChi = startCh + (offset-1) ...
Darshak (Dark) likes to get fruits from trees a lot,he always like to eat those natural fruits directly from the tree. Today he has an infinite full binary tree (each node has exactly two child's) with special properties. Dark's tree has the following special properties : Each node of the tree has a value of goodness....
def is_prime(n): if n == 2 or n == 3: return True elif n < 2: return False elif n%2 == 0: return False limit = int(n**0.5) + 1 for i in xrange(3, limit, 2): if n%i == 0: return False return True def main(): for _ in xrange(input()): ...
Kuldeep is tired from all the fun he's having with Christie, so now all he needs is a good night's sleep to get some rest. Being a math nerd, he even dreams about maths. But in this dreamland some mathematical entities have slightly different definition. For example factorial of a number n in dreamland is defined a...
import math for t in range(input()): n,m = map(int,raw_input().split()) if n > 4: print 0 else: f = math.factorial ans = f(f(n))%(10 ** m) print ans
Given a word w, rearrange the letters of w to construct another word s in such a way that s is lexicographic-ally greater than w. In case of multiple possible answers, find the lexicographic-ally smallest one. Input Format The first line of input contains t, the number of test cases. Each of the next t lines contains...
def NextPerm(s): Len = len(s) EndChar = s[Len-1] for i in range (Len-2,-1,-1): c = s[i] if(c < EndChar): buff = s[:i] for j in range(Len-1,i,-1): if(s[j] > c): break buff = buff + s[j] index = j ...
Little Jhool is still out of his mind - exploring all his happy childhood memories. And one of his favorite memory is when he found a magical ghost, who promised to fulfill one of Little Jhool's wish. Now, Little Jhool was a kid back then, and so he failed to understand what all could he have asked for from the ghost...
t=int(input()) while t>0: r,u,b,y=0,0,0,0 s=raw_input() for c in s: if c=='r': r+=1 if c=='u': u+=1 if c=='b': b+=1 if c=='y': y+=1 print(min(r,u,b,y)) t-=1
Ashima has brought home n cats. Now, being a cat lover, she is taking care of the cats and has asked me to bring cat food for them. Being a guy with no idea what to buy, I brought some n packets of cat food (I atleast knew that each and every cat being a good junkie will completely eat a whole packet of cat food and wo...
n=input() s=map(int,raw_input().split()) c=map(int,raw_input().split()) s=sorted(s) c=sorted(c) total=0 for i in range(n): total+=c[i]*s[i] print total
In the Mathematical world of Dr. Ramanujam, every new student must have to pass a exam to take the classes of Advance mathematics from Dr. Ramanujam. One day Ram wants to have classes of Advance mathematics, so he arrived at class of Dr. Ramanujam. He asked ram to solve a given mathematical expression then only he will...
t=input() i=0 while i<t: x=raw_input() j=len(x)-1 sm=int(x[j]) j=j-1 while j>=0: c=x[j] j=j-1 a=int(x[j]) if c=='*': sm=sm*a elif c=='+': sm=sm+a else: sm=sm-a j=j-1 print sm i=i+1
Samu is in super market and in a mood to do a lot of shopping. She needs to buy shirts, pants and shoes for herself and her family. There are N different shops. Each shop contains all these three items but at different prices. Now Samu has a strategy that she won't buy the same item from the current shop if she had alr...
def minCostIter(): # Here i is the current i, j is the lastColumn selected dp = [[0] * (3) for i in xrange(N)] for j in xrange(3): dp[N - 1][j] = L[N - 1][j] for i in xrange(N - 2, -1, -1): for j in xrange(3): minVal = 10**9 for k in filter(lambda x: x != j, rang...
A string is said to be "SUPER STRING" if the number of times the character appeared in the string is equal to its ASCII value. Given the conditions that the ASCII value of ‘a’ is 26 and z is ‘1’. Input First line takes number of test cases ‘N’. Following ‘N’ lines take string as input. Output ‘Yes’ if the string i...
tc = int(raw_input()) while tc>0: tc = tc - 1 s = raw_input() flag = True s = list(s) # print s for i in s: # print ord(i) x = ord('Z') - ord(i) + 1 # print x if s.count(i)==x: pass else: flag = False break if flag == False: print "No" else: print "Yes"
You are given a string, which contains entirely of decimal digits (0-9). Each digit is made of a certain number of dashes, as shown in the image below. For instance 1 is made of 2 dashes, 8 is made of 7 dashes and so on. You have to write a function that takes this string message as an input and returns a correspondin...
dashes={'0':6,'1':2,'2':5,'3':5,'4':4,'5':5,'6':6,'7':3,'8':7,'9':6} n = raw_input() s=0 for e in n: s+=dashes[e] print s
We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it. It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M). Consider the following action: * Ch...
#include<bits/stdc++.h> using namespace std; int main() { int n, m, k; cin >> n >> m >> k; vector<int> a(n), b(m); for (int &i : a) cin >> i; for (int &i : b) cin >> i; long long t = 0; for (int i = 0; i < m; i++) t += b[i]; int j = m; int ans = 0; for (int i = 0; i <= n; i++) { while (j > 0 &&...
Takahashi has many red balls and blue balls. Now, he will place them in a row. Initially, there is no ball placed. Takahashi, who is very patient, will do the following operation 10^{100} times: * Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row. How ...
#include <bits/stdc++.h> using namespace std; int main(){ int64_t N,A,B;cin>>N>>A>>B; int64_t ans = (N/(A+B))*A + min(N%(A+B),A); cout<<ans<<endl; }
There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i. Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each u...
#include<iostream> #include<algorithm> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<string.h> #include<math.h> using namespace std; const int maxn=3e2+7; typedef long long ll; const ll INF=1e18; int n,m; ll l,dis[maxn][maxn]; int main() { scanf("%d%d%lld",&n,&m,&l); for(int...
Takahashi is competing in a sumo tournament. The tournament lasts for 15 days, during which he performs in one match per day. If he wins 8 or more matches, he can also participate in the next tournament. The matches for the first k days have finished. You are given the results of Takahashi's matches as a string S cons...
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { static Scanner scanner; public static void main(String[] args) { scanner = new Scanner(System.in); String S=gs(); int a=S.length() - S.replace("x", "").length(); if(a<...
You are given strings s and t. Find one longest string that is a subsequence of both s and t. Constraints * s and t are strings consisting of lowercase English letters. * 1 \leq |s|, |t| \leq 3000 Input Input is given from Standard Input in the following format: s t Output Print one longest string that is a su...
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ string a,b; cin>>a>>b; vector<vector<ll>> dp(a.length()+1,vector<ll>(b.length()+1)); for(ll i=1;i<=a.length();i++){ for(ll j=1;j<=b.length();j++){ if(a[i-1]==b[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i-...
You are given a positive integer N. Find the minimum positive integer divisible by both 2 and N. Constraints * 1 \leq N \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N Output Print the minimum positive integer divisible by both 2 and N. Example...
n = int(input()) if n % 2 == 0: print(n) else: print(2*n)
Consider the following set of rules for encoding strings consisting of `0` and `1`: * Strings `0` and `1` can be encoded as `0` and `1`, respectively. * If strings A and B can be encoded as P and Q, respectively, then string AB can be encoded as PQ. * If string A can be encoded as P and K \geq 2 is a positive integer,...
#include <cstdio> #include <iostream> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <queue> #include <set> #include <map> #include <cmath> #include <iomanip> #include <cassert> #include <bitset> using namespace std; typedef pair<int, int> P; #define rep(i, n) for (int i=0; i<(n);...