input
stringlengths
29
13k
output
stringlengths
9
73.4k
However, you are playing a game using sequences to do brain teaser. In this game, you will be given a random sequence of numbers from 1 to 9 at the beginning. However, you will erase a part of it from the sequence. The rules are as follows. * From the sequence, select the part where two or more of the same numbers are...
#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);...
problem JOI decided to play a game with his friends. N players participate in this game. The rules for a single game are as follows: Each player writes a favorite integer from 1 to 100 on the card and submits it. Each player gets the same score as he wrote if no one else wrote the same number. If there is another per...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); int N=sc.nextInt(); int player[][]=new int[N][3]; //ゲーム数,何人目 int point[][]=new int[N][3]; int result[]=new int[N]; for(int i=0;i<N;i++){ for(int j=0;j<3;j++){ int input =sc.nextInt();...
Write a program to calculate values of arithmetic expressions which may involve complex numbers. Details of the expressions are described below. In this problem, basic elements of expressions are non-negative integer numbers and the special symbol "`i`". Integer numbers are sequences of digits of arbitrary length and ...
#include<string> #include<complex> #include<cstdlib> #include<iostream> #define rep(i,n) for(int i=0;i<n;i++) using namespace std; bool overflow; void checkOverflow(const complex<int> z){ if(abs(real(z))>10000 || abs(imag(z))>10000) overflow=true; } complex<int> term(const string &s,int &idx); complex<int> factor...
Once upon a time when people still believed in magic, there was a great wizard Aranyaka Gondlir. After twenty years of hard training in a deep forest, he had finally mastered ultimate magic, and decided to leave the forest for his home. Arriving at his home village, Aranyaka was very surprised at the extraordinary des...
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> #include <vector> #include <utility> #include <set> //#define LOCAL #define maxv 205 #define maxn 105 #define EPS 1e-10 using namespace std; typedef long long ll; typedef pair<int,int> P; struct Point{ doubl...
Problem A Secret of Chocolate Poles Wendy, the master of a chocolate shop, is thinking of displaying poles of chocolate disks in the showcase. She can use three kinds of chocolate disks: white thin disks, dark thin disks, and dark thick disks. The thin disks are $1$ cm thick, and the thick disks are $k$ cm thick. Disk...
#include <bits/stdc++.h> #define rep(i, n) for (int i=0; i<(int)(n); i++) #define all(v) v.begin(), v.end() #define PRINT(v) for (auto x : (v)) cout <<x <<" " ; cout <<endl; using namespace std; using ll = long long; using Graph = vector<vector<int>>; using mat = vector<vector<ll>>; const ll MOD = 1000000007; const ll ...
Bridge Construction Planning There is a city consisting of many small islands, and the citizens live in these islands. Citizens feel inconvenience in requiring ferry rides between these islands. The city mayor decided to build bridges connecting all the islands. The city has two construction companies, A and B. The m...
#include <bits/stdc++.h> using namespace std; #define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++) #define REP(i,n) FOR(i,0,n) #define ALL(a) a.begin(), a.end() #define MS(m,v) memset(m,v,sizeof(m)) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<string> vs; typedef pair<int,...
You decide to develop a game with your friends. The title of the game is "Battle Town". This is a game with the theme of urban warfare with tanks. As the first step in game development, we decided to develop the following prototype. In this prototype, the only tanks that appear are the player's tanks, not the enemy ta...
import java.util.*; public class Main{ static int mapNum;//Buttle Town図の数 static int h;//地図の大きさの縦 static int w;//地図の大きさの横 static char[][] battleTown;//Buttle Town地図取込用 static int bomberActNum;//指示された戦車の行動数 static char [] bomberAct;//指示された戦車の行動 // static char [] tankDirection={'^','v','<','>...
Japanese video game company has developed the music video game called Step Step Evolution. The gameplay of Step Step Evolution is very simple. Players stand on the dance platform, and step on panels on it according to a sequence of arrows shown in the front screen. There are eight types of direction arrows in the Step...
#include <bits/stdc++.h> using namespace std; #define int long long const int INF = 1e9; signed main() { cin.tie(0); ios_base::sync_with_stdio(0); cout << fixed << setprecision(12); string s; while ( cin >> s, s != "#" ) { int ans = INF; for ( int i = 0; i < 9; i++ ) { // init of left for...
The time was 3xxx, and the highly developed civilization was in a stagnation period. Historians decided to learn the wisdom of the past in an attempt to overcome this situation. What I paid attention to was the material left by the genius of the early days of computers. The calculation formula is written in this materi...
#include <iostream> #include <cctype> using namespace std; typedef string::const_iterator Iterator; struct parse_error {}; void check_range(int n) { if (n < 0 || 1024 <= n) { throw parse_error(); } } int expr(Iterator& it, const Iterator& last); int term(Iterator& it, const Iterator& last); int number(Iter...
Make a wish to a shooting star The mysterious organization JAG (Japanese Alumni Group) holds regular meetings. One day, the agenda was "How to enable participating teams to demonstrate their strength in the upcoming ICPC (International Collegiate Programming Contest) domestic qualifying round." The conclusion of the m...
#include <bits/stdc++.h> #define double long double using namespace std; const double INF = 1e9; const double EPS = 1e-11; // ????¬???? struct P3{ double x,y,z; double vx,vy,vz; double r,vr; P3(double x=0, double y=0, double z=0):x(x),y(y),z(z){} P3 operator + (const P3 &a) const{ return P3(x+a.x, y+a.y, z+...
D --Invisible Problem Statement You are trying to play a card game called "Invisible" with your friends. This card game uses two types of cards, a "scoring card" and a "jamming card". A positive value is written on each score card. The rules of this card game are as follows. * The game is played by two players, play...
#include<bits/stdc++.h> using namespace std; #define int long long vector<int> a,b; int n; int m; map<pair<pair<pair<int,int>,pair<int,int>>,int>,int> table; int get_score(int i,int j,int s,int t,int turn){ if(table.count({{{i,j},{s,t}},turn})){ return table[{{{i,j},{s,t}},turn}]; } bool astop=false; ...
problem You were solving a flow problem that is typical of graph algorithms. The graph given in the problem is $ N $ vertices and $ M $ edges, with edges from $ x_i $ vertices to $ y_i $ vertices with capacity $ z_i $ and cost $ d_i $. However, AOR Ika played a trick on the input case. As a result, the order of $ x_i,...
// 基本テンプレート #include <iostream> #include <iomanip> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #in...
Problem In 1333, the greatest scientist in human history, Dr. Ushishi, developed an artificial intelligence with an ID of ai1333 in order to pass on his wisdom to posterity. For the next 100 years, ai1333 brought great benefits to humankind, but on the 100th anniversary of its birth, it created a new artificial intell...
x = int(input()) n = x/100 def f(n): if n == 0: return 'ai1333' else: a = f(n-1) b = a+'3' return b print(f(n))
Notes Template in C Constraints * 1 ≤ n ≤ 100000 * 1 ≤ q ≤ 1000 * 1 ≤ timei ≤ 50000 * 1 ≤ length of namei ≤ 10 * 1 ≤ Sum of timei ≤ 1000000 Input n q name1 time1 name2 time2 ... namen timen In the first line the number of processes n and the quantum q are given separated by a single space. In the following n li...
#include <iostream> #include <string> #include <queue> using namespace std; int main(void){ queue<pair<string,int> > v; int N,Q,T; string s; for(cin>>N>>Q;N--;){ cin>>s>>T; v.push(make_pair(s,T)); } for(T=0;!v.empty();){ pair<string,int> p=v.front(); v.pop(); ...
Write a program which identifies the number of combinations of three integers which satisfy the following conditions: * You should select three distinct integers from 1 to n. * A total sum of the three integers is x. For example, there are two combinations for n = 5 and x = 9. * 1 + 3 + 5 = 9 * 2 + 3 + 4 = 9 Note...
n, x = map(int, input().split()) while n != 0 or x != 0: count = 0 for i in range(1, n+1): for j in range(i+1, n+1): for k in range(j+1, n+1): if i+j+k == x: count += 1 print(count) n, x = map(int, input().split())
Teddy and Tracy like to play a game based on strings. The game is as follows. Initially, Tracy writes a long random string on a whiteboard. Then, each player starting with Teddy makes turn alternately. Each turn, the player must erase a contiguous substring that exists in the dictionary. The dictionary consists of N wo...
__author__ = 'robert' from collections import defaultdict import sys def solve(cache, between, i, j): if (i, j) in cache: return cache[(i, j)] if not between[(i, j)]: return 0 if len(between[(i, j)]) == 1: return 1 grundy_numbers = set() for word in between[(i, j)]: ...
Long ago during the Jurassic Park age, there was a company TopHunters, which used to conduct hunting competitions for the Dinosaurs around the world. Petrosaurus was believed to be the greatest hunter of that time and all other dinosaurs enjoyed watching the hunting videos posted by him in the forums ( yes, they had a ...
try: x=input() while x>0: s=raw_input().split(' ') for i in range(len(s)): if s[i]=='8': s[i]='ate' elif s[i]=='w8': s[i]='wait' elif s[i]=='gr8': s[i]='great' elif s[i]=='4': s[i]='fo...
Consider a currency system in which there are notes of seven denominations, namely, Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 50, Rs. 100. If the sum of Rs. N is input, write a program to computer smallest number of notes that will combine to give Rs. N. Input The first line contains an integer T, total number of testcases. T...
for x in range(int(raw_input())): varAmount = int(raw_input()) totalNotes = 0 for denomination in [100, 50, 10, 5, 2, 1]: if varAmount != 0: varNotes = varAmount//denomination varAmount -= varNotes*denomination totalNotes += varNotes print totalNotes
The Little Elephant from the Zoo of Lviv has an array A that consists of N positive integers. Let A[i] be the i-th number in this array (i = 1, 2, ..., N). Find the minimal number x > 1 such that x is a divisor of all integers from array A. More formally, this x should satisfy the following relations: A[1] mod x = 0...
from fractions import gcd def divisors_min(r): if(r%2==0): return 2 elif(r%3==0): return 3 else: y=2 i=5 while i<pow(r,0.5)+1: if(r%i==0): return i i+=y y=6-y return r def gcd2(l,n): r=l[0] if(n>1...
Farmer Feb has three fields with potatoes planted in them. He harvested x potatoes from the first field, y potatoes from the second field and is yet to harvest potatoes from the third field. Feb is very superstitious and believes that if the sum of potatoes he harvests from the three fields is a prime number (http://en...
import sys primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 31...
Given an array A1, A2, ..., AN, count the number of subarrays of array A which are non-decreasing. A subarray A[i, j], where 1 ≤ i ≤ j ≤ N is a sequence of integers Ai, Ai+1, ..., Aj. A subarray A[i, j] is non-decreasing if Ai ≤ Ai+1 ≤ Ai+2 ≤ ... ≤ Aj. You have to count the total number of such subarrays. Input The fi...
n = int(raw_input()) for i in xrange(n): l = int(raw_input()) list_a = [0] prev = -1 numList = [int(x) for x in raw_input().split()] for num in numList: if num >= prev: list_a.append(list_a[-1] + 1) else: list_a.append(1) prev = num print sum(list_a)
Alice has a lovely piece of cloth. It has the shape of a square with a side of length a centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length b centimeters (where b < a). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to ...
def check(n): i=2 while i*i<=n: if n%i==0: return 1 i+=1 return 0 for _ in range(int(input())): a,b=map(int,input().split()) if (a-b)!=1: print('NO') else: if check((a*a)-(b*b)):print('NO') else:print('YES')
Bob has put on some weight recently. In order to lose weight a bit, Bob has decided to swim regularly in the pool. However, the day before he went to the pool for the first time he had a weird dream. In this dream Bob was swimming along one of the pool's lanes, but also there were some jellyfish swimming around him. It...
#include <bits/stdc++.h> using namespace std; int dis, t, hull[422], k, sz, ch, ch2, n, m, mini = -1, w, i, j, x[422], y[422], r[422]; long long R; struct MaxFlowDinic { struct Edge { int next; size_t inv; int res; }; int n; vector<vector<Edge> > graph; ...
In this problem we consider a very simplified model of Barcelona city. Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal...
a, b, c = map(int, input().split()) x1, y1, x2, y2 = map(int, input().split()) l = 0 xz1 = x1 if b != 0: yz1 = (-c - x1 * a) / b else: yz1 = 9999999999999999999 if a != 0: xz2 = (-c - y1 * b) / a else: xz2 = 9999999999999999999 yz2 = y1 xf1 = x2 if b != 0: yf1 = (-c - x2 * a) / b else: yf1 = 99...
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,...
w , h = map(int , input().split()) u1 , d1 = map(int , input().split()) u2 , d2 = map(int , input().split()) while h > 0: if h == d1: w = w + h w = w - u1 h -= 1 elif h == d2: w = w + h w = w - u2 h -= 1 else: w = w + h h -= 1 if w < 0: ...
You have received your birthday gifts — n triples of integers! The i-th of them is { a_{i}, b_{i}, c_{i} }. All numbers are greater than or equal to 0, and strictly smaller than 2^{k}, where k is a fixed integer. One day, you felt tired playing with triples. So you came up with three new integers x, y, z, and then for...
#include <bits/stdc++.h> using namespace std; inline int gi() { int data = 0, fu = 1; char ch = 0; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar(); if (ch == '-') fu = -1, ch = getchar(); while ('0' <= ch && ch <= '9') data = (data << 1) + (data << 3) + (ch ^ 48), ch = getchar(); return data ...
You are given an array of n integers a_1, a_2, …, a_n. You will perform q operations. In the i-th operation, you have a symbol s_i which is either "<" or ">" and a number x_i. You make a new array b such that b_j = -a_j if a_j s_i x_i and b_j = a_j otherwise (i.e. if s_i is '>', then all a_j > x_i will be flipped). A...
import java.util.*; import java.io.*; public class HotIsCold { static int[] ans; public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = scanner.nextInt(); int Q = scanner.nextInt(); Pair[] ...
You are given an array consisting of n integers a_1, a_2, ... , a_n and an integer x. It is guaranteed that for every i, 1 ≤ a_i ≤ x. Let's denote a function f(l, r) which erases all values such that l ≤ a_i ≤ r from the array a and returns the resulting array. For example, if a = [4, 1, 1, 4, 5, 2, 4, 3], then f(2, 4...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 10; const int inf = 1 << 29; int n, x; int l[maxn], r[maxn]; bool canl[maxn], canr[maxn]; vector<int> pos[maxn]; int main() { scanf("%d%d", &n, &x); int tmp; for (int i = 1; i <= n; i++) { scanf("%d", &tmp); pos[tmp].push_back(i); } ...
The only difference between easy and hard versions is constraints. Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes. In the player, Polycarp stores n songs, each of which is...
#include <bits/stdc++.h> using namespace std; const int MOD = 1000000007; template <typename T> struct modular { constexpr modular() : val(0) {} constexpr modular(const modular<T>& _m) : val(_m.val) {} template <typename U> constexpr modular(const U& _r = U()) { val = -MOD <= _r && _r < MOD ? _r : _r % MOD;...
Natasha's favourite numbers are n and 1, and Sasha's favourite numbers are m and -1. One day Natasha and Sasha met and wrote down every possible array of length n+m such that some n of its elements are equal to 1 and another m elements are equal to -1. For each such array they counted its maximal prefix sum, probably a...
#include <bits/stdc++.h> using namespace std; long long alatt[2001][2001]; long long d[2001][2001]; long long k[2001][2001]; long long mod = 998244853; long long er[2001]; int n, m; long long ans = 0; long long sum; long long oszt(long long a) { long long p = mod - 2; long long x = a; long long s = 1; while (p ...
You have a fence consisting of n vertical boards. The width of each board is 1. The height of the i-th board is a_i. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from 2 to n, the condition a_{i-1} ≠ a_i ...
#include <bits/stdc++.h> using namespace std; long long t, n, dp[300002][3], a[300002], b[300002]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> t; while (t--) { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i] >> b[i]; for (int i = 2; i <= n; i++) dp[i][0]...
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, …, p_n. Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, …, q_m. ...
t = int(input()) for a in range(t): n = int(input()) p = list(map(int, input().split())) m = int(input()) q = list(map(int, input().split())) cnt = 0 evencnt = 0 oddcnt = 0 for i in range(m): if(q[i] % 2 == 0): evencnt += 1 else: oddcnt += 1 for i in range(n): if(p[i] %2 == 0): cnt += evencnt ...
Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are n types of resources, numbered 1 through n. Bob needs at least a_i pieces of the i-th resource to build the spaceship. The numbe...
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using D = double; using uint = unsigned int; template <typename T> using pair2 = pair<T, T>; using pii = pair<int, int>; using pli = pair<ll, int>; using pll = pair<ll, ll>; mt19937 rng(chrono::steady_clock::now().time_since_epo...
An infinitely long Line Chillland Collider (LCC) was built in Chillland. There are n pipes with coordinates x_i that are connected to LCC. When the experiment starts at time 0, i-th proton flies from the i-th pipe with speed v_i. It flies to the right with probability p_i and flies to the left with probability (1 - p_i...
#include <bits/stdc++.h> using namespace std; const int N = 300010, mod = 998244353; int n, tot; int x[N], v[N], p[N]; struct mtrx { int f[2][2]; void clear() { memset(f, 0, sizeof(f)); } mtrx operator*(const mtrx a) const { mtrx c; c.clear(); for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j...
Farmer John is obsessed with making Bessie exercise more! Bessie is out grazing on the farm, which consists of n fields connected by m directed roads. Each road takes some time w_i to cross. She is currently at field 1 and will return to her home at field n at the end of the day. Farmer John has plans to increase the...
#include <bits/stdc++.h> using namespace std; struct node { int to, nxt, w, f; } e[200005]; const int N = 60; int head[N], cnt = 1, s, t, l[N]; int maxf, mins, fl[N], pre[N], dis[N]; int sf[N << 15], sw[N << 15], k, p, n, m, xk; double ans; bool vis[N]; queue<int> q; void add(int u, int v, int f, int w) { cnt++; ...
Input The input contains a single integer a (0 ≤ a ≤ 63). Output Output a single number. Examples Input 2 Output 2 Input 5 Output 24 Input 35 Output 50
# And after happily lived ever they n = int(input()) d = [0,5,3,2,4,1] r=0 for dd in d: r=r*2 + bool(n&1<<(5-dd)) print (r)
You are given two integers a and b. Print a+b. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given as a line of two integers a and b (-1000 ≤ a, b ≤ 1000). Output Print t integers — the required numbers a+b. Example ...
#include <bits/stdc++.h> #pragma GCC optimize("O3") #pragma GCC optimize("Ofast") using namespace std; long long int t, a, b; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; cin >> t; while (t--) { cin >> a >> b; cout << a + b << '\n'; } }
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
#dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] for _ in range(inp()): a,b,n,m = ip() if a+b < n+m: print("No") continue no = min(n,m) if a < no or b < no: print("No") ...
This is a harder version of the problem E with larger constraints. Twilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin. To hide the crucial information from evil eyes, pony elders cast a spell on the scroll. ...
#include <bits/stdc++.h> template <typename T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } template <typename T> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } using ll = long long; const int BS = 5.65e7; const int MOD = 1e9 + 7; const int INF = 1e7; const int MN = 1e5 + 10; const i...
You are playing a computer game. In this game, you have to fight n monsters. To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d. When you fight a monster with strength d while having a shiel...
def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f ...
Bandits appeared in the city! One of them is trying to catch as many citizens as he can. The city consists of n squares connected by n-1 roads in such a way that it is possible to reach any square from any other square. The square number 1 is the main square. After Sunday walk all the roads were changed to one-way ro...
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // 11:35.587 public class cf1436d { public static void main(String[] args) throws IOException { int n = ri(), p[] = riam1(n - 1), a[] = ria(n), leaves[] = new int[n]; long sum[] = new long[n],...
Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an n × m matrix consisting of "*" and ".". <image> To find every spruce first let's define what a spruce in the matrix is. A set ...
#include<bits/stdc++.h> #define ll long long int using namespace std; int dp[505][505]; /* 00300 02220 11111 */ int main() { int t; scanf("%d", &t); while(t--) { memset(dp, 0, sizeof(dp)); int n, m; scanf("%d%d", &n, &m); for(int i = 0;i < n;i++) { for...
The only difference between the easy and the hard version is the limit to the number of queries. This is an interactive problem. There is an array a of n different numbers. In one query you can ask the position of the second maximum element in a subsegment a[l..r]. Find the position of the maximum element in the arra...
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.concurrent.TimeUnit; public class c1486 implements Runnable{ public static void main(String[] args) { try{ new Thread(null, new c1486(), "process", 1<<26).start(); } catch(Exception e){ ...
There was no problem about a cactus at the NERC 2020 online round. That's a bad mistake, so judges decided to fix it. You shall not pass to the World Finals 2021 without solving a problem about a cactus! A cactus is a connected undirected graph in which every edge lies on at most one simple cycle. Intuitively, a cactu...
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define mp make_pair #define pb push_back #define LC k<<1 #define RC k<<1|1 typedef long long LL; const int N=110000; const int M=1100000; const LL mod=1e9+7; int n,m,f[N],fat[N],dep[N],pp[N],cp[N],du[N],h[N]; vector<pair<int,int> > ans;...
Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an n by m grid (1 ≤ n, m ≤ 2000) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: 1. For any two adjacent (sharing a side) cells, the absolute value of the d...
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class Main { static final long MOD = 1000000007L; public static void main(String hi[]) throws Exception ...
Vasya wants to buy a new refrigerator. He believes that a refrigerator should be a rectangular parallelepiped with integer edge lengths. Vasya calculated that for daily use he will need a refrigerator with volume of at least V. Moreover, Vasya is a minimalist by nature, so the volume should be no more than V, either — ...
#include <bits/stdc++.h> using namespace std; const long long inf = 1000000000000LL; int t, n, i, j, a[111], num, ri, rj; long long m, x, cur, cz, mbi, res, p[111], b[4000000]; map<long long, pair<long long, long long> > M; void rec(int l, long long cur) { if (l == n) { b[num++] = cur; return; } for (int ...
The prestigious Codeforces kindergarten consists of n kids, numbered 1 through n. Each of them are given allowance in rubles by their parents. Today, they are going to the most famous candy shop in the town. The shop sells candies in packages: for all i between 1 and m, inclusive, it sells a package containing exactly...
#include <bits/stdc++.h> using namespace std; long long i, j, k, p, n, m, ans, Mi, Ma; long long a[200000 + 10]; long long Calc(long long Mini, long long Maxi) { long long res = 0; Ma = ((Ma) < (a[n]) ? (Ma) : (a[n])); for (i = 1; i < n; ++i) Ma = ((Ma) < (a[i] - (i - 1) * Mini + Maxi) ? (Ma) ...
The Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better. The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered...
#include <bits/stdc++.h> using namespace std; inline int read(register int ans = 0, register int sgn = ' ', register int ch = getchar()) { for (; ch < '0' || ch > '9'; sgn = ch, ch = getchar()) ; for (; ch >= '0' && ch <= '9'; (ans *= 10) += ch - '0', ch = getchar()) ; return sgn - '-' ? a...
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
n=int(input()) count=0 for _ in range(n): l=list(map(int,input().split())) if(sum(l)>=2): count+=1 print(count)
Little Maxim loves interesting problems. He decided to share one such problem with you. Initially there is an array a, consisting of n zeroes. The elements of the array are indexed, starting from 1. Then follow queries to change array a. Each query is characterized by two integers vi, ti. In the answer to the query w...
#include <bits/stdc++.h> using namespace std; const int M = 777777777; struct segment { int l, r; inline bool operator<(const segment &s) const { return l < s.l; } }; int n; int w[4][4]; int dp[4][77790][4] = {0}; int dp_full; int dp_r[4][77790] = {0}, dp_l[77790][4] = {0}; int a[77777] = {0}; const int SZ = 131072...
Given the number n, find the smallest positive integer which has exactly n divisors. It is guaranteed that for the given n the answer will not exceed 1018. Input The first line of the input contains integer n (1 ≤ n ≤ 1000). Output Output the smallest positive integer with exactly n divisors. Examples Input 4 ...
import java.util.*; import java.io.*; public class Main { static int[] primes; public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); primes = new int[]{2,3,5,7,11,13,17,19,23,29}; long[] max = new long[primes.length]; long MAX = 1000000000...
Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the c...
#include <bits/stdc++.h> using namespace std; int dis[105], n, d; int cost[105][105]; int input[105]; int x[105], y[105]; int judge[105]; int abss(int x) { if (x < 0) return -x; else return x; } void solve() { fill(dis, dis + n + 1, 100000000); memset(judge, 0, sizeof(judge)); int x; dis[1] = 0; w...
There are n cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all n cities. The length of this Hamiltonian cycle is defined as the sum of the distan...
#include <bits/stdc++.h> using namespace std; const int N = 100011; const long long Inf = 0x3f3f3f3f; int x[N], y[N]; pair<int, int> sx[N], sy[N]; bool vis[2][2]; int px[N], py[N]; int main() { ios ::sync_with_stdio(false); int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> x[i] >> y[i]; sx[i] = {x[...
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (xi, yi). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinate...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOExcept...
Dima's spent much time thinking what present to give to Inna and gave her an empty sequence w. Now they want to fill sequence w with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses m integers a1, a2, ..., am (1 ≤ a1 < a2 < ... < am). Then Inna and Dima start ...
#include <bits/stdc++.h> using namespace std; struct BIT { vector<int> t; int gb; BIT(int n) { t.assign(n + 1, 0); gb = 1; while (gb < n) gb <<= 1; if (gb > n) gb = gb >>= 1; } int query(int idx) { int sum = 0; for (; idx; idx -= idx & -idx) sum += t[idx]; return sum; } void ad...
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 ce...
#include <bits/stdc++.h> using namespace std; int n, dem; bool f[102]; int main() { cin >> n; int l, r, a, b, fi; cin >> a >> b; fi = a; if (n == 1) { cout << b - a; return 0; } for (int i = 2; i <= n; i++) { cin >> l >> r; for (int j = l; j <= r - 1; j++) f[j] = true; } f[b] = true; ...
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Mar...
import java.io.BufferedInputStream; import java.util.Scanner; public class MartianDollar { //Round #40 - Martian Dollar public static void main(String[] args) { Scanner sc = new Scanner(new BufferedInputStream(System.in)); int numDays = sc.nextInt(); int[] dollarCourses = new int[numDays]; int bourlesAmount ...
DZY loves colors, and he enjoys painting. On a colorful day, DZY gets a colorful ribbon, which consists of n units (they are numbered from 1 to n from left to right). The color of the i-th unit of the ribbon is i at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first. ...
#include <bits/stdc++.h> using namespace std; const long long A = 100000000000000LL, N = 228228; long long i, j, n, m, a, l, r, x, t[3][N * 4]; void talk(long long v, long long l, long long r) { if (!t[0][v]) return; long long mid = (l + r) / 2; t[1][v * 2] += t[2][v] * (mid - l + 1), t[1][v * 2 + 1] += t[2...
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game. Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, ...
import java.io.*; import java.util.*; import java.lang.*; public class Main { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); if(n<4) { out.println("NO"); out.close(); return; } if(n%2!=0) { out.pr...
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
n=input() t=[int(skill) for skill in raw_input().split()] t1,t2,t3=[],[],[] for skill in range(len(t)): if t[skill]==1: t1.append(skill+1) elif t[skill]==2: t2.append(skill+1) else: t3.append(skill+1) w=min(min(len(t1),len(t2)),len(t3)) indices=[] print w cindx=0 for team in range(w)...
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
x = list(input()) for i in range(len(x)): if (i == 0 and '5' <= x[0] <= '8') or (i != 0 and '5' <= x[i] <= '9'): x[i] = str(9-int(x[i])) print(x[i], end = '')
Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests...
#include <bits/stdc++.h> using namespace std; vector<int> a; int main() { int N, K, P, X, Y; int l, m; cin >> N >> K >> P >> X >> Y; int sum = 0; for (int i = 0; i < K; ++i) { cin >> l; a.push_back(l); sum += a[i]; } sort(a.begin(), a.end()); l = X - sum; if (K >= ((N + 1) / 2) && a[((N + ...
Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed. After some time, the wise men ...
#include <bits/stdc++.h> using namespace std; const long double pi = 3.14159265359; template <typename T> T abs(T x) { return x > 0 ? x : -x; } template <typename T> T sqr(T x) { return x * x; } const int maxn = 405 * 4; char isV[maxn]; vector<int> g[maxn]; vector<int> gt[maxn]; int enc(int v, int vo, int neg) { re...
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
s=input() s=s.lower() ss='hello' cnt=0 for i in range(len(s)): if s[i]==ss[cnt]: cnt+=1 if cnt==5: break if cnt==5: print("YES") else: print("NO")
They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so. Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Row...
#include <bits/stdc++.h> using namespace std; const long long N = 1e5 * 3 + 2, oo = INT_MAX, mod = 1e9 + 7; void debug() { cerr << '\n'; } template <typename Head, typename... Tail> void debug(Head H, Tail... T) { cerr << " " << to_string(H); debug(T...); } int n; string s; long long dp[N][4]; long long solve(int i...
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor. The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a pla...
import java.util.*; public class Game{ public static void main (String args[]){ Scanner kb = new Scanner(System.in); long i = kb.nextLong(); if( (2 - ( i % 2)) == 2 ) System.out.print(2); else System.out.print(1); } }
Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at...
import java.util.Arrays; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/5/11 * Time: 9:27 PM * To change this template use File | Settings | File Templates. */ public class Task3 { int N; double[] d; int[] x, y, z; int px, py, pz; int vs, vp; double dist(int x1, int y1, int z1, int x2, int y2,...
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy ...
import java.util.*; import java.lang.Math.*; public class Main{ public static void main(String[] args){ solve(); } public static void solve(){ Scanner scan = new Scanner(System.in); int n; double xa, ya, va, t, x0, y0; x0 = scan.nextDouble(); y0 = scan.nextDouble(); n = scan.nextInt(); xa = va = ya ...
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s. ...
#include <bits/stdc++.h> int n, k, s, t, a[200010], b[200010], c[200010]; using namespace std; int f(int x) { int i, ans = 0; for (i = 1; i <= k + 1; i++) { int len = c[i] - c[i - 1]; if (len > x) return 0; if (x > 2 * len) ans += len; else ans += (x - len) + 2 * (len - (x - len)); } ...
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all. Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this ...
#include <bits/stdc++.h> using namespace std; vector<int> val[200001]; int lst[200001]; int indx[200001]; int notBe[200001]; int cmp(int a, int b) { return lst[a] < lst[b]; } int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) val[i].push_back(0); for (int i = 1; i <= n; i++) { int a, b; s...
You are given an integer m, and a list of n distinct integers between 0 and m - 1. You would like to construct a sequence satisfying the properties: * Each element is an integer between 0 and m - 1, inclusive. * All prefix products of the sequence modulo m are distinct. * No prefix product modulo m appears as...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, m, w[N], vis[N], dp[N], pre[N], cnt; vector<int> g[N]; long long exgcd(long long &x, long long &y, long long a, long long b) { if (!b) { x = 1, y = 0; return a; } long long g = exgcd(x, y, b, a % b); long long t = x; x = y; ...
Petya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: * Extract the first character of s and append t with this character. * Extract the last character of t and append u with this ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Map; imp...
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires. Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors. Ea...
#include <bits/stdc++.h> using namespace std; namespace FASTIN { static char buf[1 << 20], *p1, *p2; inline char getc() { if (p1 == p2) { p1 = buf; p2 = buf + fread(buf, 1, 1 << 20, stdin); if (p1 == p2) return EOF; } return *p1++; } inline int readint() { register int f = 0, sign = 1; register ch...
Nikita plays a new computer game. There are m levels in this game. In the beginning of each level a new class appears in the game; this class is a child-class of the class yi (and yi is called parent-class for this new class). Thus, the classes form a tree. Initially there is only one class with index 1. Changing the ...
#include <bits/stdc++.h> using namespace std; const int MAX = 3e5 + 5; const int LOGN = 19; bool vis[MAX]; int depth[MAX]; int tin[MAX], tout[MAX]; int fa[MAX][LOGN]; vector<int> adj[MAX]; int timer = 0; int dist(int u, int v) { if (depth[u] < depth[v]) swap(u, v); int dis = 0; for (int i = LOGN - 1; i >= 0; i--)...
Luba needs your help again! Luba has n TV sets. She knows that i-th TV set will be working from moment of time li till moment ri, inclusive. Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at leas...
#include <bits/stdc++.h> const int maxn = 2e5 + 10; const int mod = 1e9 + 7; const int inf = 2e8; using namespace std; struct node { int l, r, i; bool friend operator<(node a, node b) { if (a.l == b.l) return a.r < b.r; return a.l < b.l; } } a[maxn]; int main() { int n; cin >> n; for (int i = 1; i <...
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
import oracle.jrockit.jfr.events.*; import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new Fi...
You are given an array a consisting of n integers. You have to process q queries to this array; each query is given as four numbers l, r, x and y, denoting that for every i such that l ≤ i ≤ r and ai = x you have to set ai equal to y. Print the array after all queries are processed. Input The first line contains one...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10, B = 450, V = 103; int n, m, a[N]; struct UF { int p[B + 1], r[B + 1], v[B + 1]; void reset() { for (int i = 0; i <= B; i++) p[i] = i; memset(r, 0, sizeof(r)); } int find(int u) { if (p[u] == u) return u; p[u] = find(p[u]); ...
East or west, home is best. That's why family reunion, the indispensable necessity of Lunar New Year celebration, is put in such a position. After the reunion dinner, Little Tommy plays a game with the family. Here is a concise introduction to this game: 1. There is a sequence of n non-negative integers p1, p2, .....
#include <bits/stdc++.h> using namespace std; int n, a[300001]; int best[300001][8][2][2]; long long dp[300001][2]; int cut[300001][8][2][2]; pair<int, pair<int, int> > prv[300001][2]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); } for (int i = 0; i < 300001; i++) { f...
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined <image>. You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1. Output the minimum poss...
n, k1, k2 = map(int, raw_input().split()) k1 += k2 a = map(int, raw_input().split()) b = map(int, raw_input().split()) c = [abs(a[i]-b[i]) for i in range(len(a))] for i in range(k1): c[c.index(max(c))] = abs(max(c) - 1) sqr = 0 for ii in c: sqr+=(ii*ii) print sqr
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tr...
n = int(input()) a = list(map(int,input().split())) b = [x for x in range(1,n+1)] c = [(x,y) for x,y in zip(a,b)] d = set(c) cnt = 0 while d: x = d.pop() sti = x[1] while x[0] != sti: x = c[x[0]-1] cnt += 1 if x in d: d.remove(x) else: break if cnt%2==...
Little Jhool considers Jaadu to be a very close friend of his. But, he ends up having some misunderstanding with him a lot of times, because Jaadu's English isn't perfect, and Little Jhool sucks at the language Jaadu speaks. So, he's in a fix - since he knows that Jaadu has got magical powers, he asks him to help so as...
for T in range(int(input())): Text = raw_input() S = raw_input() l = len(S) f = 0 for i in S: if(i in Text): f = 1 print("YES") break if(f == 0): print("NO")
Caesar Cipher is one of the earliest and simplest encryption technique. To encrypt a message, we shift the alphabets of the message by a fixed position or key. For example, if message is ABC , and we shift each character by 3 characters, we will get DEF. Here key is 3. Given a message and key , compute its Caesar C...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' ##print 'Hello World!' t=int(input()) while(t>0): t-=1 n=int(raw_input()) s=raw_input() x='' for i in range(len(s)): if ord(s[i])>=97 and ord(s[i])<=122: x+=chr((ord(s[i])+in...
Tyrion, son of Tywin was released from the dungeons of vale after his champion Bronn defeated Ser Vardis in the trial by combat. As a Lannister always pays his debts, he invited Bronn to play a game of mastermind with him. The game is played as follows: Tyrion has rocks of 7 colours. (As he is rich, he has infinitel...
from sys import stdin a = stdin.readline().strip() di = {} for i in a: di[i] = di.get(i,0) + 1 t = int(stdin.readline()) for _ in xrange(t): b = stdin.readline().strip() fir = 0 sec = 0 for i in xrange(10): if a[i] == b[i]: fir+=1 hi = {} for i in b: hi[i] = hi.get(i,0)+1 for i in hi: x = hi.get(i,0) ...
"Bless us and splash us , precious . Thats a meaty mouthful . " said Gollum on seeing Bilbo Baggins . Poor Bilbo Baggins is lost in the Misty Mountains and worst of all now he is stuck with Gollum who wants to finish him off. As Mr. Bilbo Baggins is clever , he convinced Gollum to play a game of riddles where if Bil...
for _ in range(int(raw_input())): n = int(raw_input()) a = map(int,raw_input().split()) nd = n/min(a) if(nd==0): print "-1" continue li = max(a.index(min(a)),(len(a)-1)-a[::-1].index(min(a))) i1 = li+1 left = n%a[li] no = [] j = 8 while(left>0 and j>li): if(a[j]-a[li] > left): j-=1 else: no.appe...
"N" White Walkers are positioned in a circle from "1" to "N". First (No. 1) White Walker has a dragonglass . He kills the next White Walker (i.e. No. 2) and passes the dragonglass to the next (i.e. No. 3) who kills the 4th and passes the weapon to 5th White Walker. This way alternate killing of White Walkers goes on...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t = int(raw_input()) while t > 0: t = t - 1 n = int(raw_input()) if n == 0: print "0" continue m = 1 while 1: temp = m*2 if temp > n: break m = temp ans = ...
Suppose we have a sequence of non-negative integers, Namely a_1, a_2, ... ,a_n. At each time we can choose one term a_i with 0 < i < n and we subtract 1 from both a_i and a_i+1. We wonder whether we can get a sequence of all zeros after several operations. Input The first line of test case is a number N. (0 < N ≤ 100...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n = int(raw_input()) nums = map(int, raw_input().split()) #POSSIBLE = (reduce(lambda x,y : y-x, nums) == 0) diff = nums[0] for i in range(1, len(nums)): diff = nums[i]-diff if diff ...
Its vacation time and Panda with two of his best friends Agham and Rishi is in his hometown, Pandaland. One day Panda came across a very delicious dish called PandaCake. He likes it very much and bought 'N' of them from a shop. Now on the day of his arrival i.e. on the first day, he ate only one PandaCake and decided t...
from math import sqrt for _ in range(int(raw_input())): n = int(raw_input()) print int(sqrt(4 * (n-1) + 1))
Most of the time when rounding a given number, it is customary to round to some multiple of a power of 10. However, there is no reason why we cannot use another multiple to do our rounding to. For example, you could round to the nearest multiple of 7, or the nearest multiple of 3. Given an integer N and an integer B, r...
for _ in xrange(input()): N,B=map(int,raw_input().split()) S=N T=N c1,c2=0,0 while S%B!=0: S-=1 c1+=1 while T%B!=0: T+=1 c2+=1 if c2<=c1: print T else: print S
Kevin has a string S consisting of N lowercase English letters. Kevin wants to split it into 4 pairwise different non-empty parts. For example, string "happynewyear" can be splitted into "happy", "new", "ye" and "ar". He can't delete any characters or change the order of the characters. Help Kevin and find if ther...
for _ in range(int(raw_input())): a=raw_input() if len(a)<=3: print 'NO' continue elif len(a)>=10: print 'YES' continue else: flag=0 for i in range(len(a)-3): for j in range(i+1,len(a)-2): for k in range(j+1,len(a)-1): a1=a[0:i+1] a2=a[i+1:j+1] a3=a[j+1:k+1] a4=a[k+1:len(a)] ...
You are given a string S. S consists of several words separated by one or more spaces. Word consists of Latin letters as well as other symbols (but not spaces). In each word which starts from lowercase Latin letter replace starting letter with uppercase Latin letter. Input The only line contains S Output Output one l...
try: s = raw_input() #print s words = s.split(' ') #print words for i in words: if len(i)==0: print "", continue else: # print "i =", i letters = list(i) # print "leters are",letters letters[0] = letters[0].capitalize() word = ''.join(letters) print (word), except: print "exception"
Inspired by the tv series Stranger Things, bear Limak is going for a walk between two mirror worlds. There are two perfect binary trees of height H, each with the standard numeration of vertices from 1 to 2^H-1. The root is 1 and the children of x are 2 \cdot x and 2 \cdot x + 1. Let L denote the number of leaves in ...
#include<cstdio> #include<algorithm> using namespace std; int ans=0,sum=0,pp[262144],dp[262144],m,h,n,tr[5000005],cnt=0,hd[262144]; int ch[2][5000005]; const int mod=1e9+7; int pos,v,rt,inv[262144]; int M(int x){return x>=mod?x-mod:x;} int mypow(int a,int b) { int ans=1; while(b) { if(b&1)ans=1ll*ans*a%mod; a=1l...
Given is a positive integer N. We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K. * Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K. In how many choices of K will N become 1 in the end? Constraints * 2 \leq N ...
#include <bits/stdc++.h> using namespace std; int main(){ int64_t N; cin >> N; unordered_set<int64_t> divs; // 2以上であるN-1の約数, // Nの約数の一部を(N自身とsqrt(N)以下のものを試して)追加 divs.insert(N); if(N-1 > 1){ divs.insert(N-1); } int64_t div= 2; while(div*div <= N){ int cnt= 0; int64_t tmp= N; while(tmp%di...
We held two competitions: Coding Contest and Robot Maneuver. In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen....
#include <bits/stdc++.h> using namespace std; int main() { int x,y; cin >> x >> y; int k = 0; if(x <= 3) { k = (4 - x) * 100000; } if(y <= 3) { k += (4 - y) * 100000; } if(x + y == 2) { k += 400000; } cout << k << endl; }
Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder). He is dividing the problems into two categories by choosing an integer K, as follows: * A problem with difficulty K or higher will be for ...
import java.util.*; import java.util.Arrays; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int a[] = new int[n]; int s = 0; for (int i = 0; i < n; i++){ a[i] = sc.nextInt(); } Arrays.sort(a); ...
There are four towns, numbered 1,2,3 and 4. Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally. No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roa...
lst = [0] * 5 for _ in range(3): a, b = map(int, input().split()) lst[a] += 1 lst[b] += 1 if lst.count(2) == 2: print ('YES') else: print ('NO')
There is a grid of squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j). Each square is black or white. The color of the square is given as an H-by-W matrix (a_{i, j}). If a_{i, j} is `.`, the square (i, j) is white; if...
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { int h, w; cin >> h >> w; bool x[110] = { 0 }, y[110] = { 0 }; vector<string>s(h); for (int i = 0; i < h; i++) { cin >> s[i]; } for (int i = 0; i<h; i++) { for (int j = 0; j<w; j++) { if (s[i][j] == '#') { x[i] = true; ...
Takahashi has decided to give a string to his mother. The value of a string T is the length of the longest common subsequence of T and T', where T' is the string obtained by reversing T. That is, the value is the longest length of the following two strings that are equal: a subsequence of T (possibly non-contiguous), ...
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<cstdlib> using namespace std; const int N=305; int n,m; int dp[N][N][N]; char s[N]; int main(){ int l,r,k,d,i; scanf("%s",s+1); n=strlen(s+1); scanf("%d",&m); for (i=1;i<=n;i++) for (k=0;k<=m;k++) dp[i][i][k]=1; ...
A group of people played a game. All players had distinct scores, which are positive integers. Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i. Find the maximum possible number of players in the game. Constraints * 1 \leq N \leq 10^5 * 1...
import java.io.File; import java.io.FileInputStream; import java.util.Scanner; import java.util.Map.Entry; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util....
You are given a connected undirected simple graph, which has N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices A_i and B_i. Your task is to find a path that satisfies the following conditions: * The path traverses two or more vertices. * The...
#include<bits/stdc++.h> using namespace std; bool visit[100010]; vector<int>graph[100010]; vector<int>path,path2; void dfs(int t){ visit[t]=true; path.push_back(t); for(int i=0;i<graph[t].size();i++){ int nxt=graph[t][i]; if(visit[nxt]==false){ dfs(nxt); return; } } } int main(){ int n,m; cin>>n>>m; ...
The currency used in Takahashi Kingdom is Myon. There are 1-, 10-, 100-, 1000- and 10000-Myon coins, and so forth. Formally, there are 10^n-Myon coins for any non-negative integer n. There are N items being sold at Ex Store. The price of the i-th (1≦i≦N) item is A_i Myon. Takahashi is going to buy some, at least one,...
#include <bits/stdc++.h> using namespace std; #define sqr(x) ((x) * (x)) #define pb push_back #define mp make_pair #define ins insert #define er erase #define bg begin() #define ed end() #define X first #define Y second #define fin(name) freopen(name, "r", stdin) #define fout(name) freopen(name, "w", stdout) #define ...