input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (... | #include <bits/stdc++.h>
using namespace std;
const int maxn = (int)4e5;
struct state {
int next[37], len, suff;
state() {
memset(next, -1, sizeof(next));
suff = -1;
len = 0;
}
} st[2 * maxn];
int sz = 1, last = 0;
vector<int> g[maxn];
char second[maxn];
int L[maxn], R[maxn], n;
int dp[maxn * 3][11], ... |
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.
The girl finds an important permutation for the resea... | #include <bits/stdc++.h>
using namespace std;
long long dp[2010][2010];
long long fact[4010];
long long solve(int n, int k) {
if (k < 0 or n < 0)
return 0;
else if (k == 0)
return fact[n];
else if (dp[n][k] != -1)
return dp[n][k];
long long ret = 0;
ret += n * solve(n, k - 1);
ret += (k - 1) * s... |
John Doe has recently found a "Free Market" in his city — that is the place where you can exchange some of your possessions for other things for free.
John knows that his city has n items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that eac... | #include <bits/stdc++.h>
int dp[600009];
int main() {
int n, d;
int i, j, sum, tmp;
int now, back, day;
while (scanf("%d %d", &n, &d) != EOF) {
memset(dp, 0, sizeof(dp));
dp[0] = 1;
sum = 0;
for (i = 1; i <= n; i++) {
scanf("%d", &tmp);
sum += tmp;
for (j = sum; j >= tmp; j--) ... |
Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box).
Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For exampl... | #include <bits/stdc++.h>
using namespace std;
class machine {
private:
int n;
vector<int> arr;
int mn;
int mx;
int cur;
int sz;
public:
machine(int n) {
this->n = n;
sz = 0;
arr.resize(101);
mn = 101;
mx = 0;
cur = -1;
}
void getInput() {
int tmp;
for (int i = 0; i <... |
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.
The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Admin
*/
public class Main
{
public static void main(String[]... |
In this problem you will need to deal with an n × m grid graph. The graph's vertices are the nodes of the n × m grid. The graph's edges are all the sides and diagonals of the grid's unit squares.
The figure below shows a 3 × 5 graph. The black lines are the graph's edges, the colored circles are the graph's vertices. ... | #include <bits/stdc++.h>
using namespace std;
char s[1111][1111];
int a[1111][1111];
int b[1111][1111];
int m, n;
void init(void) {
scanf("%d%d", &m, &n);
for (int i = 0; i < (m); i = i + 1) scanf("%s", s[i]);
for (int i = 0; i < (m); i = i + 1)
for (int j = 0; j < (n); j = j + 1) a[i][j] = s[i][j] - 49;
}
bo... |
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al... | #!/usr/bin/env python3
import atexit
import io
import sys
import bisect
_I_B = sys.stdin.read().splitlines()
input = iter(_I_B).__next__
_O_B = io.StringIO()
sys.stdout = _O_B
@atexit.register
def write():
sys.__stdout__.write(_O_B.getvalue())
def main():
x1,y1,x2,y2=map(int,input().split())
if x1==x2:
... |
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is di... | #include <bits/stdc++.h>
using namespace std;
template <class T>
void show(T a, int n) {
for (int i = 0; i < n; ++i) cout << a[i] << ' ';
cout << endl;
}
template <class T>
void show(T a, int r, int l) {
for (int i = 0; i < r; ++i) show(a[i], l);
cout << endl;
}
const int N = 120000;
const int M = 120000;
const... |
Misha has a tree with characters written on the vertices. He can choose two vertices s and t of this tree and write down characters of vertices lying on a path from s to t. We'll say that such string corresponds to pair (s, t).
Misha has m queries of type: you are given 4 vertices a, b, c, d; you need to find the larg... | #include <bits/stdc++.h>
using namespace std;
int n, head[300300], nxt[300300 << 1], to[300300 << 1], fa[300300][22],
dp[300300];
void add_edge(int x, int y, int id) {
nxt[id] = head[x], head[x] = id;
to[id] = y;
}
void dfs(int x, int p = 0) {
fa[x][0] = p;
for (int i = 1; i <= 31 - __builtin_clz(n); i++)
... |
The project of a data center of a Big Software Company consists of n computers connected by m cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is n... | #include <bits/stdc++.h>
using namespace std;
int out[100010], deg[100010];
queue<pair<int, int> > q[100010];
bool vis[100010 * 3];
struct Node {
int a, b;
} ans[3 * 100010];
int cnt;
void dfs(int u) {
int i, v;
pair<int, int> now;
while (!q[u].empty()) {
now = q[u].front();
q[u].pop();
v = now.firs... |
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho... | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class A554 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
String book = input.next();
for (int i=0; i<=book.length(); i++) {... |
Brian the Rabbit adores chess. Not long ago he argued with Stewie the Rabbit that a knight is better than a king. To prove his point he tries to show that the knight is very fast but Stewie doesn't accept statements without evidence. He constructed an infinite chessboard for Brian, where he deleted several squares to a... | #include <bits/stdc++.h>
using namespace std;
const int OX = 200, OY = 200;
const int DX[8] = {1, 2, -1, -2, -2, -1, 1, 2};
const int DY[8] = {2, 1, 2, 1, -1, -2, -2, -1};
const long long MOD = 1e9 + 7;
const int N = 1e5, T = 50;
int n, he, ta, dep[4 * OX][4 * OY], cnt[T + 5];
long long k;
pair<int, int> q[N];
int main... |
You are given a tree T with n vertices (numbered 1 through n) and a letter in each vertex. The tree is rooted at vertex 1.
Let's look at the subtree Tv of some vertex v. It is possible to read a string along each simple path starting at v and ending at some vertex in Tv (possibly v itself). Let's denote the number of ... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 999998727899999ll, MAXN = 300001;
long long c[MAXN];
vector<long long> g[MAXN];
set<long long> s[MAXN];
string t;
bool mark[MAXN];
long long base = 101;
long long diff[MAXN];
long long ans[MAXN];
long long n;
void dsu(long long a1, long long a2) {
se... |
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
* the i-th letter occurs in the string no more than ai times;
* the number of occurrences of each letter in the string must be distinct for all the lette... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
unsigned long long a;
vector<long long> count;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a;
count.push_back(a);
}
sort(count.begin(), count.end());
unsigned long long total = 0;
long long previous = count[n - 1] + 1;
for ... |
In an attempt to make peace with the Mischievious Mess Makers, Bessie and Farmer John are planning to plant some flower gardens to complement the lush, grassy fields of Bovinia. As any good horticulturist knows, each garden they plant must have the exact same arrangement of flowers. Initially, Farmer John has n differe... | #include <bits/stdc++.h>
using namespace std;
int N, K, Q;
int freq[1000010];
long long F[1000010], inv[1000010], Finv[1000010];
long long C[1000010];
long long coef[1000010];
int minp[1000010];
long long query(int x) {
long long ans = C[freq[x] + 1] - C[freq[x]] + 1000000007ll;
if (ans >= 1000000007ll) ans -= 1000... |
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to t... | #include <bits/stdc++.h>
long long max(long long a, long long b) { return a > b ? a : b; }
const int maxn = 500005;
int a[maxn];
int n, k;
long long S, s, d, D, p, L, R;
void t_main() {
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
S += a[i];
}
std::sort(a, a + n);
d = S / ... |
Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.
<image>
Initially, happiness level of Nora is 0. Nora loves some pickup lines like "I'm falling for you" and stuff. Totally, she knows... | #include <bits/stdc++.h>
const long long N = 1e5 + 10, alpha = 128;
using namespace std;
long long n, q, m, k, x, y, a[N], mx = -1, mn = 1e9, sum[N];
string s, s1, s2;
long long trie[N][alpha], ndcnt, ids[N], fail[N], sz[N], nxtid[N], myids[N];
char children[N][alpha];
void addnode() {
memset(trie[ndcnt], -1, sizeof(... |
Today is Matvey's birthday. He never knows what to ask as a present so friends gave him a string s of length n. This string consists of only first eight English letters: 'a', 'b', ..., 'h'.
First question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what to do w... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 112345;
const int inf = 0x3f3f3f3f;
int n, a[maxn], dist[maxn][8], d[8][8], c[8][1 << 8], mask[maxn];
char s[maxn];
inline void bfs(int col) {
queue<int> que;
dist[n + col + 1][col] = 0;
que.push(n + col + 1);
for (int i = 1; i <= n; ++i)
if (co... |
Vasya plays FreeDiv. In this game he manages a huge state, which has n cities and m two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city a... | #include <bits/stdc++.h>
using namespace std;
int k, n, m;
vector<int> aa[1000010];
bool f[1000010];
int dfs(int v) {
f[v] = true;
int res = 1;
for (int i = 0; i < int(aa[v].size()); i++) {
int a = aa[v][i];
if (!f[a]) res += dfs(a);
}
return res;
}
int main() {
cin >> n >> m >> k;
for (int i = 0;... |
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.
Help Timofey to color his rectangles in 4 different... | #include <bits/stdc++.h>
using namespace std;
int x, y, a, b, n;
void init() {
scanf("%d", &n);
puts("YES");
for (int i = 1; i <= n; i++) {
scanf("%d%d%d%d", &x, &y, &a, &b);
printf("%d\n", 2 * abs(x % 2) + abs(y % 2) + 1);
}
}
int main() {
init();
return 0;
}
|
Rick is in love with Unity. But Mr. Meeseeks also love Unity, so Rick and Mr. Meeseeks are "love rivals".
Unity loves rap, so it decided that they have to compete in a rap game (battle) in order to choose the best. Rick is too nerds, so instead he's gonna make his verse with running his original algorithm on lyrics "... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
long long powmod(long long a, long long b) {
long long res = 1;
a %= mod;
assert(b >= 0);
for (; b; b >>= 1) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
}
return res;
}
const int N = 40100;
int T, p[N], c[N], dep[... |
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w ≤ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:
* Every cup will contain tea for at least hal... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int MaxN = 2e5 + 10;
struct node {
int val;
int id;
} arr[110];
bool cmp(node a, node b) {
if (a.val == b.val) return a.id < b.id;
return a.val > b.val;
}
int ans[110];
int main() {
int n, w;
scanf("%d%d", &n, &w);
for (int i ... |
Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.
The boys decided to have fun and came up with a plan. Namely, in some day in the morning M... | #include <bits/stdc++.h>
using namespace std;
const int tinf = (int)1e9 + 7;
const long long inf = (long long)1e18 + 7;
const int N = 4e5 + 5;
vector<vector<long long> > g(N);
long long used[N], tin[N], tout[N], up[N][40], l, timer, n, q, cnt[N];
void dfs(long long v, long long p = 0) {
used[v] = 1;
up[v][0] = p;
... |
Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.
There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for... | #include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ii = pair<int, int>;
using vii = vector<ii>;
using ll = long long;
using ull = unsigned long long;
using pll = pair<ll, ll>;
using vpll = vector<pll>;
using vll = vector<ll>;
using pdd = pair<double, double>;
using vpdd = vector<pdd>;
template ... |
In Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems.
Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price.
Ann decided that she wants to buy such non-empty subsegment t... | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
const int MAGIC = 320;
int a[N], p[N];
long long s[N], k;
long long now;
int l, r;
vector<long long> all;
int at[N], atp[N], atm[N], cnt[N];
void add(int i, int v) { cnt[at[i]] += v; }
long long ans[N];
int main() {
int n;
scanf("%d %lld", &n, &k)... |
Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way:
<image>
This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder o... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int r[160] = {0};
int d[160] = {0};
int r1[160] = {0};
int d1[160] = {0};
if (n == 1) {
cout << 1 << endl << 0 << " " << 1 << endl << 0 << endl << "1" << endl;
} else {
r[0] = -1;
d[0] = 0;
d[1] = 1;
for (int... |
There is a number x initially written on a blackboard. You repeat the following action a fixed amount of times:
1. take the number x currently written on a blackboard and erase it
2. select an integer uniformly at random from the range [0, x] inclusive, and write it on the blackboard
Determine the distributi... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 262144;
const int MOD = 998244353;
inline void ADD(int& x, int y) {
x += y;
if (x >= MOD) x -= MOD;
}
inline void DEC(int& x, int y) {
x -= y;
if (x < 0) x += MOD;
}
inline int add(int x, int y) { return x + y < MOD ? x + y : x + y - MOD; }
inline i... |
Input
The input contains a single integer a (10 ≤ a ≤ 999).
Output
Output 0 or 1.
Examples
Input
13
Output
1
Input
927
Output
1
Input
48
Output
0 | import java.util.*;
public class Four_test {
public static Scanner scanner = new Scanner(System.in);
public static int input;
public static void main(String []args){
input=scanner.nextInt();
int num;
num=input%2;
if (num!=0){
System.out.print("1");
}else {... |
Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choos... | #include <bits/stdc++.h>
using namespace std;
int i, j, n, m, a, b, c, d, op, mini, mij, ls, ld, ul, timp, k, maxl, rasp;
long long dp[1000005], flower[1000005], viz[1000005];
vector<int> v[1000005];
long long rez;
void go(int nod, int p) {
if (viz[nod]) return;
viz[nod] = 1;
for (int i = 0; i < v[nod].size(); i+... |
You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n.
In a single move, you can choose any position i between 1 and n and increase a_i by 1.
Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.util.*;
public class E {
static int n, m;
public static void main(String[] args) throws Throwable {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new Pri... |
Benny noticed a random property of numbers. The numbers which followed this property were called as interesting numbers by Benny. Let's dive into what Benny discovered about these numbers.
1 is an interesting number.
For every N > 1 , N is interesting if it has odd number of interesting proper divisors.
For example, ... | def rwh_primes(n):
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return [2] + [i for i in range(3,n,2) if sieve[i]]
def test(a, primes):
for p in primes:
n = 0
while (a % p) == 0:
n += 1
a = a // p
... |
Some terrorist attacks on Indian border. Now Indian Army have to send his soldiers to fight against terrorist. There are total N soldiers in the camp. Every soldier has a skill denoted by a single character lies between A-Z (all skills are in CAPITAL LETTERS). Now commander gave order to stand all the soldiers in a row... | def unique(s):
i, j = 0, 0
I, J = 0, 0
H = set([])
while j < len(s):
if s[j] in H:
H.remove(s[i])
i += 1
else:
H.add(s[j])
j += 1
if J - I < j - i:
I, J = i, j
return s[I:J]
def main():
for i in xrange(input()):
s... |
Pseudo-code to find the nth fibonacci number :
int fibo(int n)
{
if (n == 0)
{
write(0)
return 0
}
if (n == 1)
{
write(1)
return 1
}
return fibo(n - 1) + fibo(n - 2)
}
If we call fibo(3), the following happens:
fibo(3) calls fibo(2) and fibo(1) ---->the first call.
fibo(2) calls fibo(1) ---->the seco... | t = int(raw_input())
n0 = [None] * 42
n1 = [None] * 42
n0[0], n0[1] = 1, 0
n1[0], n1[1] = 0, 1
for i in range(2, 41):
n0[i] = n0[i - 1] + n0[i - 2]
n1[i] = n1[i - 1] + n1[i - 2]
for _ in range(t):
n = int(raw_input())
print n0[n], n1[n] |
A bacteria lifespan is represented as follows:-
0th year- born
1st year- Does not reproduce only grows
2nd year- Gives birth to another Bacteria
3rd year- Gives birth to another Bacteria and then Dies
Initially in 0th year there is only 1 bacteria
Population in Nth year:-
year-population
0-1
1st year- 1
2nd y... | ip = int(raw_input())
c = 0
first = 1
second = 1
third = 2
forth = 2
if(ip == 0):
print 1
if(ip == 1):
print 1
if(ip == 2):
print 2
if(ip == 3):
print 2
c = 3
while c <=ip :
forth = second + first
first = second
second = third
third = forth
#forth =
c = c + 1
print forth |
Each army fighting the world war Z is denoted with a word consisting any combination of 26 alphabets. An army is a match for his/her opponent if and only if his name is an anagram of his/her opponent. Your job as a programmer is to help find whether two randomly selected members are match for each other or not.
(An an... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
t1=input()
while t1>0:
t1-=1
s,t=raw_input().split()
s=sorted(s)
t=sorted(t)
if s==t:
print "Yes"
else:
print "No" |
Tod is very much focus about his English subject but now he is in trouble because he have to do his Math homework but also have to go for English classes so he asks you for help to solve his Math homework question.
You are given a Natural number(N) you have to print Factorial of the Prime number present in the (S) se... | import math
def fact(n):
t=n
prod =1
while(t!=1):
prod*=t
t-=1
print prod
n = input()
for num in range(2,n+1):
if(all(num%i!=0 for i in range(2, int(math.sqrt(num)+1)))):
fact(num) |
Hardy wants to test Ramanujam of his Mathematical skills. So he gives him a puzzle which is described below.
Puzzle:
There are 100 doors, numbered 1,2,....100 .Initially all doors are closed.
Now a person comes(lets call him the 1st person)he opens the first door and leaves.
Now a second guy comes and checks the stat... | def get_primes(start, stop):
dct = {x: True for x in list(range(start, stop+1))}
x = start
while x ** 2 <= stop:
if dct[x]:
y = x ** 2
while y <= stop:
dct[y] = False
y += x
x += 1
lst = []
for x, y in dct.items():
if ... |
Shil has a permutation p1 , p2 .. pN of numbers from 1 to N and M queries. Each query consists of two integers l and r . Answer to each query is total number of pairs[i , j] such that l ≤ i ≤ j ≤ r and|pi - pj| ≤ D.
INPUT:
First line consists of three integers N, M and D. Next line consists of permutation p1 , p2 ..... | (n, m, d) = [int(v) for v in raw_input().strip().split(' ')]
arr = [int(v) for v in raw_input().strip().split(' ')]
pos = [0] * (n + 1)
q = []
for i in range(0, len(arr)):
pos[arr[i]] = i
for i in range(0, m):
(l, r) = [int(v) for v in raw_input().strip().split(' ')]
q.append(((l, r), i))
q = sorted(q, ke... |
Robert Angier is divising a new magic trick to beat his rival Alfred Borden. He is going to perform a card trick. In this trick, cards are numbered from 1 to N. This trick involves the following process. Angier will invite a person from audience to shuffle the cards in random order.
Following is defined as a sing... | import math
n = int(raw_input())
for ii in range(n):
N,K = map(int,raw_input().split())
if N % 2 == 0 and K <= N/2:
print K*2-1
elif N % 2 == 1 and K <= N/2+1:
print K*2-1
elif N-K == 0:
pp = int(math.log(N)/math.log(2) - 1e-5)
print int(2*(N-math.pow(2,pp)))
else:
ff = (3+2*(N-K-1))
pp = int( mat... |
You are given an integer K. Print the string obtained by repeating the string `ACL` K times and concatenating them.
For example, if K = 3, print `ACLACLACL`.
Constraints
* 1 \leq K \leq 5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
K
Output
Print the s... | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String res="";
while(n-->0){
res=res+"ACL";
}
System.out.println(res);
}
} |
There are N towns numbered 1, 2, \cdots, N.
Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.
In the planning of construction, each town chooses one town different from itself and requests the following: roads are built... | #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<functional>
#include<vector>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
#define MOD 1000000007
#define f(i,n) for(long long i=0;i<(long long)(n);i++)
#define N 200000
vector<long long>... |
We have a grid with H rows and W columns, where all the squares are initially white.
You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions:
* Choose one row, then paint all the squares in that row black.
* Choose one column, then paint all the s... | #include <iostream>
using namespace std;
int main(){
int h,w,n;
cin >> h >> w >> n;
cout << (n + max(h,w) -1) / max(h,w) << endl;
}
|
There are N cards placed on a grid with H rows and W columns of squares.
The i-th card has an integer A_i written on it, and it is placed on the square at the R_i-th row from the top and the C_i-th column from the left.
Multiple cards may be placed on the same square.
You will first pick up at most one card from eac... | #include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for... |
There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively. Print `Yes` if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print `No` otherwise.
Constraints
* 0\leq A,B,C\leq 100
* A, B and C are distinct integers.
I... | import java.io.*;
import java.util.Scanner;
public class Main {
private static Scanner sc;
private static Printer pr;
private static void solve() {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if (a < c && c < b) {
pr.println("Yes");
} else if (a > c && c > b) {
pr.println("... |
Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.
Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?
Constraints
* 1 ≤ X ≤ 9
* X is an integer.
Input
Input is given from... | import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int X = sc.nextInt();
System.out.println(X == 7 || X == 5 || X == 3 ? "YES" : "NO");
}
}
|
In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.
For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.
In this country, a date is called Takahashi when the month and the day are equal as numbers. For exam... | #include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int ans=a>b?a-1:a;
cout<<ans<<endl;
} |
Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.
Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in whic... | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,n) for(int i = 0; i < (n); i++)
#define sz(c) ((int)c.size())
#define ten(n) ((int)1e##n)
using ll = long long;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;
template<typename ...> static inline int getchar_unlocked(void) { return getchar(); }
templa... |
Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.
The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It ... | n=int(input())
l=[int(input()) for i in range(n)]
a=1
ans=0
while a!=2:
a=l[a-1]
ans+=1
if ans==n+1:
ans=-1
break
print(ans)
|
You are given two integers K and S.
Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K.
How many different assignments of values to X, Y and Z are there such that X + Y + Z = S?
Constraints
* 2≤K≤2500
* 0≤S≤3K
* K and S are integers.
Input
The input is given from Standard Input in the following for... | k,s=map(int,input().split());r=range;print(sum(1for x in r(k+1)for y in r(k+1)if 0<=s-x-y<=k)) |
We have a grid with H rows and W columns. At first, all cells were painted white.
Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.
Compute the following:
* For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the gr... | from collections import defaultdict
H,W,N=map(int,input().split())
ans=[(H-2)*(W-2)]+[0]*9
blacks=defaultdict(int)
for i in range(N):
a, b = map(int,input().split())
for dx in [-1,0,1]:
for dy in [-1,0,1]:
if 2<=a+dx<H and 2<=b+dy<W:
ans[blacks[(a+dx,b+dy)]]-=1
ans[blacks[(a+dx,b+dy)]+1]+... |
Dr .: Peter, I've finally done it.
Peter: What's wrong, Dr. David? Is it a silly invention again?
Dr .: This table, this table.
| Character | Sign
--- | ---
(Blank) | 101
'| 000000
, | 000011
-| 10010001
. | 010001
? | 000001
A | 100101
B | 10011010
| Character | Sign
--- | ---
C | 0101
D | 0001
E | 110
F | 01001
G |... | #include <iostream>
#include <string>
using namespace std;
string ab[26] = {
"100101","10011010","0101","0001","110",
"01001","10011011","010000","0111","10011000",
"0110","00100","10011001","10011110","00101",
"111","10011111","1000","00110","00111",
"10011100","10011101","000010","10010010","10010011",
"10010000"};
s... |
"What are your shoe sizes?"
Suddenly, the doctor asked me when I met him for the first time.
"It's 23.5"
"Oh, that's a really nice number. It's 2 to the 4th power plus 2 to the 2nd power, 2 to the 1st power, 2 to the 0th power, and 2 to the 1st power."
Then the doctor asked.
"You, how tall are you?"
"Yes, it's 158.... | #include <iostream>
#include <string>
using namespace std;
int main() {
double d;
while(cin >> d, d >= 0) {
int a = 0;
string b = "";
a = d;
d -= a;
for(int i = 0; i < 4; i++) {
b += (char)((d * 2) + '0');
d *= 2;
if(d >= 1) d -= 1;
}
if(d > 1e-9 || a >= (1 << 8))
cout << "NA" << endl;
el... |
PCK Taxi in Aizu city, owned by PCK company, has adopted a unique billing system: the user can decide the taxi fare. Today as usual, many people are waiting in a queue at the taxi stand in front of the station.
In front of the station, there are $N$ parking spaces in row for PCK taxis, each with an index running from ... | #include<iostream>
#include<vector>
#include<queue>
using namespace std;
int main() {
int N;
cin >> N;
vector<vector<int>> C(N);
int i,j;
int m,c;
for(i=0;i<N;i++) {
cin >> m;
for(j=0;j<m;j++) {
cin >> c;
C[i].push_back(c);
}
}
priority_que... |
Let A, B, C, D, E be sets of integers and let U is a universal set that includes all sets under consideration. All elements in any set are different (no repetitions).
u - union of two sets, AuB = {x ∈ U : x ∈ A or x ∈ B} is the set of all elements which belong to A or B.
i - intersection of two sets, AiB = {x ∈ U : x... | #include<cstdio>
#include<vector>
#include<algorithm>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
vector<int> expr();
vector<int> set1();
vector<int> set2();
vector<int> alpha();
int idx;
char s[2000];
vector<int> S[5],U;
vector<int> calc_c(const vector<int> &A){
vector<int> B;
rep(i,U.size()) ... |
Taro and Hanako have numbers of cards in their hands. Each of the cards has a score on it. Taro and Hanako wish to make the total scores of their cards equal by exchanging one card in one's hand with one card in the other's hand. Which of the cards should be exchanged with which?
Note that they have to exchange their ... | while True:
n,m = map(int,input().split())
if n == 0:
exit()
t = []
h = []
ans = []
for i in range(n):
t.append(int(input()))
for i in range(m):
h.append(int(input()))
for i in range(n):
for j in range(m):
if (sum(t) - t[i] + h[j]) == (sum(h) -... |
International Center for Picassonian Cubism is a Spanish national museum of cubist artworks, dedicated to Pablo Picasso. The center held a competition for an artwork that will be displayed in front of the facade of the museum building. The artwork is a collection of cubes that are piled up on the ground and is intended... | #include<bits/stdc++.h>
using namespace std;
int W, D;
int hw[21], hd[21];
int main(){
int h;
while(cin >> W >> D, W){
for(int i = 0; i < 21; i++){
hw[i] = 0;
hd[i] = 0;
}
for(int i = 0; i < W; i++){
cin >> h;
hw[h]++;
}
for(int i = 0; i < D; i++){
cin >> h;
hd[h]++;
}
int ans = 0... |
Problem
Today, the Earth has been attacked by the invaders from space, Invader, and the only survivors of humankind are us at the base. There is almost no force left to compete with them. But here we do not give up. Eradication of Invaders is the last resort for us humans to survive. I will explain the contents of the... | #include "bits/stdc++.h"
using namespace std;
typedef int Value1;
typedef pair<bool,int>Value2;
const Value1 Zero1(0);
const Value2 Zero2(make_pair(false, 0));
struct Node {
Value1 sum;//??´??°????????????. ?????????????????§??????????????????????????¨????????????????????????????????????.
Value2 lazy; //?????¶????... |
Space Coconut Crab
Space coconut crab
English text is not available in this practice contest.
Ken Marine Blue is a space hunter who travels through the entire galaxy in search of space coconut crabs. The space coconut crab is the largest crustacean in the universe, and it is said that the body length after growth is... | #include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#define REP(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
int main(){ _;
int e;
while(cin>>e,e!=0){
int m=1<<29;
REP(i,101){
if(i*i*i>e) break;
REP(j,1001){
if(i*i*i+j*j>e)break;
m=min(m,i+j+(e-i*i*i-j*j));
... |
Here we describe a typical problem. There are n balls and n boxes. Each ball is labeled by a unique number from 1 to n. Initially each box contains one of these balls. We can swap two balls in adjacent boxes. We are to sort these balls in increasing order by swaps, i.e. move the ball labeled by 1 to the first box, labe... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <map>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const double... |
John is playing a famous console game named 'Tales of Algorithmers.' Now he is facing the last dungeon called 'Blue Forest.' To find out the fastest path to run through the very complicated dungeon, he tried to draw up the dungeon map.
The dungeon consists of several floors. Each floor can be described as a connected ... | #include<stdio.h>
#include<math.h>
#include<vector>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
int X[60][30];
int Y[60][30];
int g2[60][30][30];
int A[60];
int B[60];
int C[60];
double ijk[60][30];
int v[60][30];
int conv[30];
map<pair<int,int>,int> m[60];
double EPS=1e-9;
vector<pair<pair<i... |
Problem E: Laser Puzzle
An explorer John is now at a crisis! He is entrapped in a W times H rectangular room with a embrasure of laser beam. The embrasure is shooting a deadly dangerous laser beam so that he cannot cross or touch the laser beam. On the wall of this room, there are statues and a locked door. The door l... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
using namespace std;
typedef pair<int,int> ii;
int H,W,LP,LP_dir;
bool polluted_room[9][9];
bool visited[9][9];
char room[9][9];
int dx8[] = {+0,+1,+1,+1,+0,-1,-1,-1};//0 1 2 3 4 5 6 7
int dy8[] = {-1,-1,+0,+... |
Mr. A and Mr. B live in an N × M rectangular grid area. Each square is either a road, a wall, or a house. Since this area is famous for the frequent occurrence of molestation damage due to the complicated and intricate roads, the boundary between this area and the outside is completely surrounded by walls and isolated.... | /*
*
*
*/
#include <bits/stdc++.h>
using namespace std;
#define LOG(...) fprintf(stderr, __VA_ARGS__)
//#define LOG(...)
#define FOR(i, a, b) for(int i = (int)(a); i < (int)(b); ++i)
#define RFOR(i, a, b) for(int i = (int)(b - 1); i >= (int)(a); --i)
#define REP(i, n) for(int i = 0; i < (int)(n); ++i)
#define RRE... |
Problem statement
AOR Ika-chan is in a bad mood lately. Apparently, I don't like the ratio of the number of followers to the number of followers of "Ikatta". Currently, AOR Ika-chan has $ A $ followers, $ B $ followers, and a ratio of $ A: B $.
Therefore, AOR Ika decided to increase or decrease the number of follower... | a, b, n = map(int, input().split())
score = abs(a - b)
for x in range(1, n + 1):
for y in range(1, n + 1):
if b * x % y == 0:
new_a = b * x // y
score = min(score, abs(a - new_a))
print(score)
|
O: Chisaki and Picnic
Chisaki, a kindergarten student, decided to bring sweets for the excursion.
There are $ N $ of sweets, and the $ i $ th sweet is priced at $ A_i $ yen and tastes $ B_i $.
Chisaki has $ M $ friends, and the $ j $ th friend cries when she has $ D_j $ or more of sweets priced at $ C_j $ or more.
... | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
//INSERT ABOVE HERE
signed main(){
Int n,m;
cin>>n>>m;
vector<Int> a(n),b(n);
for(Int i... |
Problem
$ N $ people are lined up in a row from left to right. The string $ S $ is prevalent among them.
Each person is happy when the following conditions are met, and not happy when they are not.
* If you have been told more than $ | S | $ characters and the most recent $ | S | $ characters are arranged from oldes... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <functi... |
Find the area of intersection between a circle $c$ and a polygon $g$. The center coordinate of the circle is ($0, 0$).
The polygon $g$ is represented by a sequence of points $p_1$, $p_2$,..., $p_n$ where line segments connecting $p_i$ and $p_{i+1}$ ($1 \leq i \leq n−1$) are sides of the polygon. The line segment conne... | import cmath
import itertools
import math
from collections import defaultdict
INF = float("inf")
PI = cmath.pi
TAU = cmath.pi * 2
EPS = 1e-10
class Point:
"""
2次元空間上の点
"""
# 反時計回り側にある
CCW_COUNTER_CLOCKWISE = 1
# 時計回り側にある
CCW_CLOCKWISE = -1
# 線分の後ろにある
CCW_ONLINE_BACK = 2
# 線分の前にある
CCW_ONLINE_FRONT = -2
#... |
For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $... | import sys
d = {}
input()
for q in sys.stdin:
q = q.split()
if q[0] == '0':
d[q[1]] = q[2]
elif q[0] == '1':
print(d.get(q[1], 0))
else:
if q[1] in d:
del d[q[1]]
|
It's not the rivers that you might be thinking about. The question revolves around the concept of digital rivers.
A digital river is a sequence of numbers where the number
following n is n plus the sum of its digits.
FOR EXAMPLE
12345 is followed by 12360 since 1+2+3+4+5=15 and so
12345 + 15 gives 12360.
similarly ... | #Merging Rivers
#Testing space after all cases even final case
def main():
N = int(raw_input())
counter = 1
while(N != 0):
last_digit = N%10
while(last_digit != 1 and last_digit != 3 and last_digit != 9):
N+=sum([int(i) for i in str(N)... |
Chef has found two very old sheets of paper, each of which originally contained a string of lowercase Latin letters. The strings on both the sheets have equal lengths. However, since the sheets are very old, some letters have become unreadable.
Chef would like to estimate the difference between these strings. Let's ass... | def main():
t = input()
for x in range(0, t):
s1 = raw_input()
s2 = raw_input()
count1 = 0
count2 = 0
for i in range(0, len(s1)):
if s1[i]!=s2[i] and (s1[i]!= '?' and s2[i]!= '?'):
count1 +=1
if s1[i]!=s2[i] or s1[i]=='?' or s2[... |
The Chef is sleeping now. He tries to cook new kind of meals in his dream.
These meals are arranged in a row and numbered from 1 to N consecutively. For each meal i (1<=i<=N) there
is given one integer f(i) which denotes the time needed to cook it. Initially, all meals are uncooked. Each assistant
of The Chef (the... | n, k = map(int, raw_input().split())
times = map(int, raw_input().split())
times = sorted(zip(times, xrange(len(times))), key=lambda x: x[0])
cnt, i = 0, 0
while(i < n):
j = i+1
while(j < n and times[i][0] == times[j][0] and times[j][1] - times[i][1] < k):
j += 1
cnt += 1
i = j
print cnt |
Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants!
Vlad built up his own playlist. The playlist consists of N songs, each has a unique positi... | t=int(raw_input())
def fun(pivot, n,rn):
sm=0
for j in range(rn):
if n[j]<pivot:
sm+=1
sm+=1
print sm
for i in range(t):
rn=int(raw_input())
n=map(int, raw_input().split())
k=int(raw_input())
pivot=n[k-1]
fun(pivot,n,rn) |
Alice has learnt factorization recently. Bob doesn't think she has learnt it properly and hence he has decided to quiz her. Bob gives Alice a very large number and asks her to find out the number of factors of that number. To make it a little easier for her, he represents the number as a product of N numbers. Alice is ... | def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d)
n /= d
d += 1
if n > 1:
primfac.append(n)
return primfac
def hist(s):
d = dict()
for i in s:
if i in d:
d[i] += 1
else:
... |
Chef had constructed 2 buildings - one of height N and another of height M.
He was unhappy, and wanted both buildings to be of the same height.
In one move, he could either add a floor to a building, or remove a floor from a building.
Help him find the minimum number of moves to make the heights equal.
Input
First lin... | t = int(raw_input())
while(t):
s = map(int, raw_input().strip().split(" "))
print abs(s[0]-s[1])
t -= 1 |
Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.
Sonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers ... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int maxn = 1e6 + 5;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
int cnt[maxn], d[maxn];
int main() {
int t, x, y, n, m, ma = 0, f = 0;
scanf("%d", &t);
for (int i = 1; i <= t; i++) {
scanf("%d", &x);
cnt... |
Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.
At every moment of time, every SELL offer has higher price than every BUY offer.
In th... | #include <bits/stdc++.h>
#pragma GCC optimaze("Ofast");
#pragma GCC optimize("unroll-loops")
using namespace std;
const long long mod = 1e9 + 7;
int main() {
srand(time(NULL));
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
set<int> mis1, mis2;
vector<int> we;
long long ans = 1;
for... |
Being bored of exploring the Moon over and over again Wall-B decided to explore something he is made of — binary numbers. He took a binary number and decided to count how many times different substrings of length two appeared. He stored those values in c_{00}, c_{01}, c_{10} and c_{11}, representing how many times subs... | #include <bits/stdc++.h>
using namespace std;
const int maxn = int(2e5) + 100;
const int mod = int(1e9) + 7;
struct binary {
int n;
int a[maxn];
void read() {
char ch;
while ((ch = getchar()) != '0' && ch != '1')
;
a[n = 1] = ch - '0';
while ((ch = getchar()) == '0' || ch == '1') a[++n] = ch... |
There are n cities and m two-way roads in Berland, each road connecting two distinct cities.
Recently the Berland government has made a tough decision to transfer ownership of the roads to private companies. In total, there are 100500 private companies in Berland, numbered by integers from 1 to 100500. After the priva... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
struct Matching {
int n;
vector<int> matchL, matchR, dist;
vector<bool> seen;
vector<vector<int> > ke;
Matching(int n)
: n(n),
matchL(n + 1),
matchR(n + 1),
dist(n + 1),
seen(n + 1, false),
ke(n + ... |
Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.
The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th par... | import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static void solve(FastIO io) {
int N = io.nextInt();
int[] A = io.nextIntArray(N);
HeightMap hts = new HeightMap();
for (int i = 0; i < N; ++i) {
hts.insert(A[i], i);
}
TreeSet<Integer> seen = new TreeSet<>();
seen... |
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of 2. Thanos wants to destroy the... | def solve (l,r,y) :
if (len(y) == 0) :
return a
if (l == r) :
return b*len(y)
c = []
d = []
m = (l+r)//2
for i in y :
if i <= m :
c += [i]
else :
d += [i]
return min(b*(r-l+1)*len(y) , solve(l,m,c) + solve(m+1,r,d))
n,k,a,b = list(... |
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.
Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.
It is easy to prove that any way to trans... | def fun(a,b):
if a % b != 0:
return -1
temp = 0
m = a/b
while m % 2 == 0:
m = m / 2
temp += 1
while m % 3 == 0:
m = m/3
temp += 1
if m == 1:
return temp
else :
return -1
a,b = map(int,input().split())
print(fun(b,a)) |
Vasya has n different points A_1, A_2, … A_n on the plane. No three of them lie on the same line He wants to place them in some order A_{p_1}, A_{p_2}, …, A_{p_n}, where p_1, p_2, …, p_n — some permutation of integers from 1 to n.
After doing so, he will draw oriented polygonal line on these points, drawing oriented s... | #include <bits/stdc++.h>
using namespace std;
namespace Vectors {
struct Vector {
long long x, y;
inline Vector(long long _x = 0, long long _y = 0) { x = _x, y = _y; }
};
inline Vector operator+(const Vector& a, const Vector& b) {
return Vector(a.x + b.x, a.y + b.y);
}
inline Vector operator-(const Vector& a, con... |
This problem differs from the previous problem only in constraints.
Petya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual.
Initially, there were n different countries on the land that is now Berland. Each country had its own territory that was repr... | #include <bits/stdc++.h>
using namespace std;
long long read() {
int f = 1;
long long res = 0;
char ch;
do {
ch = getchar();
if (ch == '-') f = -f;
} while (ch < '0' || ch > '9');
do {
res = res * 10 + ch - '0';
ch = getchar();
} while (ch >= '0' && ch <= '9');
return f == 1 ? res : -res... |
In the year of 3000 travelling around parallel realities became a routine thing. However one has to take into consideration that travelling like that is highly dangerous as you never know beforehand where you're gonna get...
Little Vasya, for instance, found himself in a gaming reality and now he has to successfully c... | #include <bits/stdc++.h>
using namespace std;
template <class A, class B>
A convert(B x) {
stringstream ss;
ss << x;
A ret;
ss >> ret;
return ret;
}
const int oo = ~0u >> 2;
const double eps = 1e-10;
const int mn = 1000, mo = 100000007;
const int fx[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1},
... |
You are given a binary string s (recall that a string is binary if each character is either 0 or 1).
Let f(t) be the decimal representation of integer t written in binary form (possibly with leading zeroes). For example f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0 and f(000100) = 4.
The substring s_{... | #!/usr/bin/env python3
#Educational Codeforces Round 72 C
import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operat... |
A maze is represented by a tree (an undirected graph, where exactly one way exists between each pair of vertices). In the maze the entrance vertex and the exit vertex are chosen with some probability. The exit from the maze is sought by Deep First Search. If there are several possible ways to move, the move is chosen e... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9;
const int MOD = 1e9 + 7;
const int N = 1e5 + 5;
int S[N], T[N], SZ[N], P[N];
vector<int> G[N];
void DFS(int v, int p = 0) {
SZ[v] = 1;
P[v] = p;
for (int u : G[v])
if (u != p) {
DFS(u, v);
SZ[v] += SZ[u];
S[v] += S[u];
... |
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.
Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but ... | n=int(input())
for i in range(n):
x = list(map(int, input().split(" ")))
print(((x[1]%x[0])*((x[1]//x[0]+1)**2))+(((x[1]//x[0])**2)*(x[0]-(x[1]%x[0])))) |
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store... | """
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[:len(s) - 1])
def ... |
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, …, b_n: ... | input()
b = list(map(int,input().split()))
a = list()
sumnum = 0
negnum = 0
for i in range(len(b)):
sumnum += b[i]
a.append(sumnum+abs(negnum))
if b[i]<0:
negnum += b[i]
print(*a) |
You are given a special jigsaw puzzle consisting of n⋅ m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | import java.io.*;
import java.util.*;
public class puzzle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt(),m = sc.nextInt();
if(n==1)
System.out.println("yes");
... |
Let's denote the function f(s) that takes a string s consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows:
1. let r be an empty string;
2. process the characters of s from left to right. For each character c, do the following: if c is a lowercase La... | #include <bits/stdc++.h>
using namespace std;
const int INF = int(1e9);
inline void setmin(int &a, int b) {
if (a > b) a = b;
}
int main() {
string from, need;
cin >> from >> need;
int m = int(from.size());
int n = int(need.size());
vector<int> balance(m);
for (int i = 0; i < m; i++)
balance[i] = (i ?... |
The Committee for Research on Binary Viruses discovered a method of replication for a large family of viruses whose genetic codes are sequences of zeros and ones. Each virus originates from a single gene; for simplicity genes are denoted by integers from 0 to G - 1. At each moment in time a virus is a sequence of genes... | #include <bits/stdc++.h>
using namespace std;
template <class T>
int chkmax(T &a, T b) {
if (b > a) {
a = b;
return 1;
}
return 0;
}
template <class T>
int chkmin(T &a, T b) {
if (b < a) {
a = b;
return 1;
}
return 0;
}
template <class iterator>
void output(iterator begin, iterator end, ostr... |
There are n computers in the company network. They are numbered from 1 to n.
For each pair of two computers 1 ≤ i < j ≤ n you know the value a_{i,j}: the difficulty of sending data between computers i and j. All values a_{i,j} for i<j are different.
You want to separate all computers into k sets A_1, A_2, …, A_k, suc... | #include <bits/stdc++.h>
using namespace std;
const int c = 1502;
long long mod = 998244353, dp[c][c];
int el[c][c], inv[c][c], f[c], db[c], ki[c], n, cnt = 0;
bool v[c], h[c], kesz;
vector<pair<int, int>> sz[c];
vector<int> jo[c];
priority_queue<pair<int, pair<int, int>>> q;
void dfs(int a, int b) {
if (!v[a]) v[a] ... |
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simple... | import java.io.*;
import java.util.*;
import java.math.*;
public class TaskA {
void Run() throws IOException {
long n=ReadLong();
mn=Long.MAX_VALUE;
mx=0;
for(long a=1;a*a*a<=n;++a)
if(n%a==0) {
long t=n/a;
for(long b=a;b*b<=t;++b)
if(t%b==0) {
long c=t/b;
Check((a+1)*(b+2)*(c+2));... |
Berland regional ICPC contest has just ended. There were m participants numbered from 1 to m, who competed on a problemset of n problems numbered from 1 to n.
Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to exactly k consecutive tasks of the proble... | # Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import Byt... |
You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i.
Now you decided... |
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll int t;
cin>>t;
while(t--)
{
ll int n;
cin>>n;
vector<ll int>siz(n),a(n),b(n);
for(ll int i=0;i<n;i++)
{
cin>>siz[i];
}
for(ll int i=0;i<n;i++)
{
cin>>a[i];
}
... |
This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.
To bake a Napoleon cake, one has to bake n ... | import java.io.*;
public class Main {
static StreamTokenizer cin;
static PrintWriter cout;
public static void main(String[] args) throws IOException {
cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
cout = new PrintWriter(new OutputStreamWriter(System.out));
... |
After rejecting 10^{100} data structure problems, Errorgorn is very angry at Anton and decided to kill him.
Anton's DNA can be represented as a string a which only contains the characters "ANTON" (there are only 4 distinct characters).
Errorgorn can change Anton's DNA into string b which must be a permutation of a. ... | from collections import defaultdict
import itertools
import sys
input = sys.stdin.readline
t = int(input())
p = list("ANOT")
q = [0, 1, 2, 3]
d = dict()
for i in range(4):
d[p[i]] = i
for _ in range(t):
a = list(input().rstrip())
n = len(a)
cnt = [0] * 4
x = [[0] * 4 for _ in range(4)]
for i in... |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | n=int(input())
a=list(map(int,input().split()))
s=[0]*5
sum=0
for i in a: s[i]+=1
sum+=s[4]+s[3]
if s[3]<s[1]:
s[1]-=s[3]
s[3]=0
else :
s[3]=0
s[1]=0
sum+=s[2]//2
s[2]%=2
sum+=s[1]//4
s[1]%=4
end=s[2]*2+s[1]
if end>4:sum+=2
elif end>0: sum+=1
print(int(sum))
|
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of h cells numb... | #include <bits/stdc++.h>
using namespace std;
struct Node {
bool fr;
int lb, rb;
Node *lc, *rc;
};
void buildSeg(Node *&p, int l, int r) {
p = new Node;
p->fr = true;
p->lb = l;
p->rb = r;
if (p->lb < p->rb) {
int mid = (p->lb + p->rb) / 2;
buildSeg(p->lc, p->lb, mid);
buildSeg(p->rc, mid + ... |
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec... | import java.util.Scanner;
public class Circus {
static double distance(double x1, double x2, double y1, double y2) {
return Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
}
static double computeAngle(double a, double b, double c) {
return Math.acos((Math.pow(a, 2) + Math.pow(b, 2) - M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.