input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Little Shino loves to play with numbers. She just came to know about Fibonacci Series.
Fibonacci Series is a series of number such that
Fib(1) = 0
Fib(2) = 1
Fib(x) = Fib(x-1) + Fib(x-2)\;where\;2 < x
Soon Little Shino realized that Fibonacci series grows very fast. So she just wants the sum of last 4 digits of the F... | a=[0]*20000
ar=[0]*20000
a[1]=0
a[2]=1
ar[1]=0
ar[2]=1
for i in range(3,16000): a[i]=(a[i-1]+a[i-2])%10000
for i in range(2,16000): ar[i]=(a[i]+ar[i-1])%1000000007
def fibo(n):
return (ar[n%15000] + (((n/15000)%1000000007)*ar[15000])%1000000007)%1000000007
for _ in range(input()):
l,r=map(int,raw_input().split())
pr... |
Solve the Mystery.
Input Format:
First line contains integer T denoting number of test cases.
Next T lines contains sentences, one in each line.
Output Format:
Print output of each test case on individual line.
Constraints:
1 ≤ T ≤ 100
1 ≤ length of sentence ≤ 100
Each sentence contains characters from this set {a-z... | k='qwertyuiopasdfghjklzxcvbnm'
a='abcdefghijklmnopqrstuvwxyz'
o=''
for _ in range(input()):
string=raw_input()
o=''
for i in string:
if i!=' ':
o+=k[a.index(i)]
else:
o+=' '
print o |
Prime numbers are those numbers which have only 2 factors, 1 and the number itself. For example, 3 is a prime number have factors 1 and 3 only.
Now, all the prime numbers are arranged sequentially in ascending order. i.e:- 2, 3, 5,7...and so on. Now, your task is to calculate those prime numbers which are present at a... | def primes2(limit):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [False] * ((lmtbf - s) // p ... |
What if we Unite against the Difference between ourselves ?
Welcome into the Brother-Hood town. Citizens of Brother-Hood town are feeling very happy that you came for their help. But what is the problem they have ?
There is one very crucial problem in the town now. Years ago people of town were living together , and w... | n = int(input())
e = [0]*501
for i in range(n):
m = int(input())
a = map(int,raw_input().split())
f = [0]*501
for j in a:
f[j] = 1
for j in range(501):
e[j]+=f[j]
ans = 0
for i in range(501):
if e[i]==n: ans-=i
print ans |
Bob loves sorting very much. He is always thinking of new ways to sort an array.His friend Ram gives him a challenging task.He gives Bob an array and an integer K .The challenge is to produce the lexicographical minimal array after at most K-swaps.Only consecutive pairs of elements can be swapped.Help Bob in returning ... | def main():
t = int(raw_input().strip())
while t !=0:
n, k = [int(x) for x in raw_input().split()]
arr = [int(x) for x in raw_input().split()]
i = 0
while i<n and k !=0:
temp = arr[i]
min_index = i
for j in xrange(i+1, min(k+i+1, n)):
if arr[j]<temp:
min_index = j
temp =arr[j]
... |
At HackerEarth we love play checkers and we play it a lot! However, we play a very specific kind of checkers. Our game is played on 32x32 board. If you are a programmer, you probably know why the board size is 32. Maybe we will describe details of the game in a future challenge, but for now, the only thing you have to ... | def search(s):
m = len(s)
n = len(s[0])
count = 0
mat = [[[0,0]for i in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
if s[i][j] != s[i][j-1]:
mat[i][j][0] = mat[i][j-1][0] + 1
else:
mat[i][j][0] = 1
if ... |
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.
Constraints
* 1 \leq K \leq N \leq 1000
* 1 \leq... | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
int k = Integer.parseInt(sc.next());
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = Integer.parseI... |
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.
At least how many sheets of paper does he need?
Constraints
* N is an integer.
* 1 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the a... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Double N = sc.nextDouble();
int ans = (int) Math.ceil(N/2);
System.out.println(ans);
}
}
|
Given are N points on the circumference of a circle centered at (0,0) in an xy-plane. The coordinates of the i-th point are (\cos(\frac{2\pi T_i}{L}),\sin(\frac{2\pi T_i}{L})).
Three distinct points will be chosen uniformly at random from these N points. Find the expected x- and y-coordinates of the center of the circ... | #include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int n,L;
#define Maxn 3005
#define pi acos(-1)
double T[Maxn];
double x,y;
inline void add(double rad,int cnt){
x+=cos(rad)*cnt;
y+=sin(rad)*cnt;
}
int main(){
scanf("%d%d",&n,&L);
for(register int i=0;... |
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now.
Constraints
* All values in input are integers.
* 0 \leq A, P \leq 100
Input
Input is g... | import java.util.Scanner;
class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int a,p,maxap;
a = sc.nextInt();
p = sc.nextInt();
maxap = (3*a + p) /2;
System.out.println(maxap);
}
} |
There is a set A = \\{ a_1, a_2, \ldots, a_N \\} consisting of N positive integers. Taro and Jiro will play the following game against each other.
Initially, we have a pile consisting of K stones. The two players perform the following operation alternately, starting from Taro:
* Choose an element x in A, and remove e... | n, k = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
DP = [False] * (k + 1)
for i in range(1, k+1):
DP[i] = any(not DP[i-a] for a in A if i - a >= 0)
print('First' if DP[k] else 'Second') |
There is always an integer in Takahashi's mind.
Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is `+` or `-`. When he eats `+`, the integer in his mind increases by 1; when he eats `-`, the integer in his mind decreases by 1.
The symbols Takahashi is going t... | #include<bits/stdc++.h>
using namespace std;
int main(){
char s[5];
cin >> s;
int o=0;
for(int i=0;i<4;i++){
if(s[i]=='-')----o;
o++;
}
cout << o;
}
|
You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order:
* Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of dam... | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,h;
cin>>n>>h;
int a[n],b[n];
int normal=0;//通常攻撃の最大値
for(int i=0;i<n;i++){
cin>>a[i]>>b[i];
normal=max(normal,a[i]);
}
sort(b,b+n,greater<int>());
int x=0;
while(x<n && b[x]>normal && h>0){
h-=b[x]... |
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th qu... | import java.io.*;
import java.util.*;
class Main {
static class Pair {
int to;
long w;
Pair(int t, long wt) {
to = t;
w = wt;
}
}
static long[] depth;
static ArrayList<Pair>[] v;
static boolean[] visited;
public static void main(String[] a... |
There is a square-shaped grid with N vertical rows and N horizontal columns. We will denote the square at the i-th row from the top and the j-th column from the left as (i,\ j).
Initially, each square is either white or black. The initial color of the grid is given to you as characters a_{ij}, arranged in a square sha... | def main():
n = int(input())
grid = [input() for _ in [0]*n]
for i in grid:
if "#" in i:
break
else:
print(-1)
return
ans = 10**20
# i行目に何個黒があるか
black_cnt = [0]*n
# i列目に黒が一つでもあればTrue
exist = [False]*n
for i in range(n):
for j in range(n... |
One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 ≤ i ≤ N!) contains the i-th permutation in the lexicographical order.
Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgo... | #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <iomanip>
#include <utility>
#include <tuple>
#include <functional>
#include <bitset>
#include <cassert>
#include <complex>
#include <stdio.h>
#include <... |
n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1
Is called the factorial of n. For example, the factorial of 12
12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600
And there are two consecutive 0s at the end.
Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of... | #include <iostream>
int main(void){
int n,c;
while (true){
std::cin>>n;
if (n==0) break;
c=0;
for (;0<n;n/=5,c+=n);
std::cout<<c<<"\n";
}
} |
Beakers of various capacities are given. First, choose one of the largest beakers and pour it through the faucet until it is full. Next, transfer the water from the beaker to another beaker according to the following rules.
* All water in the beaker must be transferred to another beaker without leaving. However, if it... | import java.util.*;
import java.util.Map.Entry;
import java.math.*;
import java.awt.geom.*;
import java.io.*;
public class Main {
static boolean[] use;
static boolean[] used;
static boolean[] notEmpty;
static int[] beaker;
public static void main(String[] args) {
Scanner sc = new Scanner(Syste... |
White Tiger University holds a programming contest every year. The contest starts with a score of 0 for all teams, and points are added according to the answer status. In this contest, rankings will be made in descending order of score. When the total number of teams is N, each team is assigned a number from 1 to N. If... | #include <bits/stdc++.h>
using namespace std;
#define int long long
using ll=long long;
using vi=vector<int>;
using pii=pair<int,int>;
#define ALL(c) begin(c),end(c)
#define RALL(c) rbegin(c),rend(c)
#define ITR(i,b,e) for(auto i=(b);i!=(e);++i)
#define FORE(x,c) for(auto &x:c)
#define REPF(i,a,n) for(int i=a,i##len=(i... |
Tower of JOIOI
The JOIOI Tower is a game that uses a disk to be played by one person.
This game is played using several disks with the letters J, O, and I written on them. The discs have different diameters, and at the start of the game, these discs are stacked from bottom to top in descending order of diameter. You ... | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int n;
string s;
bool check(int x){
int l, r;
static bool isUseI[1000001], isUseO[1000001];
int cntI = 0;
for( r = 0; r < n; r++ ){ isUseI[r] = false; isUseO[r] = false; }
for( r = n-1; r >= 0; r-- ){
if( cntI == x ){
break;... |
Ever since Mr. Ikra became the chief manager of his office, he has had little time for his favorites, programming and debugging. So he wants to check programs in trains to and from his office with program lists. He has wished for the tool that prints source programs as multi-column lists so that each column just fits i... | # 2 "1115.cpp"
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <complex>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include... |
The deadline of Prof. Hachioji’s assignment is tomorrow. To complete the task, students have to copy pages of many reference books in the library.
All the reference books are in a storeroom and only the librarian is allowed to enter it. To obtain a copy of a reference book’s page, a student should ask the librarian to... | import java.util.*;
import static java.lang.Math.*;
public class Main {
final Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
new Main().init();
}
void init(){
new AOJ1258();
}
class AOJ1258{
final int INF=Integer.MAX_VALUE/4;
AOJ1258(){
while(true){
int M=sc.nextInt(... |
Arithmetic Progressions
An arithmetic progression is a sequence of numbers $a_1, a_2, ..., a_k$ where the difference of consecutive members $a_{i+1} - a_i$ is a constant ($1 \leq i \leq k-1$). For example, the sequence 5, 8, 11, 14, 17 is an arithmetic progression of length 5 with the common difference 3.
In this pro... | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define REP(i, n) for (int i = 0; i < (int)(n); ++i)
template <class T>
bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return 1;
}
return 0;
}
signed main() {
int n;
cin >> n;
vector<int> a(n);
REP(i, n... |
Taro's Shopping
Mammy decided to give Taro his first shopping experience. Mammy tells him to choose any two items he wants from those listed in the shopping catalogue, but Taro cannot decide which two, as all the items look attractive. Thus he plans to buy the pair of two items with the highest price sum, not exceedin... | #include <bits/stdc++.h>
#define int long long
#define double long double
#define INF 1e18
using namespace std;
int a[1000];
signed main() {
int N, M;
while(cin>>N>>M,N+M!=0) {
for (int i = 0; i < N; i++) cin >> a[i];
int ans = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
... |
Indigo Real-estate Company is now planning to develop a new housing complex. The entire complex is a square, all of whose edges are equally a meters. The complex contains n subdivided blocks, each of which is a b-meter square. Here both a and b are positive integers.
However the project is facing a big problem. In thi... | #include<algorithm>
#include<iostream>
#include<vector>
#include<set>
#include<cassert>
#include<cmath>
using namespace std;
typedef long long lint;
typedef vector<int>vi;
typedef pair<int,int>pii;
typedef pair<lint,lint>pll;
typedef pair<pll,lint>pplll;
#define rep(i,n)for(int i=0;i<(int)(n);++i)
pll fundamental_unit... |
Problem C: Seishun 18 Kippu
A student at R University, sirokurostone, was about to attend a training camp at Atsu University. Other members plan to use the Shinkansen, but sirokurostone was going to use the Seishun 18 Ticket. Similarly, a person who likes 2D with a youth 18 ticket was also trying to participate in the... | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
using namespace std;
/* c... |
Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station.... | #include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
#... |
Problem Statement
You have just transferred to another world, and got a map of this world. There are several countries in this world. Each country has a connected territory, which is drawn on the map as a simple polygon consisting of its border segments in the $2$-dimensional plane.
You are strange to this world, so ... | #pragma GCC optimize "Ofast"
#define X first
#define Y second
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
constexpr int N = 35;
int n, deg[N], nei[N], col[N];
vector<PII> polys[N];
vector<int> adj[N];
int cnt[N][3];
inline int cross(const PII &p0, const PII &p1)... |
Problem statement
Here are N mysteriously shaped vases. The i-th jar is a shape in which K_i right-sided cylinders are vertically connected in order from the bottom. The order in which they are connected cannot be changed. Mr. A has a volume of water of M. Pour this water into each jar in any amount you like. It does ... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
int n,m;
int k[200], s[200... |
A: IP Address (Internet Protocol Address)
problem
Since one number string is given, find the number of valid delimiters for IPv4 IP addresses. However, the effective delimiters for IPv4 IP addresses are as follows.
* The sequence of numbers is divided into four, and each of the separated columns satisfies all of the... | #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"
... |
Problem
Ai-chan has a tree $ T $ consisting of $ N $ vertices and $ N-1 $ edges. Each vertex has a number from $ 1 $ to $ N $ and a positive integer weight.
Answer the following $ Q $ queries in order.
* $ 1 \ le a_i, b_i \ le N $ ($ a_i \ ne b_i $) is given, so you can remove the vertices on the $ a_i $-$ b_i $ pat... | #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 ... |
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. I... | #include <iostream>
using namespace std;
int n;
int A[100000];
int main()
{
cin>>n;
for(int i=0;i<n;i++)cin>>A[i];
int x=A[n-1];
int j=A[0]<x?1:0;
for(int i=1;i<n-1;i++)
{
if (A[i]<=x)
{
int aj=A[j];
A[j]=A[i];
A[i]=aj;
j++;
}
}
A[n-1]=A[j];
A[j]=x;
for (int i=0;i<j;i++)
{
if (i) cout <<... |
Given a non-negative decimal integer $x$, convert it to binary representation $b$ of 32 bits. Then, print the result of the following operations to $b$ respecitvely.
* Inversion: change the state of each bit to the opposite state
* Logical left shift: shift left by 1
* Logical right shift: shift right by 1
Constraint... | //#define NDEBUG
#include "bits/stdc++.h"
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <random>
#ifdef _MSC_VER
#include <ppl.h>
//#include <boost/multiprecision/cpp_dec_float.hpp>
//#include <boost/multiprecision/cpp_int.hpp>
//#include <boost/ration... |
Mike likes strings. He is also interested in algorithms. A few days ago he discovered for himself a very nice problem:
You are given an AB-string S. You need to count the number of substrings of S, which have an equal number of 'A'-s and 'B'-s.
Do you know how to solve it? Good. Mike will make the problem a little ... | def abcstr():
s = raw_input()
n = len(s)
if n < 3:
return 0
A, B, C = ([0 for _ in xrange(n+1)] for _ in xrange(3))
for i in xrange(1, n+1):
ch = s[i-1]
A[i] = A[i-1] + 1 if ch == 'A' else A[i-1]
B[i] = B[i-1] + 1 if ch == 'B' else B[i-1]
C[i] = C[i-... |
Chef has a nice complete binary tree in his garden. Complete means that each node has exactly two sons, so the tree is infinite. Yesterday he had enumerated the nodes of the tree in such a way:
Let's call the nodes' level a number of nodes that occur on the way to this node from the root, including this node. This wa... | import sys
def update_odd( direction , value ) :
if direction == 'l' :
value = (value * 2)
else :
value = (2 *value + 2)
return value
def update_even(direction , value) :
if direction == 'l' :
value = (2*value - 1)
else :
value = (2*value + 1)
return value
... |
You have a string S consisting of N uppercase English letters. You are allowed to perform at most one operation of following kind: Choose any position in the string, remove the character at that position and insert it back to any other place in the string.
Find the lexicographically smallest string you can achieve.... | t = int(raw_input())
for i in range(t):
n = int(raw_input())
s = raw_input()
if n == 1:
print s
continue
tmp = []
for j in range(n):
for k in range(n):
x = list(s)
x.insert(k, x.pop(j))
tmp.append(x)
print ''.join(min(tmp)) |
Problem description.
Chef is playing with 'n' set of planes. He notices that when two planes intersects a line is formed. Being that curious guy that chef already is, he wonders as to how many maximum possible line intersections can he obtain with his n set of planes.Given n set of planes find the maximum number of lin... | for __ in range(input()):
n = input()
n-=1
print (n*(n+1))/2 |
Alan threw a party and invited all her close friend to it. Let us suppose there were 2n people in the party and all of them were sitting across a round table.
The host asked them to shake hands with the condition that no two hands should cross each other i.e if 4 people are sitting then 1st person cannot shake hands wi... | from math import factorial as fac
def catalan(n):
return fac(2*n) // fac(n+1) // fac(n)
def num_handshakes(n):
if n % 2 == 1: return 0
return catalan(n//2)
T=int(raw_input())
while T>0:
N=int(raw_input())
print num_handshakes(2*N) %100003
T=T-1 |
Sereja has an undirected graph on N vertices. There are edges between all but M pairs of vertices.
A permutation p on the vertices of the graph is represented as p[1], p[2], … , p[N] such that for all i, p[i] is a vertex of the graph. A permutation is called connected if there is an edge between vertices p[i] and p[i+... | import itertools
MODULO=1000000007
visited = [0] * 100001
count_connected_components = 0
#functions
def depth_first_traversal(graph, node, visited):
stack = []
visited[node] = 1
stack.extend(graph[node])
while len(stack) != 0:
seed = stack.pop()
if not visited[seed]:
visited[seed] = 1
stack.extend(graph[s... |
You are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with n vertices. The edge \\{u_j, v_j\} has weight w_j. Also each vertex i has its own value a_i assigned to it.
Let's call a path starting in vertex u and ending in vertex v, where each edge can appear no more than twic... | #include <bits/stdc++.h>
using namespace std;
const int N = 300000 + 7;
int n, q;
long long val[N];
struct edge {
int to, nex;
long long wei;
} e[N << 1];
int fir[N], eid;
int siz[N], dep[N], fa[N], son[N], ltp[N];
long long faw[N];
int dfn[N], inx;
long long f[N], g[N];
long long bit[N];
void addedge(int u, int v,... |
You are given a string s consisting of n lowercase Latin letters. n is even.
For each position i (1 ≤ i ≤ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi... | def get_mask(inp):
return(5 << ord(inp) - ord('a'))
n = int(input())
for i in range(0, n):
input()
st = input()
ls = []
for j in st:
ls.append(get_mask(j))
for j in range(0, len(ls) // 2):
if(ls[j] & ls[-1 * (j + 1)] == 0):
print("NO")
break
else... |
Since astronauts from BubbleCup XI mission finished their mission on the Moon and are big fans of famous singer, they decided to spend some fun time before returning to the Earth and hence created a so called "Moonwalk challenge" game.
Teams of astronauts are given the map of craters on the Moon and direct bidirection... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7, M = 110;
struct node {
int u, v, id;
string s;
};
int n, Q, tot, cnt, m, hd[N], fa[N][20], dep[N], ans[N], v[N << 1], nxt[N << 1],
rt[N], sum[N * 50], lc[N * 50], rc[N * 50];
unsigned long long val[N][M], nv[N], dv[M], rv[M];
char c[N << 1];
s... |
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.
The treasure map can be represented as a rectangle n × m in size. Each cell stands for an islands' square (the square's side length equals... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e3 + 5;
char grid[MAX][MAX];
int n, m;
pair<int, int> pos[30];
int row[MAX][MAX], col[MAX][MAX];
inline bool inside(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m;
}
int row_wet(pair<int, int> a, pair<int, int> b) {
if (a.second > b.second)... |
There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well.
The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes th... | #include <bits/stdc++.h>
using namespace std;
set<long long int> ans;
long long int foo(long long int n, long long int k) {
long long int num = n / k;
long long int ret = (num * (num - 1)) / 2;
ret *= k;
ret += num;
return ret;
}
int main() {
long long int n;
scanf("%lld", &n);
vector<long long int> fac... |
You are given an integer n (n ≥ 0) represented with k digits in base (radix) b. So,
$$$n = a_1 ⋅ b^{k-1} + a_2 ⋅ b^{k-2} + … a_{k-1} ⋅ b + a_k.$$$
For example, if b=17, k=3 and a=[11, 15, 7] then n=11⋅17^2+15⋅17+7=3179+255+7=3441.
Determine whether n is even or odd.
Input
The first line contains two integers b and... | b,k=map(int,input().split())
arr=list(map(int,input().split()))
arr.insert(0,0)
s=0
for i in range(1,len(arr)):
s=s+(arr[-i]*pow(b,i-1,1000000000))
if(s&1):
print("odd")
else:
print("even") |
On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number t is his lucky number, if it can be represented as:
t = a2 + b2, where a, b are arbitrary positive integers.
Now, the boys decided to f... | #include <bits/stdc++.h>
using namespace std;
bitset<300000001> prime;
int main() {
int l, r;
cin >> l >> r;
int res = l <= 2 && r >= 2;
prime.set();
prime[0] = false;
prime[1] = false;
for (int i = 3; i * i <= r; i += 2)
if (prime[i]) {
for (int j = i * i; j <= r; j += (i << 1)) prime[j] = fals... |
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l.
For example, let s = "1010111". A string t = "010... | #include <bits/stdc++.h>
using namespace std;
int n, k;
int main() {
scanf("%d%d", &n, &k), k = (n - k) / 2 + 1;
for (int i = 1; i <= n; ++i) putchar('0' + !(i % k));
return 0;
}
|
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid.
A 1-st order rhombus is just a square 1 × 1 (i.e just a cell).
A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ... | n = int(input())
print(sum(range(n)) * 4 + 1)
|
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the n days of summer. On the i-th day, a_i millimeters of rain will fall. All values a_i are distinct.
The mayor k... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.*;
import static java.lang.System.*;
/*
Shortcut-->
Arrays.stream(n).parallel().sum();
string builder fast... |
In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of ... | #include <bits/stdc++.h>
using namespace std;
inline long long Getint() {
char ch = getchar();
long long x = 0, fh = 1;
while (ch < '0' || ch > '9') {
if (ch == '-') fh = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
(x *= 10) += ch ^ 48;
ch = getchar();
}
return x * fh;
}
const i... |
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r... | n, m = map(int, input().split())
mod = 10**9+7
a = []
a.append(0)
a.append(2)
a.append(4)
for i in range(3, max(n, m)+1):
a.append((a[i-1]+a[i-2])%mod)
print((a[m]-2 + a[n])%mod) |
Let's call an array t dominated by value v in the next situation.
At first, array t should have at least 2 elements. Now, let's calculate number of occurrences of each number num in t and define it as occ(num). Then t is dominated (by v) if (and only if) occ(v) > occ(v') for any other number v'. For example, arrays [1... |
//normal
import java.util.*;
import java.lang.*;
import java.io.*;
// String Tokenizer
public class Main {
public static void main(String[] args) {
// code
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while (t > 0) {
t--;
int n = scn.nextInt();
int[] arr = new int[n];
for (int i... |
The Oak has n nesting places, numbered with integers from 1 to n. Nesting place i is home to b_i bees and w_i wasps.
Some nesting places are connected by branches. We call two nesting places adjacent if there exists a branch between them. A simple path from nesting place x to y is given by a sequence s_0, …, s_p of di... | #include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
inline void minaj(T1 &x, T2 y) {
x = (x > y ? y : x);
}
template <typename T1, typename T2>
inline void maxaj(T1 &x, T2 y) {
x = (x < y ? y : x);
}
const int MAXN = 3005;
int sz[MAXN];
vector<int> e[MAXN];
int a[MAXN];
pair<int, long ... |
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to r... | import java.util.*;
import java.io.*;
public class Anu {
static BufferedReader br;
static StringTokenizer tokenizer;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
Integer[] arr = new Integer[n];
for(int i = 0; i < n; ... |
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.
The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).
Your task is to find the number... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer n ... |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | t = int(input())
for tt in range(t):
n = int(input())
arr = list(map(int,input().split()))
mx = arr[0]
sm = 0
for j in range(n):
if (arr[j] * mx < 0 ):
sm += mx
mx = arr[j]
else:
mx = max(mx , arr[j])
print(sm + mx)
|
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following:
* Empty — '.'
* Wall — '#'
* Good person — 'G'
* Bad person — 'B'
The only escape from the maze is at cell (n, m).
A person can move to a cell only if it shares a... | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode... |
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0.
The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied:
* The length of s is 1, and it consists of the character c (i.e. s_1=c);
* The lengt... | import sys
input = sys.stdin.readline
def print(val):
sys.stdout.write(str(val) + '\n')
def solve(s,l,r,c):
if l+1 == r:
return int(s[l] != c)
replace1 = replace2 = 0
for i in range(l,(l+r)//2):
if s[i] != c:
replace1 += 1
for i in range((l+r)//2, r):
if s[i] != c... |
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro... | import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return... |
A prisoner wants to escape from a prison. The prison is represented by the interior of the convex polygon with vertices P_1, P_2, P_3, …, P_{n+1}, P_{n+2}, P_{n+3}. It holds P_1=(0,0), P_{n+1}=(0, h), P_{n+2}=(-10^{18}, h) and P_{n+3}=(-10^{18}, 0).
<image>
The prison walls P_{n+1}P_{n+2}, P_{n+2}P_{n+3} and P_{n+3}P... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using str = string;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<db, db>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector... |
The only difference between the two versions of the problem is that there are no updates in the easy version.
There are n spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.
For any two spools of the same color, you ... | //starusc
#include<bits/stdc++.h>
using namespace std;
inline int read(){
int x=0,f=1,c=getchar();
while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();}
return f==1?x:-x;
}
#define ll long long
const int mod=998244353,inv2=(mod+1)>>1;
inline int fix(int x){return x+(... |
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.
Igor generated sequence p using the following algorithm:
1. initially, p = [x];
2. for each 1 ≤ i ≤ n he did the following operation |d_i| times:
* if d_i ≥ 0, then he looke... | #include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <vector>
using namespace std;
template<typename A, typ... |
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the progr... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 5001;
long long x11[10];
long long y11[10];
long long x22[10];
long long y22[10];
long long deltax[10];
long long deltay[10];
int main() {
bool flag1 = 0;
bool flag2 = 0;
bool flag3 = 0;
for (int i = 0; i < 4; i++) {
scanf("%lld %lld %lld %lld",... |
<image>
William really wants to get a pet. Since his childhood he dreamt about getting a pet grasshopper. William is being very responsible about choosing his pet, so he wants to set up a trial for the grasshopper!
The trial takes place on an array a of length n, which defines lengths of hops for each of n cells. A g... | // Author: wlzhouzhuan
#pragma GCC optimize(2, 3, "Ofast")
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pii pair<int, int>
#define pb push_back
#define fir first
#define sec second
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (in... |
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answe... | #include <bits/stdc++.h>
using namespace std;
const int M = 100000 + 10;
int hpos[M], hneg[M];
set<int> criminal;
int claim[M];
int main() {
int n, m;
cin >> n >> m;
int pos = 0;
int neg = 0;
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
int num = 0;
for (int i = 1; i < s.length(); i++) {... |
The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series.
There are n single men and n single women among the main characters. An opinion poll showed that viewers lik... | #include <bits/stdc++.h>
const int maxi = 2000000000;
const int maxq = 1000000000;
const double eps = 1e-10;
const double pi = 3.1415926535897932;
const double inf = 1e+18;
const int mo = 1000000007;
using namespace std;
int stn, ms[1111][1111], n, k, t, st[1111111], x, y, z, sum;
bool f[11111];
void rec(int x, int y) ... |
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high.
At the beginning of the first experiment there is a single bacterium in the test tub... | import java.util.*;
import java.io.*;
public class a {
static long mod = 1000000007;
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(new PrintStream(System.out));
//input.init(new FileInputStream(new File("input.txt")));
//PrintWriter out =... |
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.
... | #include <bits/stdc++.h>
using namespace std;
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cout << *it << " = " << a << "\n";
err(++it, args...);
}
const long long M = 1e9 + 7, inf = 1e9;
int main() {
ios_base::sync_wit... |
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:
* he chooses two elements of the array ai, aj (i ≠ j);
... | import java.util.Scanner;
public class P246B {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int n = inScanner.nextInt();
int sum = 0;
for (int j = 0; j < n; j++) {
sum += inScanner.nextInt();
}
if (sum % n == 0) {
System.out.println(n);
... |
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presup... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int ans[N];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
if (n < 3 * k) {
cout << -1 << '\n';
return 0;
}
if (k % 2 == 0) {
for (int i = 1; i <= 3 * k; i += 6) {
ans[i] = ans[i + 1] =... |
The great Shaass is the new king of the Drakht empire. The empire has n cities which are connected by n - 1 bidirectional roads. Each road has an specific length and connects a pair of cities. There's a unique simple path connecting each pair of cities.
His majesty the great Shaass has decided to tear down one of the ... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 2147483647;
long long read() {
long long first = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
first = first * 10 + ch - '0';
ch = getch... |
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number... | import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long x = sc.nextLong();
long y = sc.nextLong();
long m = sc.nextLong();
if (x <= 0 && y <= 0 && m > 0)
System.out.println(-1);
// else if(x>=0 && y>=0 && m<)
else if (x >= m || y... |
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius r (the cupboard's top) and two walls of height h (the cupboard's sides). The cupboard's depth is r, that is, it looks like a rectangle with base r and height h + r from the sides. The figure below shows what... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
long long r, h;
cin >> r >> h;
if (h % r == 0) {
cout << 2 * (h / r) + 1 << endl;
} else {
long long c = h / r;
long long ans = 2 * c;
if (2 * (h - c * r) >= r) {
ans += 2;
... |
We'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if <image>, then <image>. In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.
Your task is to find any beautiful set, where the number of... | #include <bits/stdc++.h>
using namespace std;
vector<int> as;
int a[20] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43};
int main() {
int i, j, n;
as.push_back(1);
scanf("%d", &n);
for (j = 0; as.size() <= n; j++)
for (i = 0; i < as.size(); i++) {
if (as[i] * a[j] <= n * n * 2) as.push_back(as[... |
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output... | #include <bits/stdc++.h>
using namespace std;
int powInt(int x, int y) {
int r = 1;
while (y > 0) {
if (y & 1) r = (r * x);
x = (x * x);
y /= 2;
}
return r;
}
int qrt(long k, int ex) {
int res = 1;
while (powInt(res, ex) <= k) {
res++;
}
return res - 1;
}
int main() {
int k;
cin >> k... |
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of points on a plane.
Each of the next n lines contains two real coordinates xi and yi of the <image> point, specified with exactly 2 fractional digits. All coordinates are between - 1000 and 1000, inclusive.
Output
Output a single real... | #include <bits/stdc++.h>
using namespace std;
int main() {
double x, y[1010], n, ans, all = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> x >> y[i];
all += y[i];
}
ans = 5 + all * 1.0 / n;
printf("%.3lf", ans);
return 0;
}
|
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set S:
* its elements were distinct integers from 1 to limit;
* the value of <ima... | import java.awt.Point;
import java.io.*;
import java.util.*;
public class C
{
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in) ;
PrintWriter out = new PrintWriter(System.out) ;
int sum = sc.nextInt() , limit =... |
On a history lesson the teacher asked Vasya to name the dates when n famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [li, ri] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose... | # http://codeforces.com/contest/45/problem/D
from sys import stdin
inFile = stdin
tokens = []
tokens_next = 0
def next_str():
global tokens, tokens_next
while tokens_next >= len(tokens):
tokens = inFile.readline().split()
tokens_next = 0
tokens_next += 1
return tokens[tokens_next - 1]
... |
You play the game with your friend. The description of this game is listed below.
Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals <image>. You... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 333;
const long long linf = 1e18 + 333;
const int N = 50;
const int M = 21;
int n, m, cnt[1 << M];
long long w[1 << M];
double dp[1 << M];
char s[N][M];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%s", s[i]);
m = strlen(s[0])... |
Mr. Kitayuta's garden is planted with n bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the i-th bamboo is hi meters, and it grows ai meters at the end of each day.
Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed beca... | #include <bits/stdc++.h>
using namespace std;
int a1234;
inline void xxx() {
for (;;)
;
}
inline int rd(int l, int r) { return rand() % (r - l + 1) + l; }
const int mxn = 1e5 + 3;
long long a[mxn], now[mxn];
int n, m, k, hh;
priority_queue<pair<long long, int> > q;
int day[mxn], h[mxn];
inline void ins(int x) { q... |
You are given a n × m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).
Input... | #include <bits/stdc++.h>
using namespace std;
char arr[1001][1001];
int main() {
int row[1001] = {0};
int col[1001] = {0};
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
cin >> arr[i][j];
if (arr[i][j] == '*') {
row[i]++;
col[j]++;
}
... |
Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure.
However, he needs help conducting one of the investigative experiment. There are n pegs put on a plane, they are numbered from 1 to n, the coordinates of the i-th of them are (x... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 200003;
long long INF = 0x3f3f3f3f3f3f3f3fll;
int n, Q, pos[maxn];
pair<long long, int> a[maxn];
int main() {
scanf("%d%d", &n, &Q);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i].first), a[i].second = i;
sort(a + 1, a + n + 1);
a[0].first = -INF,... |
Petya loves computer games. Finally a game that he's been waiting for so long came out!
The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is... | import java.io.*;
import java.util.*;
public class A1{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int arr[] = new int[n];
int a[] = new int[n];
int ans=0;
for(int i=0;i<n;i++){... |
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where... | #include <bits/stdc++.h>
using namespace std;
const int INF = (1LL << 30) - 1;
const long long int LINF = (1LL << 62) - 1;
const int MOD = (int)1e9 + 7;
const int NMAX = (int)1e6;
int P, K;
int root[NMAX + 5];
unordered_set<int> M;
int expLog(int B, int E) {
int Q = B, sol = 1;
for (int i = E; i; i /= 2) {
if (... |
Ostap Bender recently visited frog farm and was inspired to create his own frog game.
Number of frogs are places on a cyclic gameboard, divided into m cells. Cells are numbered from 1 to m, but the board is cyclic, so cell number 1 goes right after the cell number m in the direction of movement. i-th frog during its t... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
int read() {
int x = 0, f = 1, ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar();
return x * f;
}
int n, L, p[100005], a[100005], ... |
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, the... | # -*- coding:utf-8 -*-
import sys
def some_func():
"""
"""
a,b,c = map(int,sys.stdin.readline().split())
if c:
if a==b:
print "YES"
return
if (b-a)%c==0 and (b-a)/c>0:
print 'YES'
else:
print 'NO'
else:
if a==b:
... |
You are given a description of a depot. It is a rectangular checkered field of n × m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*").
You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column... | #include <bits/stdc++.h>
using namespace std;
string s[1000];
int main() {
int n, m, k = 0, l = 0, f = 0, g = 0;
cin >> n >> m;
for (int i = 0; i < n; i++) cin >> s[i];
if (n == 3 && m == 3 && s[0] == ".*." && s[1] == ".*." && s[2] == ".**") {
cout << "YES" << endl << 3 << " " << 2;
} else if (n == 3 && m... |
Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them.
Vasya lays out nm cards as a rectangle n × m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which a... | #include <bits/stdc++.h>
using namespace std;
string firsts = "23456789TJQKA";
string seconds = "CDHS";
int n, m;
string a[55][55];
vector<pair<string, string>> cur, ans;
vector<pair<int, int>> wh;
bool go(int x, int y) {
if (y == m) {
y = 0;
++x;
}
if (x == n) {
vector<pair<int, int>> goods;
for ... |
As you have noticed, there are lovely girls in Arpa’s land.
People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.
<image>
Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are a... | import java.io.*;
import java.util.*;
public class CF741A {
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
St... |
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. ... | #include <bits/stdc++.h>
using namespace std;
int a[300000];
int s[2];
int b[300000];
int fp(int a, int k, int m) {
int res = 1;
while (k) {
if (k & 1) res = 1LL * res * a % m;
a = 1LL * a * a % m;
k >>= 1;
}
return res;
}
int main() {
int m, n;
scanf("%d%d", &m, &n);
s[0] = s[1] = 0;
for (i... |
Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia.
It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending... | #include <bits/stdc++.h>
using namespace std;
bool mark[1000005], visited[1000005];
long long loop, res, n, m;
vector<int> graph[1000005];
void dfs(int u) {
visited[u] = 1;
int len = graph[u].size();
for (int i = 0; i < len; i++) {
int v = graph[u][i];
if (visited[v] == 1) continue;
dfs(v);
}
}
long... |
Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking.
In total, they intended to visit n towns. However ... | #include <bits/stdc++.h>
using namespace std;
struct Treap {
int key, p, lz;
Treap *l, *r;
Treap() {}
Treap(int key) {
this->key = key, this->p = rand();
l = r = NULL;
lz = 0;
}
void unlz() {
key += lz;
if (l) l->lz += lz;
if (r) r->lz += lz;
lz = 0;
}
int size() {
int sz... |
<image>
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in th... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
long long a, b, c, d, e, f, i, j, k, n;
string x, y, z;
cin >> n >> k;
cin >> x;
a = x.length();
vector<long long> v(30, 0), u(30, 0);
for (i = 0; i < a; i++) {
b = (long long)(x[i] - 'A');
if (v[b] == 0... |
Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.
First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares s... | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class C extends PrintWriter {
int cnt1, cnt2;
class Node {
final int fx, tx;
final int[] y;
final Node l, r;
Node(int x, int y) {
... |
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an... | #include <bits/stdc++.h>
using namespace std;
bool res[15][2];
char commands[500005];
int num[500005];
int Xor, Or, And;
int main() {
int n, i, j, st = 1, j2;
bool b, b2, BB;
cin >> n;
for (i = 0; i < n; i++) {
cin >> commands[i] >> num[i];
}
for (i = 0; i <= 9; i++) {
for (j2 = 0; j2 <= 1; j2++) {
... |
You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n.
You have to answer q queries. Each query is described by a segment of vertices [l; r... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
long long n, m, q, l, r;
long long vis[3 * maxn], cir[3 * maxn], suff[3 * maxn];
vector<long long> G[3 * maxn];
stack<long long> path;
void dfs(long long now, long long pre) {
path.push(now);
vis[now] = 1;
for (int i = 0; i < (int)G[now].siz... |
In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are l... | #include <bits/stdc++.h>
using namespace std;
long long n, m, ladder, lift, v, q;
vector<long long> lads, lifts;
long long sa(long long xa, long long ya, long long xb, long long yb,
vector<long long>& lads, long long v) {
long long xrun = abs(xa - xb);
long long ydist = abs(ya - yb);
if (ya == yb) {
... |
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard.
Initially, you have an empty string. Until you type the whole string, you may perform the following operation:
* add a character to the end of the string.
Besides, at most once you may perform one... | import com.sun.corba.se.impl.logging.InterceptorsSystemException;
import java.beans.Expression;
import java.io.*;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
public class test {
public static void main(String[] ar... |
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.
<image>
You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times... | s =input()
dash = s.count('-')
ring = s.count('o')
k = min(dash,ring)
m = max(dash,ring)
if dash == 0 or ring==0:
print('YES')
else:
if dash%ring==0:
print('YES')
else:
print('NO')
|
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | x, y = input().split()
x = int(x)
y = int(y)
z = 7 - max(x, y)
ans = z/6
if ans == (1/6):
print("1/6")
elif ans == (2/6):
print("1/3")
elif ans == (3/6):
print("1/2")
elif ans == (4/6):
print("2/3")
elif ans == (5/6):
print("5/6")
else:
print("1/1")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.