input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.
Consider the painting as a n × m rectangular grid. At the beginning an x × y rectangular brush is placed somewhere in the frame, with edges parallel to the frame, (1 ≤ x ≤ n, 1 ≤ y ≤ m)... | #include <bits/stdc++.h>
using namespace std;
int getint() {
int s = 0, o = 1;
char c;
for (c = getchar(); c < '0' || c > '9'; c = getchar())
if (c == '-') o = -1;
for (; c >= '0' && c <= '9'; c = getchar()) s *= 10, s += c - '0';
return s * o;
}
const int maxn = 1010;
int a[maxn][maxn], b[maxn][maxn], n,... |
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the po... | x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
n = int(input())
arr = []
for _ in range(n):
a, b, c = map(int, input().split())
arr.append((a,b,c))
res = 0
for i in arr:
a, b, c = i
if(b != 0):
y00 = -c/b
y01 = -(a+c)/b
s1 = x1*(y01-y00)-(y1-y00)
s2 = x2*(y01-y00)-(y2-y00)
if(s1<0<s... |
You are given sequence a1, a2, ..., an and m queries lj, rj (1 ≤ lj ≤ rj ≤ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x ≠ y), that:
* both indexes of the elements lie within range [lj, rj], that is, lj ≤ x, y ≤ rj;
* the values of the elements are equal, tha... | #include <bits/stdc++.h>
using namespace std;
const long long N = 5e5 + 10;
const long long inf = 1e18;
long long n, m;
map<long long, long long> last;
vector<pair<long long, long long> > q[N];
long long a[N], nex[N];
long long t[4 * N];
long long ans[N];
long long get(int v, int tl, int tr, int L, int R) {
if (tl > ... |
Yura has a team of k developers and a list of n tasks numbered from 1 to n. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing no less than 2 numbers, i. e. a sequence of form l, l + 1, ..., r for som... | #include <bits/stdc++.h>
using namespace std;
const int inf = int(1e9);
const double eps = 1e-9;
const double pi = 4 * atan(double(1));
const int N = int(3e5) + 100;
int murmur(int x) {
x ^= x >> 16;
x *= -2048144789;
x ^= x >> 13;
x *= -1028477387;
x ^= x >> 16;
return x;
}
struct open_map {
int n, sz;
... |
Sasha and Ira are two best friends. But they aren’t just friends, they are software engineers and experts in artificial intelligence. They are developing an algorithm for two bots playing a two-player game. The game is cooperative and turn based. In each turn, one of the players makes a move (it doesn’t matter which pl... | #include <bits/stdc++.h>
using namespace std;
int n;
int fac[2000010], a[2000010];
const int mod = 1000000007;
int ans = 0;
int fpow(int i, int j) {
int ret;
if (j == 0) return 1;
ret = fpow(i, j / 2);
ret = (long long)ret * ret % mod;
if (j % 2 == 1) ret = (long long)ret * i % mod;
return ret;
}
int inv(in... |
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.
Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputSt... |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | a = raw_input()
a = list(a)
b = raw_input()
b = list(b)
c = []
for i in range(len(a)):
if a[i] == b[i]:
c.append('0')
else:
c.append('1')
print "".join(c) |
Limak is a smart brown bear who loves chemistry, reactions and transforming elements.
In Bearland (Limak's home) there are n elements, numbered 1 through n. There are also special machines, that can transform elements. Each machine is described by two integers ai, bi representing two elements, not necessarily distinct... | #include <bits/stdc++.h>
using namespace std;
namespace io {
const int N = 1 << 20;
char buf[N], *t1 = buf, *t2 = buf;
inline int read() {
static int an;
an = 0;
static char ch;
ch = t1 == t2 && (t2 = (t1 = buf) + fread(buf, 1, N, stdin), t1 == t2)
? EOF
: *t1++;
while (ch < 48 || ch > 5... |
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know l... | #include <bits/stdc++.h>
using namespace std;
int a[10005], f[10005][4], q[28000], h2[10005], h3[10005], n, or230[27500],
or2900[27500];
char toc[200];
int main() {
char in = getchar();
while (in != '\n') a[++n] = in - 'a' + 1, in = getchar();
for (int i = 6; i <= n; i++)
h2[i] = a[i] * 900 + a[i + 1] * 3... |
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite!... | 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 FileReader("input.txt"));
o... |
Owl Sonya decided to become a partymaker. To train for this role she gather all her owl friends in the country house. There are m chairs located in a circle and consequently numbered with integers from 1 to m. Thus, chairs i and i + 1 are neighbouring for all i from 1 to m - 1. Chairs 1 and m are also neighbouring. Som... | #include <bits/stdc++.h>
using namespace std;
long long n, m;
long long a[200010], b[200010], l, r, ans;
inline void init() {
int it = 1;
for (register int i = 2; i <= n; i++)
if (a[i + 1] - a[i] > a[it + 1] - a[it]) it = i;
r = a[it + 1] - a[it] - 1;
for (register int i = 1; i <= n; i++) b[i] = a[i + it];
... |
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.
Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions.
1. Spells of... | """
ref: http://codeforces.com/blog/entry/48397
At first, observe that if we'll take the i-th potion of the first type and
the j-th potion of the second type, then we can prepare all the potions in
ai*(n-cj) seconds. So, we have to minimize this number.
Let's iterate over what potion of the first type we'll use. Then ... |
On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others.
Seating in the class looks like a rectangle, where n rows with m pupils in each.
The teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of t... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
long long b[105][105] = {0};
int main() {
long long n, m, k, x, y, mx = 0, mn = INF, ans;
scanf("%lld%lld%lld%lld%lld", &n, &m, &k, &x, &y);
if (n == 1) {
mx = k / m + (k % m != 0);
mn = k / m;
ans = mn + (k % m >= y);
print... |
The year of 2012 is coming...
According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us... | #include <bits/stdc++.h>
using namespace std;
long long marray[8];
pair<long long, long long> p;
long long n1, n2, n3;
long long mat[8][8];
void recurse(long long ind) {
if (ind > 7) {
vector<long long> v[4];
for (long long i = 1; i <= 7; i++) {
if (marray[i] == 1) {
v[marray[i]].push_back(i);
... |
The plans for HC2 are rather far-fetched: we are just over 500 000 days away from HC2 3387, for example, and accordingly we are planning to have a couple hundred thousand problems in that edition (we hope that programming contests will become wildly more popular). The marmots need to get to work, and they could use a g... | #include <bits/stdc++.h>
int a[500000], b[500000], n;
std::priority_queue<std::pair<long long, int> > q;
inline std::pair<long long, int> solve(int c) {
std::pair<long long, int> ans = {0, 0};
while (!q.empty()) q.pop();
for (int i = 0; i < n; i++) {
q.push({-a[i], 0});
int first = b[i] - c;
std::pair... |
You are given a connected weighted graph with n vertices and m edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id i. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change the oth... | #include <bits/stdc++.h>
using namespace std;
const int Maxn = 2e5 + 5;
const int INF = 1e9 + 5;
class edge {
public:
int u, v, c, id;
void read(int i) {
scanf("%d%d%d", &u, &v, &c);
id = i;
}
bool operator<(const edge& o) const { return c < o.c; }
};
int n, m;
edge e[Maxn];
int ans[Maxn];
int pa[Maxn]... |
Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.
On the sides of t... | #include <bits/stdc++.h>
using namespace std;
pair<int, pair<int, int> > dance[100005];
pair<int, pair<int, int> > event[100005];
int finish[100005];
vector<pair<int, int> > x, y;
vector<int> ini;
int main() {
int n, w, h;
cin >> n >> w >> h;
for (int i = 1; i <= n; i++) {
int tipe, p, t;
cin >> tipe >> p... |
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.
An integer greater than 1 is composite, if it is not prime, i.e. if... | t = int(input())
for i in range(t):
n = int(input())
if n in [1, 2, 3, 5, 7, 11]:
print(-1)
else:
print((n // 4) - (n % 2))
|
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.
For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.
For given n find out to which integer will Vasy... | n=int(input())
if(n%10==0):
print(n)
elif(n%10>5):
print(n+(10-(n%10)))
else:
print(n-(n%10))
|
We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer.
Input
A single line with a positive integer k (1 ≤ k ≤ 10 000).
Output
A single number, denoting the k-th smallest perfect integer.... | rpta = []
def solve(pos, sum, arr):
# if len(rpta) > 30:
# return
# # print(sum)
if sum > 10 or pos >= 9:
return
else:
if sum == 10:
# print(sum, arr)
rpta.append(arr)
inicio = 0 if pos > 0 else 1
for i in range(inicio, min(10,10-sum+1) )... |
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.
Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the... | n = int(input())
a = list(map(int, input().split()))
res = 0
for i in range(n):
if a[i] > 0:
res += a[i]
else:
res -= a[i]
print(res) |
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.*;
import java.util.*;
public class D2{
class node{
int num;
long dist;
public node(int a,long b){
num = a;
dist = b;
}
}
private BufferedReader in;
private StringT... |
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.
Both participants communicated to each other a set ... | #include <bits/stdc++.h>
using namespace std;
int a[50];
int b[50];
int biao;
int shu;
map<int, int> shuji;
map<int, int> ji;
map<int, int> duia, duib;
void check(int ta, int ta1) {
if (biao == -1) return;
ji[a[ta * 2 - 1]] = 1;
ji[a[ta * 2]] = 1;
if (ji[b[ta1 * 2]] == 1 && ji[b[ta1 * 2 - 1]] == 1) {
ji[a[t... |
Given N numbers and M queries, for each query Mi, find the sum of two distinct
numbers closest to the query number, if more than one such sum exists print the smallest one.
Input:
First line contains the value of N and M
Second line contains N integers separated by a space
In each of the M lines contains the query n... | n,k=(int(i) for i in raw_input().split())
l=[int(i) for i in raw_input().split()]
l.sort()
for kkk in range(0,k):
q=input()
i=0
j=n-1
ans=99999999
soln=0
while i<j:
s=l[i]+l[j]
if s>q:
j-=1
elif s<q:
i+=1
else:
soln=q
... |
Valentine week has started and Chotu wants to impress his crush. On this rose day Chotu plans to give his crush a bouquet of roses. Chotu visits a rose shop which has N number of roses and each rose has a certain love factor. Now Chotu wants to make a bouquet with maximum number of roses. As Chotu’s crush is very selec... | t = int(raw_input())
for i in range(t):
s = int(input())
num1 = set(map(int, raw_input().split()))
num = list(num1)
res = list()
c = 0
for j in range(len(num)):
if c == 0:
temp = max(num)
if temp not in res:
res.append(temp)
num.rem... |
Valentina had a birthday recently.
She got a special piano from parents.
They told her about the piano melodies and the connection with the mathematical sequences.
She got amazed and started to use piano keys to create her own musical sequences.
The piano has m keys, numbered 0 through m-1.
Valentina has already hit... | for x in range(input()):
line = raw_input().split()
n,m,z = map(int, line)
l = raw_input().split()
arr = map(int, l)
ans = 0
tp=-1
for i in range(n-1,-1,-1):
tp*=-1
ans+= (tp)*arr[i]
arr.append(ans)
if n%2==1:
arr+=arr
else:
arr+=[-p for p in arr]
print arr[z%(2*(n+1))]%m |
At the annual meeting of Board of Directors of Biana Inc, every one starts shaking hands with everyone else in the room. Given the fact that any two persons shake hand exactly once, Can you tell the total count of handshakes?
Input Format
The first line contains the number of test cases T, T lines follow.
Each line ... | #@author:debverine | 20-Feb-2016 | 9:32:50 am
for _ in range(int(input())):
n=long(input())
print (long((n-1)*n/2)) |
Raju is very much interested in winning money through lotteries.
Lottery Association is organising lottery matches quite frequently.
A lottery match begins at certain time and ends at a certain time. Raju can buy ticket of certain match if he wants to bet in that match.
But according to Lottery Association, Raju can ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
numCases=int(raw_input())
for iCase in xrange(numCases):
numMatches=int(raw_input())
matches=[]
for i in xrange(numMatches):
st,et,wp=map(int, raw_input().split())
matches... |
Solve The Mystery
Input:
First line contains T - number of test cases.
Following T lines each contains a string of characters in the range [a-z] only
Output:
Print a numeric string for each test case.
Constraints:
1 ≤ T ≤ 100
1 ≤ Length of String ≤ 100
SAMPLE INPUT
10
key
to
control
nine
tails
is
in
your
hand... | a={'a':2,'b':2,'c':2,'d':3,'e':3,'f':3,'g':4,'h':4,'i':4,'j':5,'k':5,'l':5,'m':6,'n':6,'o':6,'p':7,'q':7,'r':7,'s':7,'t':8,'u':8,'v':8,'w':9,'x':9,'y':9,'z':9}
t=input()
for _ in range(t):
s=str(raw_input())
l=len(s)
ans=''
for i in range(l):
ans=ans+str(a[s[i]])
print ans |
Apples and Oranges. You thought this question was gone when you passed class 6th. WELL YOU ARE WRONG. It's back.
See we have n apples and m oranges. You need to put these apples and oranges into some boxes. Though we've put some terms&conditions with a bright *
1. Number of apples should be same in each box.
2. Numb... | num1,num2=map(int,raw_input().split())
d,b=num1,num2
while d>0:
r=b%d
b=d
d=r
print str(num1/b) + " " + str(num2/b) |
Statement: Security is the major factor, which is prohibiting hackers letting into bank accounts online. But still, we have breached 2nd level security of SBIS bank and a final level is kept for you. Your task is simple, we are receiving an integer token every time we try to send an authorization request. After analysi... | t=input()
for _ in range(t):
a=map(list,raw_input().split())
a=a[0]
z=len(a)
b=[]
for i in range(z):
if a[i]=='2':
b.append('cde')
q=1
if a[i]=='6':
b.append('b3')
if a[i]=='7':
b.append('acf')
if a[i]=='9':
b.append ('c6a')
#print b
if len(b)==0:
print ' '
else:
print ''.join(b) |
Pati's girlfriend dumped him because he couldn't even solve a simple string puzzle.
Puzzle is, given a string of lowercase alphabets and you are supposed to check whether the frequency of the most frequent character is even or not.
Even after being dumped because of this puzzle, Pati is quite confident that it is im... | t=int(raw_input())
for x in range(t):
n=int(raw_input())
s=raw_input()
ar=[]
for y in s:
ar.append(y)
l=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
c=[]
for z in ar:
if z in l:
l.remove(z)
c.append(ar.count(z))
if max(c)%2==0:
prin... |
Alice and Bob text each other everyday. Bob, tired of writing long messages has come up with a way to reduce their size.
Alice and Bob are both fluent in 2 languages, L1 and L2. A language consists of a collection of
distinct words, where each word consists of lowercase letters in the english alphabet. Each word in
L1 ... | d=dict()
n,m=ms=map(int,raw_input().split())
for i in xrange(m):
s=raw_input().split()
d[s[0]]=s[1]
s=raw_input().split()
for i in s:
if len(i)>len(d[i]):
print d[i],
else:
print i, |
Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S zero or more times:
* Remove the two characters at the beginning of S, erase one of them, and reinsert the other somewhere in S. This operation can be applied only whe... | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int N=310,mod=998244353;
int n,f[N][N][N],g[N][N][N],C[N*2][N*2];
char s[N];
void add(int &x,int y){x+=y;x>=mod?x-=mod:0;}
int main(){
// freopen("a.in","r",stdin);
scanf("%s",s);n=strlen(s);
g[n][0][0]=1;
for(int i=0;i<... |
There are N people living on a number line.
The i-th person lives at coordinate X_i.
You are going to hold a meeting that all N people have to attend.
The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to atte... | import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
String[] S = sc.nextLine().split(" ");
int[] nums = new int[N];
int sum = 0;
for(int i = 0; i < N; i++){
nums[i] = Integer.parseIn... |
Given is a directed graph G with N vertices and M edges.
The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.
It is guaranteed that the graph contains no self-loops or multiple edges.
Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree a... | import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
n,m=map(int,input().split())
E=[[] for _ in range(n)]
for _ in range(m):
a,b=map(lambda x:int(x)-1,input().split())
E[a].append(b)
# bfs
def bfs(sv):
... |
We have N ID cards, and there are M gates.
We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.
How many of the ID cards allow us to pass all the gates alone?
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* ... | #include <bits/stdc++.h>
using namespace std;
int main(){
int N, M; cin >> N >> M;
int low = -1, high = N, L, R;
while(cin >> L >> R){
low = max(low, L);
high = min(high,R);
}
cout << max(high - low + 1, 0) << endl;
} |
Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:
* The sum of the digits in base ten is a multiple of D.
Constraints
* All values in input are integers.
* 1 \leq K < 10^{10000}
* 1 \leq D \leq 100
Input
Input is given from Standard Input in the following ... | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class Main {
private final static InputReader inputReader = new InputReader(System.in);
private final s... |
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.
The shop sells N kinds of cakes.
Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.
Th... | #include<bits/stdc++.h>
using namespace std;
using ll = long long;
ll
a[]={1,1,1,1,-1,-1,-1,-1},
b[]={1,1,-1,-1,1,1,-1,-1},
c[]={1,-1,1,-1,1,-1,1,-1};
struct xyz{ll x,y,z;};
ll I;
bool cmp(xyz x,xyz y)
{
ll A = a[I]*x.x+b[I]*x.y+c[I]*x.z;
ll B = a[I]*y.x+b[I]*y.y+c[I]*y.z;
return A > B;
}
int main()
{
ll n,m;
c... |
You are given a string S consisting of `0` and `1`. Find the maximum integer K not greater than |S| such that we can turn all the characters of S into `0` by repeating the following operation some number of times.
* Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfi... | #include<bits/stdc++.h>
using namespace std;
int main(){
string s;cin >> s;
int n=s.size();
int ans=1e7;
for(int i=0;i<n-1;i++){
if(s[i]!=s[i+1]){
ans=min(ans,max(i+1,n-i-1));
}
}
if(ans==1e7){
ans=n;
}
cout << ans << endl;
} |
In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.
There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island a_i and Island b_i.
Cat Snuk... | n,m = input().split()
n = int(n)
m = int(m)
l = [[] for i in range(n)]
for i in range(m):
a,b = input().split()
a = int(a)
b = int(b)
l[a-1].append(b-1)
l[b-1].append(a-1)
f = False
for i in l[0]:
for j in l[i]:
if j == n-1:
f = True
break
if f:
print("POSSIB... |
Alice and Bob are playing One Card Poker.
One Card Poker is a two-player game using playing cards.
Each card in this game shows an integer between `1` and `13`, inclusive.
The strength of a card is determined by the number written on it, as follows:
Weak `2` < `3` < `4` < `5` < `6` < `7` < `8` < `9` < `10` < `11` < `... | a,b=map(int,input().split())
a=(a-2)%13
b=(b-2)%13
if a<b:print('Bob')
elif a>b:print('Alice')
else:print('Draw') |
There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.
Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from t... | #include <bits/stdc++.h>
int n, a, b, x, y;
std::string s;
int main() {
std::cin >> n >> a >> b >> s;
x = 0;
y = 0;
for (int i = 0; i < n; i++) {
if (s[i] == 'a' && x < (a+b)) {
std::cout << "Yes" << std::endl;
x++;
}
else if (s[i] == 'b' && x < (a+b) && y < b) {
std::cout << "Ye... |
There is one card each with the numbers from "1" to "10", for a total of 10 cards. This card has numbers on the front and nothing on the back. Using this card, you and your opponent will play the game according to the following rules.
1. You and your opponent are dealt a total of two cards, one face up and one back up... | #include <iostream>
using namespace std;
int main() {
int c1, c2, c3;
while (cin >> c1) {
cin >> c2 >> c3;
int hand = c1 + c2;
int count = 0;
for (int i = 1; i <= 10; ++i) {
if (i == c1 || i == c2 || i == c3) continue;
if (hand + i <= 20) ++count;
}
//cout << 1.0f*count / 7 << endl;
if (1.0f*... |
Dr. Sato, a botanist, invented a number of special fertilizers for seedlings. When you give the fertilizer to the seedlings, the size of the seedlings changes in a blink of an eye. However, it was found that fertilizer has the following side effects.
* The size of the seedlings does not change with the fertilizer give... | import java.util.Scanner;
public class Main {
int n,m;
double table[][];
double memo[][];
public static void main(String[] args) {
new Main().run();
}
void run(){
Scanner sc=new Scanner(System.in);
while(true){
n=sc.nextInt();
m=sc.nextInt();
if(n+m==0) break;
table=new double[n][n];
memo=n... |
Ekiden competitions are held every year in Aizukuni. The country of Aiz is dotted with N towns, each numbered from 1 to N. Several towns are connected by roads that allow them to come and go directly to each other. You can also follow several roads between any town. The course of the tournament is decided as follows.
... | #include<bits/stdc++.h>
using namespace std;
#define INF 1000000007
typedef pair<int, int> P;
vector<P> sg;
vector<P> edge[1501];
int leng[1501][1501], f[1501][1501], flg[1501];
vector<int> fl;
int main(void){
int n, r;
cin >> n >> r;
// cout << n << endl;
for(int i = 0; i < r; i++){
int a, b, c;
cin >> a >> b >... |
problem
JOI took six subjects: physics, chemistry, biology, earth science, history, and geography. Each test was scored on a 100-point scale.
JOI chooses 3 subjects from 4 subjects of physics, chemistry, biology, and earth science, and 1 subject from 2 subjects of history and geography.
When choosing a subject so th... | lst=[]
for i in range(6):
n=int(input())
lst.append(n)
lst1=lst[0:4]
lst2=lst[4:6]
lst1.sort(reverse=True)
lst3=lst1[0:3]
a=sum(lst3)
b=max(lst2)
print(a+b)
|
Seiji Hayashi had been a professor of the Nisshinkan Samurai School in the domain of Aizu for a long time in the 18th century. In order to reward him for his meritorious career in education, Katanobu Matsudaira, the lord of the domain of Aizu, had decided to grant him a rectangular estate within a large field in the Ai... | #include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(n);++i)
using namespace std;
int n;
void proc(){
int w,h;
int x,y;
int data[500][500];
cin>>w>>h;
memset(data,0,sizeof(data));
rep(i,n){
cin>>x>>y;
data[--x][--y]=1;
}
cin>>x>>y;
rep(i,w){
rep(j,h){
if(i>=1)data[i][j]+=data[i-1... |
One of the questions children often ask is "How many stars are there in the sky?" Under ideal conditions, even with the naked eye, nearly eight thousands are observable in the northern hemisphere. With a decent telescope, you may find many more, but, as the sight field will be limited, you may find much less at a time.... | #include<bits/stdc++.h>
using namespace std;
int n,m;
double x[1000],y[1000],z[1000];
double tx,ty,tz,ar;
double dot(double ax,double ay,double az,
double bx,double by,double bz){
return ax*bx+ay*by+az*bz;
}
int calc(double sx,double sy,double sz){
double S=sqrt(sx*sx+sy*sy+sz*sz);
double T=sqrt(tx*... |
Colorful Tree
A tree structure with some colors associated with its vertices and a sequence of commands on it are given. A command is either an update operation or a query on the tree. Each of the update operations changes the color of a specified vertex, without changing the tree structure. Each of the queries asks t... | #include <bits/stdc++.h>
using namespace std;
using graph = vector<vector<int>>;
class lowest_common_ancestor {
using pii = pair<int, int>;
vector<int> depth, par, heavy, head;
int dfs(int v, int prev, const graph& G) {
par[v] = prev;
depth[v] = prev != -1 ? depth[prev] + 1 : 0;
int ma = 0, cnt = 1;
for (au... |
Income Inequality
We often compute the average as the first step in processing statistical data. Yes, the average is a good tendency measure of data, but it is not always the best. In some cases, the average may hinder the understanding of the data.
For example, consider the national income of a country. As the term ... | #include <iostream>
using namespace std;
int main(void){
int n, a[100000], sum; //sumはn人の平均値の合計
int num; //numは平均値以下の所得者数
while(true){
cin >> n;
if(n == 0) break;
sum = 0;
num = 0;
for(int i = 0; i < n; i++){
cin >> a[i];
sum ... |
You’ve just entered a Japanese-style pub, or an izakaya in Japanese, for a drinking party (called nomi-kai) with your dear friends.
Now you are to make orders for glasses of hard and soft drink as requested by the participants. But unfortunately, most staffs in typical izakayas are part-time workers; they are not used... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include ... |
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to train your eyesight and concentration by observing many stars shining in the night sky. Rabbits can record the characteristics of stars with their own sense.
Rabbi... | #include<cstdio>
#include<vector>
#include<utility>
#include<queue>
#include<algorithm>
using namespace std;
typedef pair<int,long long> P;
const long long mod=1000000009;
vector<int> G[100100];
bool used[100100];
int N,M;
int dis[100100];
int base[100100];
int bfs(int v){
queue<int> que;
dis[v]=0;
base[v]=v;
... |
You are given one polygonal line, which is a collection of line segments. Your task is to calculate the sum of areas enclosed by the polygonal line.
A point is defined to be "enclosed" if and only if the point is unreachable without crossing at least one line segment from the point at infinity.
Input
The first lin... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-7)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
#define equals(a,b) (fabs((a)-(b)) < EPS)
using namespace std;
class Point{
public:
dou... |
Ikta, who hates to lose, has recently been enthusiastic about playing games using the Go board. However, neither Go nor Gomoku can beat my friends at all, so I decided to give a special training to the lesser-known game Phutball.
This game is a difficult game, so I decided to give special training so that I could win ... | // g++ -std=c++11 a.cpp
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<random>
#include<cstring>
#include<queue>
#include<stack>
#include<bitset>
#include<cstdio>
#include<sstream>
#include<iomanip>
#include<assert.h>
#inc... |
E: How To Make Stars-
story
Kitano Kisaka Gakuin 1st grade stardust bell! I like the stars of the bells! At night, I'm always secretly watching the stars on the roof of the school with my childhood friend Hanayo-chin! But unfortunately the weather today is rainy ... With this, you can't see the stars! What should I d... | #include <bits/stdc++.h>
#define show(x) cerr << #x << " = " << x << endl
using namespace std;
using ld = long double;
int main()
{
auto out = [](const ld y, const ld x, const ld sp) {
const ld PI = 3.141592653589793;
const ld F = 0.22451398828979266;
const ld r1 = sqrt(sp / F / 5);
... |
problem
Given the lengths of $ 2 $ sides that are not the hypotenuse of a right triangle, $ A $ and $ B $. The side of length $ A $ overlaps the $ x $ axis, and the side of length $ B $ overlaps the $ y $ axis.
Do the following:
1. Rotate the triangle around the $ x $ axis.
2. Rotate the shape created by performing ... | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;
template<typename A,typename B>inline ... |
Problem
Given a sequence $ X $ of length $ N $. In the initial state, all $ X $ elements are $ 0 $. In addition, a pair of $ M $ integers $ (A_i, B_i) $ is given. Do the following for each pair and output the final sequence $ X $.
* For the integer $ j $$ (1 \ le j \ le N) $, add the remainder of $ (A_i + j) $ divide... | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define int ll
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb emplace_back
#define INF (1e9+1)
signed main(){
int n,m;
cin>>n>>m;
vector<int> a(m),b(m);
rep(i,m)cin... |
Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.
* insert $k$: Insert a node containing $k$ as key into $T$.
* find $k$: Report whether $T$ has a node containing $k$.
* print: Print the keys of the binary search tree by inorde... | class Node(object):
root = None
def __init__(self, key, parent=None, left=None, right=None):
self.key = key
self.parent = parent
self.left = left
self.right = right
self.height = None
@classmethod
def insert(cls, z):
y = None
x = cls.root
... |
For a dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations:
* pushBack($x$): add element $x$ at the end of $A$
* randomAccess($p$):print element $a_p$
* popBack(): delete the last element of $A$
$A$ is a 0-origin array and it is empty in the initial state.
Constraints... | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
int q; cin >> q;
while (q--) {
int com; cin >> com;
if (com == 0) {
int x; cin >> x; v.push_back(x);
} else if (com == 1) {
int p; cin >> p; cout << v[... |
Many years ago there was a kingdom called 'sentence', which comprises of two groups namely strings and integers. Strings consists of all the characters and alphabets(both capital and small) whereas the integers consists of all
the kinds of numbers. 'A' was the leader of strings and was prefer over '0' the leader of in... | for ii in range(input()):
string=raw_input()
ans=""
k=len(string)
for ii in range(k):
if not string[ii].isdigit():
ans=ans+string[ii]
print ans |
Shil has a number X.He challenges you to find minimum positive number K such that F(K) is equal to X.
F(x) is defined as 1^2^3^....x. ^ denotes the bitwise Xor operation
Input
First line of input will consists of total number of test cases T.Next T lines contains a number X.
Output
For each test case , outpu... | def main():
for _ in xrange(input()):
X = input()
if X == 0:
print 3
else:
if X == 1:
print 1
else:
if X % 4 == 0:
print X
elif (X - 3) % 4 == 0:
print X - 1
... |
After a long period of relaxation Alice and Bob decided to play a game.
This time of course not a number game. The rules of the game are as follows:
There is a vehicle situated at the point (m, n) of a rectangular grid.
Only one corner of the rectangular grid is defined, i.e. the left-top point (0, 0),
which is also kn... | a=[[0 for i in xrange(1001)] for y in range(1001)]
def row(i,j):
for k in xrange(1001-j-1):
a[i][k+j+1]=2
def col(i,j):
for k in xrange(1001-i-1):
a[k+i+1][j]=2
def diag(i,j):
i=i+1
j=j+1
while(i<1001)and(j<1001):
a[i][j]=2
i=i+1
j=j+1
def main():
tes... |
You are given integers N,K and M and operation F. Operation F is defined for an integer as follows:
F:
for i from 1 to M inclusive, do
if N is a multiple of K,
divide N by K
else,
multiply N by K
print N
Perform the operation F on N.
Input
The first line contains a single integer T the number of test cases.
... | def fun(n,k,m):
if k==1:
return n
while m>0 and n%k==0:
m = m-1
n = n/k
if m==0:
return n
if m%2==0:
return n
return n*k
t= int(raw_input())
for i in range(t):
n,k,m= map(int,raw_input().split())
print fun(n,k,m) |
You had an array of integer numbers. You also had a beautiful operations called "Copy-Paste" which allowed you to copy any contiguous subsequence of your array and paste it in any position of your array. For example, if you have array [1, 2, 3, 4, 5] and copy it's subsequence from the second to the fourth element and p... | t=input()
for _ in xrange(t):
raw_input()
print len(set(raw_input().split())) |
Chef is going to participate in a new quiz show: "Who dares to be a millionaire?"
According to the rules of the game, contestants must answer N questions. The quiz being famous for its difficulty, each question has 26 candidate answers, but only one of which is correct. Answers are denoted by capital Latin letters from... | test = input()
for i in xrange(test):
n = input()
ans = raw_input()
chef = raw_input()
W = map(int, raw_input().split())
correct = 0
for i in range(n):
if(ans[i] == chef[i]):
correct += 1
if(correct != n):
print max(W[:correct+1])
else:
print W[n] |
Gerald is positioned in an old castle which consists of n halls connected with n - 1 corridors. It is exactly one way to go from any hall to any other one. Thus, the graph is a tree. Initially, at the moment of time 0, Gerald is positioned in hall 1. Besides, some other hall of the castle contains the treasure Gerald i... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 500000;
int n;
vector<int> G[MAXN], W[MAXN];
long long dp[MAXN], dsum[MAXN], son[MAXN];
int indice[MAXN];
bool cmp(int u, int v) { return dsum[u] * son[v] < dsum[v] * son[u]; }
void dfs(int u, int fa) {
dsum[u] = dp[u] = son[u] = 0;
int cnt = 0;
for (... |
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, …, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As... | arr_len = int(input())
a = [0] + [int(x) for x in input().split(" ")]
x = [0] * arr_len
res = []
for i in range(1, arr_len + 1):
x[i-1] = a[i]-a[i-1]
def ok(k, x ,a):
for i in range(0, arr_len):
tmp = x[i%k] + a[i]
if tmp != a[i + 1]:
return False
return True
for k in ... |
Let's denote (yet again) the sequence of Fibonacci strings:
F(0) = 0, F(1) = 1, F(i) = F(i - 2) + F(i - 1), where the plus sign denotes the concatenation of two strings.
Let's denote the lexicographically sorted sequence of suffixes of string F(i) as A(F(i)). For example, F(4) is 01101, and A(F(4)) is the following... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 0x3f3f3f3f3f3f3f3f;
const int mxn = 201, w = 3;
long long n, m, k;
long long a[mxn][mxn], first[mxn][mxn], tr[mxn][w];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> k >> m;
string second;
for (int i = 1; i <= m; i++)
for (... |
You're given a tree consisting of n nodes. Every node u has a weight a_u. You want to choose an integer k (1 ≤ k ≤ n) and then choose k connected components of nodes that don't overlap (i.e every node is in at most 1 component). Let the set of nodes you chose be s. You want to maximize:
$$$\frac{∑_{u ∈ s} a_u}{k}$$$
... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
vector<int> G[maxn];
int a[maxn];
long long mx = -1e18, cnt, dp[maxn];
void dfs(int v, int fa, int flag) {
dp[v] = a[v];
for (int i = G[v].size() - 1; i >= 0; i--) {
int to = G[v][i];
if (to == fa) continue;
dfs(to, v, flag);
i... |
Vasya has a string s of length n consisting only of digits 0 and 1. Also he has an array a of length n.
Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty... | #include <bits/stdc++.h>
using namespace std;
int n;
string s;
vector<int> val;
vector<vector<vector<long long>>> memo;
long long solve(long long l, long long r, long long p) {
if (l >= r) return 0;
if (r - l == 1) return val[p];
if (memo[l][r][p] != -1) return memo[l][r][p];
long long ans = val[p] + solve(l + ... |
In this task, Nastya asked us to write a formal statement.
An array a of length n and an array k of length n-1 are given. Two types of queries should be processed:
* increase a_i by x. Then if a_{i+1} < a_i + k_i, a_{i+1} becomes exactly a_i + k_i; again, if a_{i+2} < a_{i+1} + k_{i+1}, a_{i+2} becomes exactly a_{... | import java.util.*;
import java.io.*;
import javafx.util.*;
public class DAB
{
static class Task
{
final int N = (int)1e5 + 5 ;
final long INF = (long)1e18;
long T[][] = new long[N << 2][3] , lzy[] = new long[N << 2] , a[] = new long[N] , b[] = new long[N];
long[] ac = new long[N] , acf = new long[N];
l... |
A telephone number is a sequence of exactly 11 digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro... | #include <bits/stdc++.h>
using namespace std;
long long maxi = 1000005;
long long mini = LLONG_MIN;
void fast() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
int main() {
fast();
long long n;
cin >> n;
string s;
cin >> s;
long long k = (n - 11) + 1;
long long cnt = 0;
for (long long i = 0; i ... |
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...
Your task is to print the k-th digit of this sequence.
Input
The first and only lin... | x = ''.join(str(i) for i in range(1, 5000))
k = int(input())
print(x[k-1])
|
Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size n × m cells on a map (rows of grid are numbered from 1 to n from north to south, and columns are numbered from 1 to m from west to east). After that he measured the average height of each c... | #include <bits/stdc++.h>
using namespace std;
inline long long mod(long long n, long long m) {
long long ret = n % m;
if (ret < 0) ret += m;
return ret;
}
long long gcd(long long a, long long b) { return (b == 0 ? a : gcd(b, a % b)); }
long long exp(long long a, long long b, long long m) {
if (b == 0) return 1;... |
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates.
You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:
* Move the chip i by 2 to the left or 2 to the right for free (i.e. replace... | n = int(input())
v = list(map(int, input().split()))
a = []
b = []
for x in v:
a.append(x) if x & 1 else b.append(x)
print(min(len(a), len(b)))
|
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different ki... | '''Author- Akshit Monga'''
from sys import stdin, stdout
input = stdin.readline
mod=10**9+7
t = 1
for _ in range(t):
n,m=map(int,input().split())
print(pow((pow(2,m,mod)-1),n,mod)) |
Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.
His farm is presented by a rectangle grid with r rows and c columns. Some of these cells contain rice, others are empty. k chickens are living on his farm. The number of chicken... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
import java.util.Random;
import java.util.StringTokenizer;
public class Solution{
publ... |
You are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen.
A rectangle (rectangular matrix)... | #include <bits/stdc++.h>
using namespace std;
void program();
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
program();
}
const int MX = 1e6;
int n, a[MX];
map<int, int> cnt;
priority_queue<pair<int, int>> pq;
set<pair<int, int>> visited;
int dpMX[MX];
void program() {
cin >> n;
for (int i = in... |
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob... | #include <bits/stdc++.h>
using namespace std;
int a[10001] = {0};
int b[10001] = {0};
int s = 0;
int sn = 0;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) {
cin >> b[i];
if (b[i] > a[i])
s++;
else if (b[i] < a[i])
sn++;
}
if (sn ... |
A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward").
You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the lis... | #include <bits/stdc++.h>
using namespace std;
char A[102];
int M[102][205][3][52];
int dp(int i, int x, int d, int n) {
if (n < 0) return 0;
if (!A[i] && n == 0) return abs(x - 102);
if (!A[i]) return 0;
int &r = M[i][x][d == 1][n];
if (r == -1) {
if (A[i] == 'F') {
r = max(dp(i + 1, x + d, d, n),
... |
Johnny has a new toy. As you may guess, it is a little bit extraordinary. The toy is a permutation P of numbers from 1 to n, written in one row next to each other.
For each i from 1 to n - 1 between P_i and P_{i + 1} there is a weight W_i written, and those weights form a permutation of numbers from 1 to n - 1. There... | #include <bits/stdc++.h>
using namespace std;
template <class T>
istream& operator>>(istream& is, vector<T>& v) {
for (T& x : v) is >> x;
return is;
}
template <class T>
ostream& operator<<(ostream& os, const vector<T>& v) {
if (!v.empty()) {
os << v.front();
for (int i = 1; i < v.size(); ++i) os << ' ' <... |
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno... | t=int(input())
for _ in range(t):
n=int(input())
a=list(map(lambda x:int(x),input().split()))
first_nonforced_index=-1
for i in range(0,len(a)):
if a[i]!=1:
first_nonforced_index=i
break
if first_nonforced_index==-1:
if len(a)%2==0:
print("Second")... |
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.
The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N... | import java.util.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int testCases = sc.nextInt();
for (int t = 0; t < testCases; t++) {
long n = sc.nextLong();
long coun... |
A patient has been infected with an unknown disease. His body can be seen as an infinite grid of triangular cells which looks as follows:
<image>
Two cells are neighboring if they share a side. Therefore, each cell (x, y) has exactly three neighbors:
* (x+1, y)
* (x-1, y)
* (x+1, y-1) if x is even and (x-1,... | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n, x[N], y[N], i, j, tot, g[N], ccnt, F, trcnt;
int gfa(int x) { return g[x] == x ? x : g[x] = gfa(g[x]); }
bool b[505][505], cir, bb[505][505];
inline void tryuni(int x, int y) {
x = gfa(x);
y = gfa(y);
if (x != y)
g[x] = y, --ccnt;
e... |
You are given n points on a plane.
Please find the minimum sum of areas of two axis-aligned rectangles, such that each point is contained in at least one of these rectangles.
Note that the chosen rectangles can be degenerate. Rectangle contains all the points that lie inside it or on its boundary.
Input
The first ... | #include <bits/stdc++.h>
#define ALL(v) (v).begin(), (v).end()
struct Point {
int x, y;
};
Point operator-(const Point &a, const Point &b) {
return {a.x - b.x, a.y - b.y};
}
bool by_x(const Point &a, const Point &b) { return a.x < b.x; }
long long area(int a, int b) { return 1LL * a * b; }
long long det(const... |
This is the easy version of the problem. The only difference is that in this version k = 0.
There is an array a_1, a_2, …, a_n of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfe... |
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.Math.PI;
import static java.lang.Math.min;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import ... |
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to ... | #include <bits/stdc++.h>
using namespace std;
const long long DIVN = 1000000007;
int main(int argc, char const *argv[]) {
int n, m, k, calc;
long long res = 1;
cin >> n >> m >> k;
if (k == 1 || k > n)
calc = n;
else if (k < n && (!(k % 2)))
calc = 1;
else if (k < n && (k % 2))
calc = 2;
else i... |
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1... | # _
#####################################################################################################################
def minCo_growingSequenceWith(array):
sequence, prevValue = [], 0
for value in array:
n = prevValue&(prevValue^value)
prevValue = value^n
sequence.append(n)
ret... |
Vasya plays Robot Bicorn Attack.
The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string s. Vasya decided to... | #include <bits/stdc++.h>
using namespace std;
char s[35];
long long mx = -1, x, y, z, Lim = 1000000;
long long toS(int f, int l) {
long long ln = 0;
for (int i = f; i <= l; i++) {
ln *= 10;
ln += s[i] - '0';
}
return ln;
}
int main() {
scanf("%s", s);
int len = strlen(s);
for (int i = 0; i < 7; i+... |
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int mid = (m + 1) / 2;
int cnt = 0;
int ans[m + 1];
if (m % 2) {
int i = 1;
int cnt = 1;
int k = 1;
ans[k++] = mid;
while (true) {
if (cnt > m) break;
ans[k++] = mid - i;
cnt++;
if... |
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.
Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he... | p, d = input().split()
p = int(p); d = int(d)
ans = p = p + 1
i = 10
while i <= 1000000000000000000:
if p % i <= d:
ans = p - p % i
i *= 10
print(ans - 1) |
Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.
Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connecte... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const double eps = 1e-10;
const int inf = 2000000000;
const long long int MOD = 1000000007;
int MOD1 = 1000000007;
int MOD2 = 1000000009;
inline bool checkBit(long long int n, long long int i) {
return n & (1LL << i);
}
inline long long int set... |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | n = input()
print n + n * n * (n - 1) / 2 - n * (n - 1) * (2 * n - 1) / 6 |
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ...
Input
The only line of the input is a string between 1 and 106 characters long.
Output
Output "Yes" or "No".
Examples
Input
HHHH
Output
Yes
Input
HQHQH
Output
No
Input
H... | #include <bits/stdc++.h>
using namespace std;
string s;
int i, j, k, l;
int q = 0, rq, rh;
int h;
int hnow;
int qnow;
int main() {
cin >> s;
for (i = 0; i < s.length(); i++)
if (s[i] == 'H')
h++;
else
q++;
q = int(sqrt(double(q) + 1e-9));
h = h / (q + 1);
l = h + q;
for (i = 0; i < l; i+... |
Smart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dre... | #include <bits/stdc++.h>
using namespace std;
const int sx[4] = {1, 0, -1, 0};
const int sy[4] = {0, 1, 0, -1};
int i, n, m, D[111000], f[111000], t[111000], p[111000], ii, fl[111000],
o[111000], q1, q2, q[111000], vn, qq, v[111000], pr[111000], ret, j,
a[111][111], c[111][111], k, x2, y2, it;
void addedge(int ... |
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i... | def main(n, m, lst):
count = 0
lst = [1] + lst
for i in range(1, len(lst)):
if lst[i] >= lst[i-1]:
count += lst[i] - lst[i-1]
else:
count += n - lst[i-1] + lst[i]
return count
n, m = [int(x) for x in input().split()]
lst = list(map(int, input().split()))
print(ma... |
Levko has an array that consists of integers: a1, a2, ... , an. But he doesn’t like this array at all.
Levko thinks that the beauty of the array a directly depends on value c(a), which can be calculated by the formula:
<image> The less value c(a) is, the more beautiful the array is.
It’s time to change the world an... | import java.io.*;
import java.util.*;
public class Main {
InputReader in; PrintWriter out;
int[] a;
void solve() {
int n = in.nextInt();
int k = in.nextInt();
a = new int[n + 1];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
a[n] = a[n - ... |
The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.
String x(i, j) contains strin... | #include <bits/stdc++.h>
using namespace std;
void IOS() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
void solve() {
string str;
cin >> str;
long long n = str.length();
vector<long long> v;
long long sum = 0;
for (long long i = 0; i < str.length(); i++) {
if (str[i] == 'b') {
i... |
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is ... | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.