input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
There are many caves deep in mountains found in the countryside. In legend, each cave has a treasure hidden within the farthest room from the cave's entrance. The Shogun has ordered his Samurais to explore these caves with Karakuri dolls (robots) and to find all treasures. These robots move in the caves and log relativ... | #include <algorithm>
#include <functional>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <bitset>
#include <cl... |
In the year 2020, a race of atomically energized cars will be held. Unlike today’s car races, fueling is not a concern of racing teams. Cars can run throughout the course without any refueling. Instead, the critical factor is tire (tyre). Teams should carefully plan where to change tires of their cars.
The race is a r... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
while ( cin >> n, n ) {
vector<int> a(n+1);
vector<double> d(10001, 100000000.0);
d[0] = 0;
vector<int> is(10001, 0);
a[0] = 0;
for ( int i = 1; i <= n; i++ ) {
cin >> a[i];
is[a[i]] = 1;
}
double b;
... |
Fair Chocolate-Cutting
You are given a flat piece of chocolate of convex polygon shape. You are to cut it into two pieces of precisely the same amount with a straight knife.
Write a program that computes, for a given convex polygon, the maximum and minimum lengths of the line segments that divide the polygon into two... | #include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
using namespace std;
const double EPS = 1e-8;
const double INF = 1e12;
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<double> P;
typedef vector<P> V... |
Boolean Expression Compressor
You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning.
The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule:
> <E>... | a=65280; b=61680; c=52428; d=43690; e=65535
from heapq import heappush, heappop
base = [a, b, c, d, e, 0]
Q = [(1, el) for el in base]
L = {el: 1 for el in base}
H = []
get = L.get
push = H.append
while Q:
l, p = heappop(Q)
if L[p] < l: continue
if l+1 < get(p ^ e, 17):
L[p ^ e] = l+1
if l+1... |
A new lord assumed the position by the death of the previous lord in a Far Eastern province.
The new greedy lord hates concave polygons, because he believes they need much wasted area to be drawn on paper. He always wants to modify them to convex ones.
His castle is currently surrounded by a wall forming a concave po... | #include<iostream>
#include<cstdlib>
#include<cmath>
#include<complex>
#include<vector>
#include<algorithm>
#include<cassert>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
typedef complex<int> P;
const double eps= 1e-10;
const int N =200;
int cr... |
Problem G: Water clock
An unusually shaped water clock was discovered from the bottom of Lake Biwa.
The water clock is placed on a wide horizontal plane and consists of a cubic aquarium with one or more sides of 30 cm. The aquariums are placed on pedestals of various heights arranged in a grid pattern. The thickness ... | #include<iostream>
#include<vector>
#include<cstdio>
#include<cmath>
#define f first
#define s second
#define REP(i,n) for(int i=0; i<(int)(n); i++)
#define IN(x,s,g) ((x) >= (s) && (x) < (g))
#define ISIN(x,y,w,h) (IN((x),0,(w)) && IN((y),0,(h)))
#define print(x) printf("%d\n",x)
using namespace std;
const int _dx... |
Given a string of length n s = s1, s2,…, sn and m queries. Each query qk (1 ≤ k ≤ m) is one of four types, "L ++", "L-", "R ++", "R-", and l [for the kth query qk. k] and r [k] are defined below.
* L ++: l [k] = l [k-1] + 1, r [k] = r [k-1]
* L-: l [k] = l [k-1] -1, r [k] = r [k-1]
* R ++: l [k] = l [k-1], r [k] = r... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <iostream>
#include <set>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define PRIME1 99999883
#define PRIME2 99999893
#define EPS 0.00... |
Ikta has an extraordinary feeling for undirected graphs. Ikta likes the undirected graph G and its two-point s, t pair (G, s, t) that has the greatest "beauty". The "beauty" of a pair (G, s, t) is the edge e = \\ {u, v \\} (u and v are two different points of G), and the shortest path from s to t in G. Is the number of... | #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
... |
A: Isono, let's do that! --Sendame -
story
Nakajima "Isono ~, let's do that!"
Isono "What is that, Nakajima"
Nakajima "Look, that's that. It's hard to explain because I have to express it in letters for some reason."
Isono "No, it seems that you can put in figures and photos, right?"
<image>
Nakajima "It's true!... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* AOJ Sendame</br>
*
* @author ?????????????????§???
*/
public class Main{
enum Name {
ISONO("Isono-kun"), NAKAJIMA("Nakajima-kun"), HIKIWAKE("Hikiwake-kun");
// ??????????????????????... |
E: Balanced Edge Deletion
problem
Given a weighted simple undirected graph G of N vertices and M edges. The vertices are numbered from 1 to N and the edges are numbered from 1 to M. The i-th edge connects the vertices u_i and v_i, and its cost is w_i.
Consider performing the following operation only once for this gr... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
int n,m;
vector<pii> g[125252];
// スパソを写経しました
vector<pii> bridges;
vector<vector<int>> islands;
int num[125252];
bool inS[... |
Problem
Given a sequence of length $ N $ $ A = $ {$ a_ {1}, a_ {2}, a_ {3}, ..., a_ {n} $}.
It is assumed that $ a_ {i} $ ($ i = 1,2,3, ..., n $) is initialized with $ i $.
Process the following two types of queries a total of $ Q $ times.
* Outputs the value of the $ k $ th element from the beginning of the sequen... | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int N, Q;
cin >> N >> Q;
int p = 0;
while (Q--) {
int t, k;
cin >> t >> k;
if (t == 0) {
printf("%d\n", (p + --k) % N + 1);
}
else {
p = (p + k) % N;
}
}
return 0;
}
|
A rooted binary tree is a tree with a root node in which every node has at most two children.
Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:
* node ID of u
* parent of u
* sibling of u
* the number of children of u
* depth of u
* height of... | import java.util.*;
import java.io.*;
class Main {
static Node[] node = null;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
node = new Node[n];
for (int i=0; i<n; i++) {
node... |
Print all subsets of a set $S$, which contains $0, 1, ... n-1$ as elements. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elements.
Constraints
* $1 \leq n \leq 18$
In... | #include<bits/stdc++.h>
using namespace std;
using UL = unsigned int;
using ULL = unsigned long long;
using LL = long long;
#define rep(i, n) for(UL i = 0; i < (n); i++)
struct Problem {
public:
void Solve() {
UL N; scanf("%d", &N);
rep(i, 1 << N) {
printf("%d:", i);
rep(j, N) {
if ((i >> j) & 1) print... |
The Chef has prepared the appetizers in the shapes of letters to spell a special message for the guests. There are n appetizers numbered from 0 to n-1 such that if the appetizers are arrayed in this order, they will display the message. The Chef plans to display them in this order on a table that can be viewed by all g... | for _ in range(input()):
k,s = raw_input().strip().split()
k = int(k)
out = ['']*2**k
for n in range(2**k):
r = int(bin(n)[2:].zfill(k)[::-1],2)
out[n] = s[r]
print "".join(out) |
After getting bored of the monotonous routine of college, Chahak wants go back to the golden days of her life ‘Her Childhood’ when she used to enjoy playing games and one such game is "Stapu" (Hopscotch).
Chahak wants to play the game differently now. She plays the game on marble floor consisting of N parallelly placed... | # cook your code here
for _ in range(input()):
n,fff = map(int,raw_input().split())
s = map(int,raw_input().split())
if min(s) == 1 or max(s) == n:
print 'NO'
else:
f = True
s = sorted(s)
for i in range(len(s)-2):
if s[i+2]-s[i] == 2:
f = False... |
Henry and Derek are waiting on a room, eager to join the Snackdown 2016 Qualifier Round. They decide to pass the time by playing a game.
In this game's setup, they write N positive integers on a blackboard. Then the players take turns, starting with Henry. In a turn, a player selects one of the integers, divides it b... | grunds = [0,1,2,2,3,3,0,0,0,0,0,0]
def grundy(n):
return grunds[n] if n < 12 else grundy(n/12)
for cas in xrange(input()):
n = input()
a = map(int, raw_input().strip().split())
x = 0
for v in a: x ^= grundy(v)
print 'Henry' if x else 'Derek' |
Asmany strings are strings of '0's and '1's that have as many 00 as 11. A string such as 00110001 consists of 3 "00" and
1 "11". Of course this is not an Asmany string. 0011, 1100, 000111000111 are Asmany strings. An L'th Asmany number is the number of
Asmany strings of length L for all positive integers L.
For esote... | import sys
dp = set();
dp.add(2)
dp.add(4)
prev = 2
max=10**1000
i=2
while i:
cur=prev*4-(prev*2)/i
i=i+1
dp.add(cur)
dp.add(cur*2)
prev=cur
if cur>max:
break
t=int(input());
while t:
t=t-1
n=int(input());
if n in dp:
print ('YES')
else:
print ('NO') |
In a far away dystopian world, the measure of the quality of a person’s life is the numbers of likes he gets for an article about their life. For a person to stay alive, he has to acquire at least L number of likes before D days pass.
People in this world employ various techniques to increase the number of likes.... | t=input()
while t>0:
l,d,s,c=map(int,raw_input().split())
x=l*1.0/s
if d==1:
if s>=l:
x=1
else:
x=0
else:
x=pow(x,1.0/(d-1.0))
if (1+c)>=x:
x=1
else:
x=0
if x==1:
print "ALIVE AND KICKING"
else:
... |
Let's start from some definitions.
Strings A and B are called anagrams if it's possible to rearrange the letters of string A using all the original letters exactly once and achieve string B; in other words A and B are permutations of each other. For example, remote and meteor are anagrams, race and race are anagrams a... | import sys
from collections import Counter
num = int(sys.stdin.readline().rstrip())
text = sys.stdin.readline().rstrip()
common_dict = Counter(text)
while num != 1:
text = sys.stdin.readline().rstrip()
count = Counter(text)
tmp = {}
for key,val in common_dict.items():
if key in count:
tmp[key] = min(val,coun... |
You have a set of n weights. You know that their masses are a_1, a_2, ..., a_n grams, but you don't know which of them has which mass. You can't distinguish the weights.
However, your friend does know the mass of each weight. You can ask your friend to give you exactly k weights with the total mass m (both parameters ... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long x = 0, f = 1;
char c = getchar();
while ((c < '0' || c > '9') && (c != '-')) c = getchar();
if (c == '-') f = -1, c = getchar();
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
const int N = 1... |
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days [l_a; r_a] are lucky, then there are some unlucky days: [r_a + 1... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1000000 + 5;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
long long la, ra, ta, lb, rb, tb;
long long cal(long long la, long long ra, long long lb, long long rb) {
long long mn = max(la, lb), mx = min(ra, rb);
return max(0ll... |
You are given an array s consisting of n integers.
You have to find any array t of length k such that you can cut out maximum number of copies of array t from array s.
Cutting out the copy of t means that for each element t_i of array t you have to find t_i in s and remove it from s. If for some t_i you cannot find s... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200000;
int n, k, v[MAXN + 10];
bool can(int fr) {
int qtd = 0;
for (int i = 0; i <= MAXN; ++i) qtd += v[i] / fr;
return qtd >= k;
}
inline int bs() {
int lo = 1;
int hi = n / k;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (can(mid))
... |
Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree!
Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the s... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public ... |
Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.
In return, the fleas made a bigger ukulele for her: it has n strings, and each string has (10^{18} + 1) frets numerated from 0 to 10^{18}. The fleas use the array s_1, s_2, …... | #include <bits/stdc++.h>
using namespace std;
int main(void) {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
std::vector<long long> a(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i];
sort(a.begin(), a.end());
std::vector<long long> v(n + 1);
for (int i = 2; i <= n; i++) v[i] =... |
Alice has a string s. She really likes the letter "a". She calls a string good if strictly more than half of the characters in that string are "a"s. For example "aaabb", "axaa" are good strings, and "baca", "awwwa", "" (empty string) are not.
Alice can erase some characters from her string s. She would like to know wh... | lita=input()
a=lita.count('a')
b=len(lita)
if a>(b/2):
print(b)
else:
print(2*a-1)
|
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | def check(n ,s):
if n < 11:
print("NO")
return
k = n-11
t = "8"
if t in s[:k+1]:
print("YES")
return
else:
print("NO")
return
for i in range(int(input())):
n = int(input())
s = input()
check(n,s)
|
A sequence a_1, a_2, ..., a_k is called an arithmetic progression if for each i from 1 to k elements satisfy the condition a_i = a_1 + c ⋅ (i - 1) for some fixed c.
For example, these five sequences are arithmetic progressions: [5, 7, 9, 11], [101], [101, 100, 99], [13, 97] and [5, 5, 5, 5, 5]. And these four sequence... | n=int(input())
a=list(map(int,input().split()))
res=-1
a=list(map(lambda x: (x[1],x[0]),enumerate(a)))
a.sort()
cnt=0
if n==2:
res=1
else:
#keep 1 and 2
diff=a[1][0]-a[0][0]
cnt=0
prev=a[0][0]
ind=0
for i in range(1,len(a)):
if a[i][0]-prev==diff:
prev=a[i][0]
else:
cnt+=1
ind=a[... |
Mislove had an array a_1, a_2, ⋅⋅⋅, a_n of n positive integers, but he has lost it. He only remembers the following facts about it:
* The number of different numbers in the array is not less than l and is not greater than r;
* For each array's element a_i either a_i = 1 or a_i is even and there is a number (a_i)/(... | from sys import stdin
def count(N, l, r):
resultmin, resultmax = 0, 0
fmax, smax = 1, 1
for n in range(N):
if l:
resultmin += fmax
fmax *= 2
l -= 1
else:
resultmin += 1
if r:
resultmax += smax
smax *= 2
... |
You are working for the Gryzzl company, headquartered in Pawnee, Indiana.
The new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be n antennas located somewhere in the park.... | #include <bits/stdc++.h>
using namespace std;
const int mn = 1e5 + 10;
long long x[mn], y[mn], d[mn];
inline long double sq(long double x) { return x * x; }
inline long long sq(long long x) { return x * x; }
long double eps = 1e-8;
long double i1x, i1y, i2x, i2y;
vector<pair<long long, long long> > ans;
void idk(long l... |
You are at the top left cell (1, 1) of an n × m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y).
Some cells of the labyrinth contain r... | #include <bits/stdc++.h>
using namespace std;
const long long mod = (long long)1e9 + 7;
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
long long n, m;
cin >> n >> m;
long long a[n][m];
for (long long i = 0; i < n; ++i) {
for (long long j = 0; j < m; ++j) {
char now;
cin >> no... |
Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked n of them how much effort they needed to reach red.
"Oh, I just spent x_i hours solving problems", said the i-th of them.
Bob wants to train his math skills... | T = int(input())
for t in range(T):
a = [int(x) for x in list(input())]
if sum(a)%3==0 and a.count(0)>0 and (a.count(0)+a.count(2)+a.count(4)+a.count(6)+a.count(8)>1):
print("red")
else:
print("cyan") |
Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of n light bulbs in a single row. Each bulb has a number from 1 to n (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland.... | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOExcepti... |
Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.
The text is a string s of lowercase Latin letters. She considers a string t as hidden in string s if t exists as a subsequence of s whose indices form an arithmetic pr... | import os
import sys
def main():
s=input()
dp=[[0]*(27) for i in range(27)]
d=[0]*27
for i in range(len(s)):
k=ord(s[i])-97
for j in range(27):
dp[k][j]+=d[j]
d[k]+=1
ans=0
for i in range(27):
for j in range(27):
ans=max(ans, dp[i][j])
for i in d:
ans=max(ans , i)
print(ans)
if __name__ == "__ma... |
Dreamoon likes coloring cells very much.
There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.
You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n)
Dreamoon will perform m operations.
In i-th operation, Dreamoon will choose a number ... | #include <bits/stdc++.h>
const long long N = 1e6 + 10;
const long long INF = 1e18;
const long long inf = -1e18;
const long long MOD = 1e9 + 7;
const long long xesh = 31;
using namespace std;
long long n, m, p, k, mx, ans, t, g;
long long a[N];
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> a[... |
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow:
* \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x.
* lcm(s) is the minimum positive integer x, that divisible on all integ... | #include <bits/stdc++.h>
using namespace std;
long long prime[200001];
vector<long long> v[200001];
long long p(long long a, long long b) {
long long res = 1;
while (b) {
if (b % 2) res *= a;
a *= a;
b /= 2;
}
return res;
}
int32_t main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;... |
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.
This is an interactive problem.
You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secre... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Ar... |
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).
A... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
unordered_map<int, int> el_cnt, grp_cnt;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
el_cnt[num]++;
grp_cnt[el_cnt[num]]++;
}
int q;
cin >> q;
while (q--) {
char typ;
int num;
cin >> typ >> num... |
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal.
Hopefully, you've met a very handsome wandering trader who has two trade offers:
* exchange 1 stick for x sticks (you lose 1 stick and gain x sticks... | #include <bits/stdc++.h>
using namespace std;
void fast_io() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
void sol() {
long long x, y, k;
cin >> x >> y >> k;
cout << (k + y * k + x - 3) / (x - 1) + k << '\n';
}
int32_t main() {
fast_io();
long long t;
cin >> t;
while (t-- > 0) sol();
return ... |
Shikamaru and Asuma like to play different games, and sometimes they play the following: given an increasing list of numbers, they take turns to move. Each move consists of picking a number from the list.
Assume the picked numbers are v_{i_1}, v_{i_2}, …, v_{i_k}. The following conditions must hold:
* i_{j} < i_{j+... | #include <bits/stdc++.h>
template <typename T>
bool ckmax(T& a, const T& b) {
return b > a ? a = b, 1 : 0;
}
template <typename T>
bool ckmin(T& a, const T& b) {
return b < a ? a = b, 1 : 0;
}
const int MV = 1e5 + 10;
const int MM = 1e5 + 10;
const int MG = 450;
const int INF = 0x3f3f3f3f;
struct DSU {
int p[MM],... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has sequence a consisting of n integers.
The subsequence of the sequence a is such subseque... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
const long long mod = 1000000007;
map<int, int> mp;
map<int, int>::iterator it;
long long fv[maxn], f[maxn];
long long cnt, tot;
long long b[maxn];
long long dp[2100][2100];
long long quick_power(long long x, long long y) {
long long ans = 1;
fo... |
You are given n - 1 integers a_2, ..., a_n and a tree with n vertices rooted at vertex 1. The leaves are all at the same distance d from the root.
Recall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root v... | from collections import deque
T = int(input())
def solve(E, W):
nodes = {idx: (w, []) for idx, w in weights.items()}
for u, v in E:
nodes[u][1].append(v)
nodes[v][1].append(u)
layers = []
visited = set([1])
parents = {idx: None for idx in weights.keys()}
Q = deque([1])
whi... |
I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus 62 has exactly n stops (stop 1 goes first on its way and stop n goes last). The stops are positioned on a straight line and their coordinates are 0... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1000005;
const long long INFLL = 1000000000000000005ll;
const long long MOD = 1000000007;
const int RIGHT = 262144;
const int SIZE = 525000;
struct Node {
double left, right, total, sum;
Node(double p1 = 0, double p2 = 0, double p3 = 0, double p4 = 0)
... |
Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array a = [a_1, a_2, …, a_n] of n distinct integers. An array b = [b_1, b_2, …, b_k] is called nice if for any two distinct elements b_i, b_j of b, |b_i-b_j| appears ... | #include<bits/stdc++.h>
typedef int LL;
typedef double dl;
#define opt operator
#define pb push_back
#define pii std::pair<LL,LL>
const LL maxn=1e6+9,mod=998244353,inf=0x3f3f3f3f;
LL Read(){
LL x(0),f(1); char c=getchar();
while(c<'0' || c>'9'){
if(c=='-') f=-1; c=getchar();
}
while(c>='0' && c<='9'){
x=(x<<3ll... |
Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters e... | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
int main() {
int n;
scanf("%d", &n);
;
int x1 = 0, x2 = 0, y = 0;
for (int i = 0; i < n; ++i) {
char c[10];
scanf("%s", c);
if (strlen(c) == 4) {
y++;
} else {
if (c[0] == 'U' && c[1] == 'R') {
x1++... |
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.
To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scie... | #include <bits/stdc++.h>
using namespace std;
int main() {
long n;
cin >> n;
long long int ans = 0, ans1, k, a1, a2, x, y, m, s = 0;
vector<pair<long, pair<long, long>>> r;
for (int i = 0; i < n; ++i) {
cin >> k;
s += k;
cin >> a1 >> x >> y >> m;
ans1 = 0;
r.push_back(make_pair(0, make_pai... |
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.
You are given an array of n positive integers. For each of them determine whether it is Т-prime or not.
Input
The f... | N=1000000
a=[1]*N
a[0]=a[1]=0
s=set()
for i,x in enumerate(a):
if x:
s.add(i*i)
for j in range(i+i,N,i):
a[j] = 0
n= int(input())
lis = list(map(int,input().split()))
for i in lis:
print("YES" if i in s else "NO") |
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:
* a1 = p, where p is some integer;
* ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is som... | //package round156;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[... |
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ... | n = input()
a = map(int, raw_input().split())
sp = [0 for i in range(5000)]
for i in a: sp[i-1] += 1
k = 1
for i in range(5000):
if(not sp[i]):
k = i + 1
break
print k |
Yaroslav calls an array of r integers a1, a2, ..., ar good, if it meets the following conditions: |a1 - a2| = 1, |a2 - a3| = 1, ..., |ar - 1 - ar| = 1, |ar - a1| = 1, at that <image>.
An array of integers b1, b2, ..., br is called great, if it meets the following conditions:
1. The elements in it do not decrease (... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
int n, m, k, dp[2][51][101][101], now = 1, last = 0, C[101][101], ans;
void update(int &x, int y) { x = (x + y) % mod; }
int main() {
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i <= 100; i++) {
C[i][0] = 1;
for (int j = 1; j <= i; j... |
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the ro... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 210;
int N;
char room[MAXN][MAXN];
vector<pair<int, int> > cells;
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++) scanf("%s", room[i]);
bool done = true;
cells.clear();
for (int i = 0; done && i < N; i++) {
... |
There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept ... | #include <bits/stdc++.h>
using namespace std;
const double EXP = 1e-9;
const int INF = 0x3f3f3f3f;
const long long MINF = 0x3f3f3f3f3f3f3f3f;
const double DINF = 0xffffffffffff;
const int mod = 1e9 + 7;
const int N = 1e5 + 5;
int a[N];
int b[N];
int main() {
std::ios::sync_with_stdio(false);
int n, r1, r2, x;
cin... |
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1.
In the festival m fireworks will be launched. The i-th (1 ≤ i ≤ m) launching is on time ti at section ai. If you are at s... | #include <bits/stdc++.h>
using namespace std;
int a[301], t[301];
int dp[2][150001];
int sp[18][150001];
int n, m, d, ans = 1e9, tt;
long long vv = 0;
void build(int x) {
for (int i = 1; i <= n; i++) sp[0][i] = dp[x][i];
int temp = log(n + 0.0) / log(2.0);
for (int i = 1; i <= temp; i++)
for (int j = 1; j + (... |
Let's assume that
* v(n) is the largest prime number, that does not exceed n;
* u(n) is the smallest prime number strictly greater than n.
Find <image>.
Input
The first line contains integer t (1 ≤ t ≤ 500) — the number of testscases.
Each of the following t lines of the input contains integer n (2 ≤ n ≤ ... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
/**
* Created by dhamada on 15/05/21.
*/
public class B {
public static void main(String[] args) {
InputRea... |
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column... | #include <bits/stdc++.h>
using namespace std;
int a[110], b[110];
int main() {
int n, m;
scanf("%d%d", &n, &m);
if (n == 1)
a[1] = 1;
else if (n == 2)
a[1] = 3, a[2] = 4;
else {
a[1] = n - 2;
for (int i = 2; i <= n; i++) {
a[i] = 2;
}
}
if (m == 1)
b[1] = 1;
else if (m == 2... |
DZY loves chessboard, and he enjoys playing with it.
He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa... | n,m = map(int,input().split())
for i in range(n):
s = list(input())
for j in range(m):
if s[j]==".":
if (i+j)%2==0:
s[j]="W"
else:s[j]="B"
k="".join(s)
print(k)
|
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».
The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | def dif(a, b):
cont = 0
for i in range(0, len(a)):
if a[i]!=b[i]:
cont+=1
return cont
n, m, k = [int(x) for x in input().split()]
lista = []
string = ''
for i in range (0, m+1):
string = bin(int(input()))[2:]
string = ('0'*(n-len(string)))+string
if i<m:
lista.appe... |
Once upon a time in a kingdom far, far away… Okay, let’s start at the point where Ivan the Fool met Gorynych the Dragon. Ivan took out his magic sword and the battle began. First Gorynych had h heads and t tails. With each strike of the sword Ivan can either cut off several heads (from 1 to n, but not more than Gorynyc... | #include <bits/stdc++.h>
using namespace std;
int r;
int n, m;
int dh[2][210];
int dt[2][210];
int h0, t0;
void read() {
scanf("%d %d %d", &h0, &t0, &r);
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d %d", &dh[0][i], &dt[0][i]);
scanf("%d", &m);
for (int i = 1; i <= m; i++) scanf("%d %d", &dh[1][i], ... |
Cthulhu decided to catch Scaygerboss. Scaygerboss found it out and is trying to hide in a pack of his scaygers. Each scayger except Scaygerboss is either a male or a female. Scaygerboss's gender is "other".
Scaygers are scattered on a two-dimensional map divided into cells. A scayger looks nerdy and loveable if it is ... | #include <bits/stdc++.h>
const int MAXN = 22 + 5;
const int MAXM = 2e5 + 5;
int n, m;
char str[MAXN][MAXN];
inline int id(int i, int j) { return (i - 1) * m + j; }
int dis[MAXN * MAXN][MAXN * MAXN];
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
inline void bfs(std::pair<int, int> v, int dis[]) {
for... |
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that ... | #include <bits/stdc++.h>
using namespace std;
int n;
int main() {
cin >> n;
if (n == 1) {
cout << 1;
return 0;
}
cout << 1 << " " << n << " ";
int diff = n - 2, prev = n;
for (int i = 3; i <= n; i++) {
int curr = prev + diff;
if (i % 2) curr = prev - diff;
cout << curr << "\n";
prev ... |
Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.
Once a year the President visited his historic home town t, for which his motorcade passes alo... | #include <bits/stdc++.h>
using namespace std;
int n, m, s, t;
int cnt, u[400010], v[400010], last1[200010], last2[200010], nxt[400010];
long long w[400010], d1[200010], d2[200010];
unsigned long long f1[400010], f2[400010];
void insert(int x, int y, int z) {
u[++cnt] = x;
v[cnt] = y;
w[cnt] = (long long)z;
nxt[... |
Polycarp has quite recently learned about email aliases. Of course, he used to suspect that the case of the letters doesn't matter in email addresses. He also learned that a popular mail server in Berland bmail.com ignores dots (characters '.') and all the part of an address from the first character "plus" ('+') to cha... | from sys import stdin
line = stdin.readline()
n = int(line)
d = {}
for i in xrange(0, n):
line = stdin.readline().strip()
ad = line.lower().split("@")
if ad[1] == "bmail.com":
ad[0] = ad[0].replace(".", "")
ad[0] = ad[0].split("+")
ad[0] = ad[0][0]
ad = str(ad)
if not ad in d:
d[ad] = []
d[ad].append(l... |
Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbo... | from sys import stdin
from itertools import repeat
from collections import defaultdict
def main():
n = int(stdin.readline())
h = defaultdict(list)
w = defaultdict(list)
for i in range(n):
a, b, c, d = map(int, input().split())
if a > c:
a, c = c, a
if b > d:
... |
The Department of economic development of IT City created a model of city development till year 2100.
To prepare report about growth perspectives it is required to get growth estimates from the model.
To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic developmen... | a,b,c=map(float,input().split())
q=((b*b-4*a*c)**0.5)
x=((-b+q)/(2*a))
y=((-b-q)/(2*a))
print(max(x,y))
print(min(x,y)) |
The farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:536870912")
const int MOD = 1000000007;
const int INF = 1000000001;
const int MAXN = 100010;
const long double EPS = 1e-6;
const int HASH_POW = 29;
const long double PI = acos(-1.0);
using namespace std;
void my_return(int code) { exit(code); }
int n, m, p[1010][... |
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.
The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call ver... | import java.util.*;
public class Main682C{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt()+1;
Node[] v = new Node[n];
//int[][] d = new int[n][n];
boolean[] visited = new boolean[n];
for(int i=1; i<n; i++){
v[i] = new Node(in.nextInt());
}
for(int ... |
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.
Initially t... | import java.util.Scanner;
public class SpiderMan{
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n=kbd.nextInt();
kbd.nextLine();
int sum=0;
for(int i=0;i<n;i++)
{
sum+= kbd.nextInt()-1;
if(sum%2==0)
System.out.println("2");
else
System.out.println("1... |
Several years ago Tolya had n computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD in clockwise order. The names were distinct, the length of each name was equal to k. The names didn't overlap.
Thus, there is a c... | #include <bits/stdc++.h>
using namespace std;
int N, K, G, f[1100100];
char s[2200200], t[100100];
map<long long, int> id;
bool did[100100];
vector<int> v;
struct hash {
long long cum[2200200], rcum[2200200], MOD, M = 2200100, po[2200200];
void init(long long mod) {
MOD = mod, po[0] = 1;
for (int i = 1; i <... |
The country Treeland consists of n cities connected with n - 1 bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly 2k teams from 2k different citi... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200000 + 10;
using namespace std;
int n, k, root = 1;
vector<int> v[MAXN], l, r;
int vis[MAXN];
void init() {
for (int i = 0; i < MAXN; ++i) v[i].clear();
memset(vis, 0, sizeof vis);
l.clear();
r.clear();
root = 0;
}
int get_root(int x, int father... |
Limak has a grid that consists of 2 rows and n columns. The j-th cell in the i-th row contains an integer ti, j which can be positive, negative or zero.
A non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to 0.
Limak wants to choose some nice rectangles and give them ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
const int inf = 0x3f3f3f3f;
long long sum[4][maxn];
int f[4][maxn];
map<long long, int> lst;
int n;
void init(long long *sum, int *f) {
lst.clear();
for (int i = 1; i <= n; ++i) sum[i] += sum[i - 1];
lst[0] = 0;
for (int i = 1; i <= n; ++i... |
Zane and Zane's crush have just decided to date! However, the girl is having a problem with her Physics final exam, and needs your help.
There are n questions, numbered from 1 to n. Question i comes before question i + 1 (1 ≤ i < n). Each of the questions cannot be guessed on, due to the huge penalty for wrong answers... | #include <bits/stdc++.h>
using namespace std;
inline char gc() {
static char now[1 << 16], *S, *T;
if (T == S) {
T = (S = now) + fread(now, 1, 1 << 16, stdin);
if (T == S) return EOF;
}
return *S++;
}
inline long long read() {
register long long x = 0, f = 1;
char ch = gc();
while (!isdigit(ch)) {... |
Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.
Bottle with potion has two values x and y written on it. These values define four moves which can be performed... | import java.util.Scanner;
/**
* Created by shalin on 3/7/17.
*/
public class Problem817A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x1 = in.nextInt();
int y1 = in.nextInt();
int x2 = in.nextInt();
int y2 = in.nextInt();
int ... |
Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.
For each two integer numbers ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t, n, i, j;
int l, r, x, y, k;
cin >> l >> r >> x >> y >> k;
int flag = 0;
for (int i = l; i <= r; i++) {
if (i % k == 0) {
int reqd = i / k;
if (reqd >= x && reqd <= y) {
... |
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.
String t is called a palindrome, if it reads the same from left to right and from right to left.
For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin... | s=input()
if s==s[::-1]:
print("YES")
else:
news=""
c=0
start=0
end=len(s)
for i in range(len(s)):
if s[i]!="0":
start=i
break
for i in range(len(s)-1,-1,-1):
if s[i]!="0":
end=i+1
break
news=s[start:end]
if news==news[:... |
You are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 ≤ b1 < b2 < ... < bk ≤ n) in such a way that the value of <image> is maximized. Chosen sequence can be empty.
Print the maximum possible value of <image>.
Input
The first l... | import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] a= new int[n];
for (int i = 0; i < n; i++) {
... |
Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.
When a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if i-th garland is switched on during x-th secon... | k1, k2, k3 = map(int, input().split())
ans = 'NO'
if [k1, k2, k3].count(2) >= 2:
ans = 'YES'
if 1 in [k1, k2, k3]:
ans = 'YES'
if [k1, k2, k3].count(3) >= 3:
ans = 'YES'
if 2 in [k1, k2, k3] and [k1, k2, k3].count(4) == 2:
ans = 'YES'
print(ans)
|
A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.
A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, th... | #include <bits/stdc++.h>
using namespace std;
inline void splay(int &v) {
v = 0;
char c = 0;
int p = 1;
while (c < '0' || c > '9') {
if (c == '-') p = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
v = (v << 3) + (v << 1) + c - '0';
c = getchar();
}
v *= p;
}
const int N = 100010;
i... |
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class D {
static ArrayList<state>[] adj;
static int n, m, x, y;
static long[] t;
static long[] c;
public static void ma... |
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:
* the Power Gem of purple color,
* the Time Gem of green color,
* the Space Gem of blue color,
* the Soul Gem of orange color,
* the Reality Gem of red color,
* the Mind Gem of yellow color.
... | #include <bits/stdc++.h>
using namespace std;
int n, c;
bool b[10];
string k;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> k;
if (k == "purple") b[0] = 1;
if (k == "red") b[4] = 1;
if (k == "green") b[1] = 1;
if (k == "blue") b[2] = 1;
if (k == "orange") b[3] = 1;
if (k ==... |
Lily Aldrin, as the slap bet commissioner, needs to resolve issues regarding slap bets due with Barney and Marshall. She has mandated that there be a fixed period of time in which the slaps may be used.
So, she draws two lines representing the given two time slots, each of Barney and Marshall; you need to help her wr... | test=input()
for i in range(test):
b1,b2,m1,m2=map(int,raw_input().split(" "))
left=min(max(b1,b2),max(m1,m2))
right=max(min(b1,b2),min(m1,m2))
if (left>right):
print "Nothing"
elif (left < right):
print "Line"
else:
print "Point" |
DG (Departmental Gathering) is coming….
As one of the most famous girls in the college everybody is smitten with Harshada and wants to give
her roses. But Harshada is only into coders , therefore she sends out word that she would accept
roses from the nth guy only if he brings her x roses such that ‘x’ is the nth ... | def fun(n):
if n <= 2:
return n
if(n%2==1):
return fun(n-2) * fun(n-1)
elif(n%2==0):
return fun(n-2) + fun(n-1)
t=int(input())
while(t):
x=int(input())
val=fun(x)
print(val)
t=t-1 |
Problem :
The Starks(S),Lannisters(L) and the Baratheons(B) are fighting for the
Iron Throne. These three houses are fighting from ages to capture the
throne.
The N th battle goes on for N days before a winner
emerges. Interestingly,the battles follow a pattern.
If the battle
number N is divisible by 3 it is fought... | __author__ = 'apritam'
import math
no_of_test=int(raw_input())
while no_of_test > 0:
t_range = raw_input()
t= long(t_range)
n = long(math.ceil((-1+(math.ceil(math.sqrt(8*t-1))))/2))
if n % 3 == 0:
print 'SL'
elif n % 3 == 1:
print 'LB'
else:
print 'BS'
no_of_test-=1 |
"IT can do almost everything using codes", a Arjun(a CS Student) says to his mathematics' teacher. Mathematics teacher gives a very simple problem to solve using codes but Arjun got stuck. The problem was find out all those pairs of two numbers whose multiplication is divisible by their sum, i.e.
You are given a numb... | t=input()
for i in range(0,t):
x=input()
c=0
for j in range(1,x):
for k in range(j+1,x+1):
if((j*k)%(j+k)==0):
c=c+1
print c |
Karan performed poorly in the Capillary Java Hiring Challenge because he did not know the concept of trees. After the contest, he asks you to help him out in the questions.
Given two nodes of a binary tree, you need to tell the lowest common ancestor.
The root node is 1 and the general form of left node is 2n and of ... | '''
# 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(raw_input())
for i in range(t):
a,b = map(int,raw_input().split())
while(a != b):
if a > b:
if a % 2==0:
a = a... |
Heisenberg is very fond of mixing various strings together. But he has storage problem.
He wants that his strings use as less space as possible.
He has N strings right now. He wants to store them together.
To reduce space he can use this property of mixing two strings:
Suppose he has string A="abcdef" and B="cdefg... | def suture(s1, s2):
for n in xrange(len(s2), 0, -1):
if s1.endswith(s2[:n]):
return s1 + s2[n:]
return s1 + s2
import itertools
strings = []
for _ in xrange(input()):
strings.append(raw_input())
best = 10**100
for perm in itertools.permutations(strings):
line = ''
for s in perm:... |
It is vacation time and Panda is in his hometown Pandaland. Panda is very bored so he started studying some interesting properties of natural numbers. Some days later he meet his friend Agham, who is pretty good in mathematics and tells him about interesting properties of natural numbers & ask him to test his skills.So... | from sys import stdin
import math
def get(n):
return int(math.sqrt(n))
a = stdin.readlines()
for i in a[1:]:
l,r = map(int,i.strip().split())
if r < 11:
while True:
x = 3
else:
print get(r)-get(l-1) |
Harsh is thinking of starting his own business.He has decided to start with the hotel business.
He has been given a list which contains the arrival time and the duration of stay of each guest at his hotel.
He can give 1 room to only 1 guest.Since he does not want to disappoint his guests he wants to find the minimum nu... | T = input()
while(T>0):
n = input()
A = map(int,raw_input().split())
D = map(int,raw_input().split())
E = []
l = len(A)
for i in range(l):
E.append(A[i]+D[i])
A.sort()
E.sort()
i = 0
j = 0
m = 0
g = 0
while((i<n) and (j<n)):
if(A[i] < E[j]):
g = g+1
if(g>m):
m = g
i = i+1
else:
g = g... |
Karan has decided to give stickers to all the attendees of the last day of Google Week. The stickers will be given such that the last person to enter the hall gets a single sticker. The second last person entering the hall gets two stickers and so on.
Given the strength of the audience, can you tell him the total numb... | from sys import stdin
a = stdin.readlines()
for i in a[1:]:
n = int(i)
print ((n*(n+1))/2 % 2**32) |
Today Omar has assignment problems from his math professor. Yes, Omar has infinite number of questions that he must solve today. The first problem went something like this.
Given N integers in the form of A_i where 1 ≤ i ≤ N, Omar wants to make each number A_i in the N numbers equal to M. To convert a number A_i to ... | import math
t=int(raw_input())
while t:
t=t-1
n = int(raw_input())
a = map(int,raw_input().split())
a.sort()
m = 0
x=n/2
if n%2==0:
m = int(math.ceil((a[x-1]+a[x])/float(2)))
else:
m = a[x]
cost = 0
for i in a:
cost+=abs(m-i)
print cost |
We have N strings of lowercase English letters: S_1, S_2, \cdots, S_N.
Takahashi wants to make a string that is a palindrome by choosing one or more of these strings - the same string can be chosen more than once - and concatenating them in some order of his choice.
The cost of using the string S_i once is C_i, and t... | #include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
struct state {
string pref, suff;
ll cost;
int hash() {
ll res = 0;
for (int i=0;i<pref.length();i++) {
res = (res*41+pref[i]-... |
We have held a popularity poll for N items on sale. Item i received A_i votes.
From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes.
If M popular items can be selected, print `Yes`; otherwise, print `No`.
Constraints
* 1 \... | n,m=map(int,input().split())
a=list(map(int,input().split()))
c=len([i for i in a if i>=sum(a)/(4*m)])
print("Yes" if c>=m else "No") |
Given is a string S representing the day of the week today.
S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.
After how many days is the next Sunday (tomorrow or later)?
Constraints
* S is `SUN`, `MON`, `TUE`, `WED`, `THU`,... | s=input()
A=["","SAT","FRI","THU","WED","TUE","MON","SUN"]
print(A.index(s)) |
There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.
Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).
When Mountain i (1 \leq i \l... | #include <bits/stdc++.h>
using namespace std;
int main(){
int n; cin>>n;
vector<long long> a(n);
long long x=0LL;
for(int i=0; i<n; ++i){
cin>>a[i];
if(i%2==0)x+=a[i];
else x-=a[i];
}
cout<<x<<" ";
x/=2;
for(int i=0; i<n-1; ++i){
x=a[i]-x;
cout<<x*2<<" ";
}
cout<<endl;
}
|
Katsusando loves omelette rice.
Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.
To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.
The i-th person answered that he/she only l... | import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
int[] dish = new int[Integer.parseInt(sc.next())];
for (int i = 0; i < n; i++) {
int num = Integer.... |
You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. The order of a,b,c does matter, and some of them can be the same.
Constraints
* 1 \leq N,K \leq 2\times 10^5
* N and K are integers.
Input
Input is given from ... | n,k = map(int, input().split())
ans=(n//k)**3
if k%2==0:
ans+=((n+k//2)//k)**3
print(ans) |
We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j).
The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}.
You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by... | h,w,d = map(int,input().split())
a = [0]*h
for i in range(h):
a[i] = list(map(int,input().split()))
num = [[] for i in range(w*h+1)]
for i in range(h):
for j in range(w):
num[a[i][j]].append([i,j])
s = [0]*(h*w+1)
for i in range(1,h*w-d+1):
s[d+i] = s[i] + abs(num[d+i][0][0]-num[i][0][0]) + abs(num[... |
You are given an integer N.
Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.
If there are multiple solutions, any of them will be accepted.
Constraints
* It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.
Inputs
Input is given from Stan... | #include <bits/stdc++.h>
#include <math.h>
using namespace std;
long long inf=1000000007;
int main(){
long long und;
cin>>und;
for(long long i=1;i<=3500;i++){
for(long long j=1;j<=3500;j++){
if((4*i*j-und*j-und*i)>0 && (und*i*j)%(4*i*j-und*j-und*i)==0){
cout<<i<<" "<<j<<" "<<(und*i*j)/(4*i*j-und*j-und*i... |
Alice and Brown loves games. Today, they will play the following game.
In this game, there are two piles initially consisting of X and Y stones, respectively. Alice and Bob alternately perform the following operation, starting from Alice:
* Take 2i stones from one of the piles. Then, throw away i of them, and put the... | print('ABlriocwen'[-2<eval(input().replace(' ','-'))<2::2]) |
Takahashi is a magician. He can cast a spell on an integer sequence (a_1,a_2,...,a_M) with M terms, to turn it into another sequence (s_1,s_2,...,s_M), where s_i is the sum of the first i terms in the original sequence.
One day, he received N integer sequences, each with M terms, and named those sequences A_1,A_2,...,... | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef __int128 INT;
struct cww{cww(){
ios::sync_with_stdio(false);cin.tie(0);
}}star;
#define fin "\n"
#define FOR(i,bg,ed) for(int i=(bg);i<(ed);i++)
#define REP(i,n) FOR(i,0,n)
#define fi first
#define se second
#define pb push_back
#define DEBU... |
Write a program which reads an integer n and identifies the number of combinations of a, b, c and d (0 ≤ a, b, c, d ≤ 9) which meet the following equality:
a + b + c + d = n
For example, for n = 35, we have 4 different combinations of (a, b, c, d): (8, 9, 9, 9), (9, 8, 9, 9), (9, 9, 8, 9), and (9, 9, 9, 8).
Input
... | import java.util.Scanner;
class Main{
public static void main(String[] a){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
int n = scan.nextInt();
int sum = 0;
if(n > 36) System.out.println(0);
else{
for(int i = 0; i <= 9; i++){
for(int j = 0; j <= 9; j++){
for(int k = 0; k... |
There is a bus route as shown in Figure 1. There are 10 stops, each numbered 0-9. The bus turns back at stop 0, but the other side is a circulation route, which circulates in the order of 5 → 6 → 7 → 8 → 9 → 5 as shown in the figure.
<image>
For this bus route, create a program that inputs the stop to get on and the... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Bus Line
*/
public class Main {
// 15 stations
final static int[] route = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 4, 3, 2, 1 };
public static void main(String[] args) throws IOException {
BufferedReader br = new Buff... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.