input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
You are given a rectangular matrix of size n × m consisting of integers from 1 to 2 ⋅ 10^5.
In one move, you can:
* choose any element of the matrix and change its value to any integer between 1 and n ⋅ m, inclusive;
* take any column and shift it one cell up cyclically (see the example of such cyclic shift belo... | from collections import Counter
from sys import stdin
def input():
return(next(stdin))
def main():
n, m = map(int, input().split())
aaa = []
for _ in range(n):
aaa.append([int(a) for a in input().split()])
aaar = list(zip(*aaa))
t = m * n
cost = 0
for i,aa in enumerate(aaar, 1... |
The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2^n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion.
Teams are numbered from 1 to 2^n and will play games one-on-o... | #include <bits/stdc++.h>
using namespace std;
int si();
long long sl();
string ss(int);
char sc();
float sf();
double sd();
long double sld();
template <typename T>
void print(T, char = '\n');
template <typename T, typename... Args>
void print(T, Args...);
void pi(const int&, char = '\n');
void pl(const long long&, cha... |
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | """
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math,cmath,time
start_time = time.time()
################# ---- USER DEFINED INPUT FUNCTIONS ---- #################
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[... |
We define x mod y as the remainder of division of x by y (\% operator in C++ or Java, mod operator in Pascal).
Let's call an array of positive integers [a_1, a_2, ..., a_k] stable if for every permutation p of integers from 1 to k, and for every non-negative integer x, the following condition is met:
(((x mod a_1) m... | #include <bits/stdc++.h>
using namespace std;
const long long M = 998244353;
int t, n, k;
long long st(long long a, long long b) {
if (b == 0)
return 1;
else if (b % 2 == 0) {
long long aa = (a * a) % M;
return (st(aa, b / 2) % M);
} else {
return ((a * st(a, b - 1)) % M);
}
}
int main() {
vec... |
Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.
Ildar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;
import java.util.Random;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.Tre... |
One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:
Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are n trees and m magic mushrooms in the woods: the i-th tree grows at a ... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int x[100005 * 4 + 10005], num[100005 * 4 + 10005], cnt;
double p[100005 * 4 + 10005];
struct Tree {
int w, l, r, h;
} data[100005];
struct Mushroom {
int w, z;
} mush[10005];
int find(int w) {
int g = 0, h = cnt - 1;
while (g <= h) {
int mid = (g + h)... |
John has Q closed intervals of consecutive 2K-bit numbers [l_i, r_i] and one 16-bit value v_i for each interval. (0 ≤ i < Q)
John wants to implement a function F that maps 2K-bit numbers to 16-bit numbers in such a way that inputs from each interval are mapped to that interval's value. In other words: $$$F(x) = v_i, \... | #include <bits/stdc++.h>
using namespace std;
const int MAXQ = 2e5;
vector<int> solve(int K, vector<tuple<uint32_t, uint32_t, int> > V) {
uint32_t mask = (((uint32_t)1) << K) - 1;
vector<int> HT(1 << K), LT(1 << K);
for (auto [l, r, v] : V)
if (v) {
uint32_t lhi = l >> K, llo = l & mask;
uint32_t ... |
Bertown is a city with n buildings in a straight line.
The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise.
Bertown's best sapper knows how to activate... | # ========== //\\ //|| ||====//||
# || // \\ || || // ||
# || //====\\ || || // ||
# || // \\ || || // ||
# ========== // \\ ======== ||//====||
# code
def solve():
a,b = map(int, input().split())
s = str... |
There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates (0, 0). He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding dire... | ///Astalavista Code........~CodeSlayer007
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define Br cout<<endl
#define int long long
#define fe first
#define se second
#define double long double
#define all(v) v.begin(),v.end()
#define allr(v) v.rbegin(),v.rend()
#define PT(x) cout << (x) << endl
#defi... |
You are given two integers l and r in binary representation. Let g(x, y) be equal to the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all integers from x to y inclusive (that is x ⊕ (x+1) ⊕ ... ⊕ (y-1) ⊕ y). Let's define f(l, r) as the maximum of all values of g(x, y) satisfying l ≤ x ≤ y ≤ r.
... | i=int;p=input
N=i(p());L=p();R=p()
l=i(L,2);r=i(R,2);a=R
if l-l%2<r:a=R[:-1]+'1'
if i(L[-1])and l+1==r:a=R
if L==R:a=L
if L[0]<R[0]:a='1'*N
print(a) |
Baby Ehab is known for his love for a certain operation. He has an array a of length n, and he decided to keep doing the following operation on it:
* he picks 2 adjacent elements; he then removes them and places a single integer in their place: their [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR... | import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
static FastScanner in = new FastScanner();
static void solve() {
int n = in.nextInt();
int[] pre = new int[n];
int val = 0;
for (int i = 0; i < n; ++i) {
int x = in.nextInt();
... |
After defeating a Blacklist Rival, you get a chance to draw 1 reward slip out of x hidden valid slips. Initially, x=3 and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are c, m, and p, respectively. There... | a = 0
def dp(c, m, p, v, h, ans):
global a
a += h*p*ans
if (c > 1e-6):
if (m < 1e-6):
dp(c-min(c, v), 0, p+min(c, v), v, h+1, ans*c)
else:
dp(c-min(c, v), m+min(c, v)/2.0, p+min(c, v)/2.0, v, h+1, ans*c)
if (m > 1e-6):
if (c < 1e-6):
dp(0, m-... |
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" — people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy.
Input
The only line of the input c... | #include <bits/stdc++.h>
inline int getInt() {
int s;
scanf("%d", &s);
return s;
}
using namespace std;
int main() {
int ans[5] = {2, 3, 1, 2, 1};
int n = getInt();
printf("%d\n", ans[n - 1]);
return 0;
}
|
In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares.
Bertown has n squares, numbered from 1 to n, they are numb... | #include <bits/stdc++.h>
using namespace std;
class myistream {
static const int maxsize = 1000007, tmpsize = 50;
char *s, *tmp;
char *cur, *upperbound;
FILE *fp;
bool last_read;
bool end_of_file;
bool to_return;
void upd() {
int num = fread(s, sizeof(char), maxsize, fp);
if (num < maxsize) last... |
The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested ... | from math import sqrt
f = lambda: list(map(int, input().split()))
r1 = max(f()[1:])
p1s = f()[1:]
p2 = min(f()[1:])
a, b = f()
print(str(sqrt(max(b * p1 * r1**2 / float(a * p2 + b * p1) for p1 in p1s))))
|
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.
* Current character pointer (CP);
*... | import java.util.*;
import java.io.*;
import java.lang.*;
import static java.lang.System.*;
public class P239b{
static char[] code;
static int[] cnt;
static boolean[] removed;
static void simulate(int l, int r){
int cp = l;
int dp = 0;
char[] tmp = new char[code.length];
for(int i=0; i<code.length; i++) tm... |
You've got a table of size n × m. On the intersection of the i-th row (1 ≤ i ≤ n) and the j-th column (1 ≤ j ≤ m) there is a non-negative integer ai, j. Besides, you've got a non-negative integer k.
Your task is to find such pair of integers (a, b) that meets these conditions:
* k ≤ a ≤ n - k + 1;
* k ≤ b ≤ m -... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 1010;
int n, m, k;
struct matrix {
int n, m;
long long a[MaxN][MaxN];
long long sy[MaxN][MaxN];
long long ty[MaxN][MaxN];
long long sv[MaxN * 2][MaxN];
long long tv[MaxN][MaxN];
long long st[MaxN][MaxN];
void set(int _n, int _m) {
n = _n... |
As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define ... | #include <bits/stdc++.h>
using namespace std;
int a[1000100], c[1000100];
int main() {
int i, j, k, n, m, t;
scanf("%d", &n);
for (i = 1; i <= n; i++) scanf("%d", &a[i]);
scanf("%d", &t);
for (i = 1; i <= t; i++) {
scanf("%d", &k);
a[k] = -fabs(a[k]);
}
m = 0;
for (i = n; i >= 1; i--) {
if (... |
Rainbow built h cells in a row that are numbered from 1 to h from left to right. There are n cells with treasure. We call each of these n cells "Treasure Cell". The i-th "Treasure Cell" is the ai-th cell and the value of treasure in it is ci dollars.
Then, Freda went in the first cell. For now, she can go just k cells... | #include <bits/stdc++.h>
using namespace std;
struct record {
long long x, y;
bool operator<(const record &b) const { return x == b.x ? y > b.y : x < b.x; }
record() {}
record(long long _x, long long _y) {
x = _x;
y = _y;
}
};
vector<long long> p[10010];
long long a[100010];
long long c[100010];
long ... |
In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land.
The river area can be represented by a grid with r rows and exactly two columns — each cell represents a rectangular area. The rows are numbered ... | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solut... |
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.
Inna wants her present to show Dima how great a programmer he is. For that, she is going to g... | #include <bits/stdc++.h>
using namespace std;
string aS = "pushStack";
string aQ = "pushQueue";
string aF = "pushFront";
string aB = "pushBack";
string pS = "popStack";
string pQ = "popQueue";
string pF = "popFront";
string pB = "popBack";
int main() {
ios_base::sync_with_stdio(false);
int qq;
cin >> qq;
vector... |
Sereja loves integer sequences very much. He especially likes stairs.
Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met:
a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.
For example, sequences [1, 2, 3, 2... | from sys import stdin,stdout
from math import factorial as f
inp=stdin.readline
op=stdout.write
n=int(inp())
a=list(map(int,inp().split()))
a.sort()
# op(str(a))
if(len(set(a))==n):
op(str(len(a))+"\n")
a=[str(i) for i in a]
op(' '.join(a[::-1])+"\n")
else:
temp=float('inf')
i=0
rev=[]
while... |
You have a nuts and lots of boxes. The boxes have a wonderful feature: if you put x (x ≥ 0) divisors (the spacial bars that can divide a box) to it, you get a box, divided into x + 1 sections.
You are minimalist. Therefore, on the one hand, you are against dividing some box into more than k sections. On the other hand... | import java.io.*;
import java.util.*;
public class p402a
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println();
int k = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int v = sc.nextInt();
int spac... |
Once Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. "Aha, blacks certainly didn't win!", — Volodya said and was right for sure. And your task is to say whether whites had won or not.
Pieces on the ch... | #include <bits/stdc++.h>
using namespace std;
struct Point {
Point(int _x = 0, int _y = 0) : x(_x), y(_y) {}
int x, y;
};
int table[8][8];
int dirx[4] = {-1, 0, 0, 1};
int diry[4] = {0, -1, 1, 0};
int main() {
Point a[4];
for (int i = 0; i < 4; ++i) {
char x, y;
scanf(" %c%c", &x, &y);
a[i] = Point(... |
Devu wants to decorate his garden with flowers. He has purchased n boxes, where the i-th box contains fi flowers. All flowers in a single box are of the same color (hence they are indistinguishable). Also, no two boxes have flowers of the same color.
Now Devu wants to select exactly s flowers from the boxes to decorat... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
int n;
long long s;
long long f[22];
long long mult(long long a, long long b) { return (a * b) % mod; }
long long add(long long a, long long b) { return (a + b) % mod; }
long long inv(long long n) {
long long ret = 1;
for (int i = 0; (1... |
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty... | #include <bits/stdc++.h>
using namespace std;
int v[100010];
int som[100010];
int t, k;
void pd() {
for (int i = 0; i < 100010 - 5; i++) {
if (i < k)
v[i] = 1;
else {
v[i] = v[i - 1] + v[i - k];
if (v[i] >= 1000000007) v[i] -= 1000000007;
}
}
}
int main() {
cin >> t >> k;
int ans;
... |
You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair (ik, jk) meets the following conditions: ik + jk is an odd number and 1 ≤ ik < jk ≤ n.
In one operation you can perform a sequence of actions:
* ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
struct Dinic {
int N, E;
vector<int> head, dis, ptr;
vector<int> to, prv, cap, flo;
Dinic(int N) : N(N), E(0), head(N, -1), dis(N) {}
void addEdge(int v, int u, int vu, int uv = 0) {
to.resize(E + 2);
prv.resize(E + 2);
cap.resize(... |
Vasya plays one very well-known and extremely popular MMORPG game. His game character has k skill; currently the i-th of them equals to ai. Also this game has a common rating table in which the participants are ranked according to the product of all the skills of a hero in the descending order.
Vasya decided to 'upgra... | #include <bits/stdc++.h>
using namespace std;
struct Add {
long long x, d;
int i;
bool operator<(const Add& p) const {
return (long long)d * p.x > (long long)p.d * x;
}
} a[100005];
int cnt, d[100005], p[100005], sig[100005];
long long x[100005];
vector<pair<int, int>> chain[100005];
int main() {
int i, k... |
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 ... | #include <bits/stdc++.h>
using namespace std;
int main() {
string theWord = "";
int shiftRight = 0;
int shiftDown = 0;
int faces = 0;
int n;
int m;
cin >> n;
cin >> m;
char arr[n][m];
char letter;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> letter;
arr[i][j] ... |
Note the unusual memory limit for the problem.
People working in MDCS (Microsoft Development Center Serbia) like partying. They usually go to night clubs on Friday and Saturday.
There are N people working in MDCS and there are N clubs in the city. Unfortunately, if there is more than one Microsoft employee in night c... | #include <bits/stdc++.h>
bool used[21];
char P[21], way[21];
int n, m, res, U[21], V[21], minv[21], ar[21][21], fri[21][21], sat[21][21];
int hungarian(int i) {
int j, i0, i1, j0, j1, cur, delta;
P[0] = i, j0 = 0;
for (j = 0; j <= m; j++) minv[j] = (1 << 27), used[j] = false;
do {
used[j0] = true;
i0 = ... |
Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k.
Input
The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 1018; - 1018 ≤ a ≤ b ≤ 1018).
Output
Print the required number.
E... | k, a, b = map(int, input().split())
def Do(a, b,):
suma = 0
if a < 0:
if b == 0:
print(-a // k + 1)
if b > 0:
suma = 1
a = -a
if a % k == 0:
if b % k == 0:
suma += b // k + a // k
... |
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.
In the evening Noku is going to take a look at the night sky. He would like to find three d... | f = lambda: list(map(int, input().split()))
d = lambda x, y: (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2
r = lambda x, y, z: (x[0] - y[0]) * (x[1] - z[1]) == (x[1] - y[1]) * (x[0] - z[0])
n = int(input())
t = [f() for i in range(n)]
j = k = -1
b = c = 0
x = t.pop()
for i in range(n - 1):
a = d(x, t[i])
if j < 0 ... |
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.
Spring is starting and the Winter sleep is ... | import sys
window = set()
n, k, q = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
for i in range(q):
a, b = [int(x) for x in input().split()]
if (a == 1):
if (len(window) < k):
window.add(arr[b - 1])
else:
window.add(arr[b - 1])
m = min(window)
window.remove(m)
else:
... |
The famous sculptor Cicasso is a Reberlandian spy!
These is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, P = 1e9 + 7;
int n, m, Q, fc[N], ifc[N], pw[N], len[N];
char s[N];
bool vis[N];
vector<int> f[N];
int inv(int x) { return x == 1 ? x : 1LL * (P - P / x) * inv(P % x) % P; }
int C(int n, int m) {
return n < m ? 0 : 1LL * fc[n] * ifc[n - m] % P * ifc[... |
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)?
The ... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long a;
long long dva = 2;
cin >> a;
if (a % 2 == 1)
cout << (a - 1) / 2;
else {
while (dva * 2 <= a) {
dva *= 2;
}
cout << (a - dva) / 2;
}
return 0;
}
|
There are n casinos lined in a row. If Memory plays at casino i, he has probability pi to win and move to the casino on the right (i + 1) or exit the row (if i = n), and a probability 1 - pi to lose and move to the casino on the left (i - 1) or also exit the row (if i = 1).
We say that Memory dominates on the interva... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
pair<long double, long double> st[4 * N];
int n, q;
template <typename T>
pair<T, T> operator+(const pair<T, T> &a, const pair<T, T> &b) {
pair<T, T> res;
res.first = a.first + b.first * a.second;
res.second = a.second * b.second;
return res;
... |
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere.
Zahar has n stones which are rectangul... | n = int(input())
data = {}
ans = 0
res = 0
pos = 0
ind = []
for i in range(n):
tmp = sorted(list(map(int, input().split())))
if min(tmp) > ans:
ans = min(tmp)
ind = [i, -1]
t = (tmp[1], tmp[2])
if t in data:
third, _ = data[t]
if min([third + tmp[0], tmp[1], tmp[2]]) > ans:
ans = min([third + tmp[0], ... |
Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.
Bash defines a function f0(n), which denotes the number of ways of factoring n into two factors p and q such that gcd(p, q) = 1. In other words, f0(n) is the number of ordered pairs of positive i... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5, MOD = 1e9 + 7;
inline int read() {
char c = getchar();
int x = 0, f = 1;
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x *... |
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result ... | n , k = map(int,input().split())
n = list(str(n))
counter = 0
zero_counter = 0
if n.count('0') >= k :
for i in range(len(n)-1 , -1 , -1):
if (n[i] != '0'):
counter += 1
if (n[i] == '0'):
zero_counter += 1
if (zero_counter == k):
break
print(counter)
else:
print(len(n) - 1) |
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to d... | def dfs(u,cur):
global ans
vis[u]=True
flag=True
for x in vec[u] :
v=x[0]
c=x[1]
if not vis[v] :
dfs(v,cur+c)
flag=False
if flag:
ans=max(cur,ans)
ans=0
vec=[]
vis=[]
i=0
n=int(input())
while(i<n) :
vec.append([])
vis.append(False)
... |
Ivan wants to write a letter to his friend. The letter is a string s consisting of lowercase Latin letters.
Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string s instead of... | #include <bits/stdc++.h>
using namespace std;
int MOD = 1e9 + 7;
int PRIME = 102838201;
int INF = 1e9;
vector<string> &split(const std::string &s, char delim, vector<string> &e) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) e.push_back(item);
return e;
}
int Pow(int a, int b, int Mo) {
i... |
A never-ending, fast-changing and dream-like world unfolds, as the secret door opens.
A world is an unordered graph G, in whose vertex set V(G) there are two special vertices s(G) and t(G). An initial world has vertex set {s(G), t(G)} and an edge between them.
A total of n changes took place in an initial world. In e... | #include <bits/stdc++.h>
using namespace std;
inline void Add(int& x, int y) { x = (x + y) % 1000000007; }
int i, j, k, n, m, p, q, f[60][60], g[60][60], F[60][60], t, inv[60];
int c;
int main() {
scanf("%d%d", &n, &m);
for (i = 2, inv[0] = inv[1] = 1; i <= n; i++)
inv[i] =
1ll * inv[1000000007 % i] * (... |
You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?
D... | #include <bits/stdc++.h>
using namespace std;
const long long inf = 1e9 + 113;
const long long maxn = 1e5 + 113;
int main() {
srand(time(NULL));
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, k;
cin >> n >> k;
vector<int> s1;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
s1.push_back... |
Are you going to Scarborough Fair?
Parsley, sage, rosemary and thyme.
Remember me to one who lives there.
He once was the true love of mine.
Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.
Willem asks his friend, Grick for directions, Grick helped... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class IOtest {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in... |
As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of ... | a , b = map(int , input().split())
names = dict()
for i in range(a):
x , y = input().split()
names[y] = x
for i in range(b):
com = input()
h = com.split()[-1][:-1]
print(f"{com} #{names[h]}")
|
Right now she actually isn't. But she will be, if you don't solve this problem.
You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations:
1. Subtract 1 from x. This operation costs you A coins.
2. Divide x by k. Can be performed... | import java.util.*;
import java.io.*;
import java.lang.*;
public class codeforces
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
//Code starts..
long n = in.nextInt();;
long k = in.nextInt();
long... |
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence a_1, …, a_n. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence b_1, …, b_n using the following rules:
... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAX = 3e5 + 5;
int n;
long long int num[MAX];
stack<int> s[100];
vector<long long> v;
int hb[MAX];
int main() {
ios_base::sync_with_stdio(false);
cin >> n;
long long int x = 0;
for (int i = 1; i <= n; i++) {
cin >> num[i];
... |
Nikita likes tasks on order statistics, for example, he can easily find the k-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number x is the k-th number in increasing order on this segment. In other words, you should find the numb... | #include <bits/stdc++.h>
using namespace std;
struct cplx {
double re, im;
cplx() : re(0), im(0) {}
cplx(double r, double i) : re(r), im(i) {}
cplx operator+(const cplx &rhs) const {
return cplx(re + rhs.re, im + rhs.im);
}
cplx operator-(const cplx &rhs) const {
return cplx(re - rhs.re, im - rhs.im... |
Atul opens a book store and soon he recives his first bill form his wholeseller. To see the bill is correct or not he try to cross check the bill. since he is weak at mathematics he ask you to sove his problem
P is product Q is quantity of product and T is total cost i.e P *Q=T
INPUT
first line of input contains no ... | def getres(p,q,t):
if p*q == t:
print "YES"
else:
print "NO"
n = int(raw_input())
for mem in range(n):
p,q,t = [ int(x) for x in raw_input().split() ]
getres(p,q,t) |
Raju has a crush on girl of his class. He wanted to become close friend of her so he started trying to impress her. She came to know about raju and she also likes him but she is not ready to tell him about her feelings. She gave him a task,she will ask him a chocolate weighs x and raju has to get chocolate of exact wei... | T = int(raw_input())
num = map(int,raw_input().split())
N = len(num)
for i in range(N):
for j in range(i + 1, N):
num.append(num[i] + num[j])
N = int(raw_input())
for i in range(N):
j = int(raw_input())
if j in num:
print "I Like You"
else:
print "I Hate You" |
Its NU-Tech'15 and participants are pouring in large numbers. Its the first day of the fest and everybody has gathered around the registration desks but are confused on receiving a set of very large numbers on the registration slip. They are later told by the volunteers that in order to get their respective registratio... | case = int(raw_input())
lst = []
def num_sum(n):
st = str(n)
ln = len(st)
val = False
total = 0
for i in range(0, ln):
total += int(st[i])
return total
def one_check(num):
val = False
if(len(str(num)) == 1):
val = True
else:
val = False
return val
for i in range(0, case):
num = int(raw_input())
l... |
You are given 3 points - middles of the sides of some triangle. Find coordinates of the triangle vertices.
Input
Input has 3 lines with 2 space-separated reals each - coordinates of the middles of the sides.
Output
Output 3 lines with 2 space-separated reals - coordinates of the triangle vertices. Each number should... | x1, y1 = tuple(map(float, raw_input().split()))
x2, y2 = tuple(map(float, raw_input().split()))
x3, y3 = tuple(map(float, raw_input().split()))
X3 = x1+x2-x3; Y3 = y1+y2-y3;
X2 = x1+x3-x2; Y2 = y1+y3-y2;
X1 = x3+x2-x1; Y1 = y3+y2-y1;
out = [[X1, Y1], [X2, Y2], [X3, Y3]]
out.sort()
for i in out:
print "%.4f %.4f" % (... |
Little Vaishnavi is bored during the vacation which is going on. Being the only little girl in the neighbourhood she did not have any one else to play with. Her parents are so strict that they will not let her out of the house even to see what the kids from the other houses are playing.
So she decided to make a game o... | T=input()
for _ in xrange(T):
[M,K]=map(int,raw_input().split())
ans=0
if(K==0):
print M-1
else:
ans=(K-1)*4 + 5
if(M!=5 and M!=1):
if(K&1==1):
ans+=4-M
elif(K&1==0):
ans+=M-2
else:
if(M==1):
ans=8*K
elif(M==5):
ans=4+8*K
print ans |
Solve the mystery.
Input :
First line contains T - No. of test cases.
For each test case there are two lines.
first line contains N.
Second line contains N space separated integers A[1] to A[N].
Output :
Print answer of the mystery in separate lines.
Constraints :
1 ≤ T ≤ 10
1 ≤ N ≤ 10^5
0 ≤ A[i] ≤ 10... | from sys import stdin
t = int(stdin.readline())
for _ in xrange(t):
n = int(stdin.readline())
a = map(int,stdin.readline().split())
ans = 0
for i in a:
if i%2:
ans += i
print ans |
Alfie was a prisoner in mythland. Though Alfie was a witty and intelligent guy.He was confident of escaping prison.After few days of observation,He figured out that the prison consists of (N × N) cells.i.e The shape of prison was (N × N) matrix. Few of the cells of the prison contained motion detectors.So Alfie planned... | #https://www.hackerearth.com/problem/algorithm/prison-break-5/
answers = []
for t in range(int(raw_input())):
grid = []
n = int(raw_input())
for i in range(n):
grid.append([int(x) for x in raw_input().split()])
count = 0
S = [[[0,0]]]
while S:
currPath = S.pop(0)
pos =... |
You have a long list of tasks that you need to do today. To accomplish task i you need Mi minutes, and the deadline for this task is Di. You need not complete a task at a stretch. You can complete a part of it, switch to another task, and then switch back.
You've realized that it might not be possible to complete all ... | import sys
import math
stdin = sys.stdin
Mid= lambda x : ((x[0] + x[1])>>1)
Lowbit = lambda x : (x&(-x))
used = {}
class Task:
def __init__(self , _d , _m , _index):
self.d = int(_d)
self.m = int(_m)
self.index = int(_index)
def __lt__(self , other):
if (self.d == other.d):
... |
You are a product engineer and would like to improve the quality of duct tapes that your company manufactures. An entire tape can be represented as a single row of N cells. Each cell has its Stickiness factor, which stands for its ability to stick to an object. We say that a tape is a good quality product, if and only ... | def solve(n,k,d,l):
ll = [0]*n
p,j = 0,-1
for i in xrange(n):
if l[i] == 0:
if i - j >= k: return -1
else:
p,j = l[i],i
ll[i] = (p,j)
r = 0
t = 0
for i in xrange(k-1): t += l[i]
i = k-1
while i < n:
if i != k-1: t -= l[i-k]
... |
After Governor's attack on prison, Rick found himself surrounded by walkers. They are coming towards him from all sides. Now, suppose Rick have infinite number of bullets with him. Suppose Rick need 1 bullet to kill each walker (yeah he is good in killing walkers. They need to be shot at head. See, how good he is). Now... | T = int(raw_input());
while T > 0:
T = T-1;
N = int(raw_input());
arr = raw_input().split(' ');
A = map(int, arr);
A.sort();
index = 0;
minute = 1;
myR = 1;
while index < N:
if minute > A[index]:
print 'Goodbye Rick';
print index;
break;
... |
There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.
Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.
Recently, they learned the operation called xor (exclusive OR).
What is xor?
For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n]; //a_max = 10^9
int XORsum = 0;
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
XORsum... |
An SNS has N users - User 1, User 2, \cdots, User N.
Between these N users, there are some relationships - M friendships and K blockships.
For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.
For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i... | #include <bits/stdc++.h>
using namespace std;
#define N 100100
#define SIGMA 26
vector <int> a[N];
vector <int> b[N];
int cnt[N], c[N];
int x, y, n, m, k, i, nr, curr, j;
void df (int nod, int comp){
c[nod] = comp;
++cnt[comp];
for (int it = 0; it < a[nod].size(); ++it)
if (!c[a[nod][it]])
... |
Given is an integer N.
Takahashi chooses an integer a from the positive integers not greater than N with equal probability.
Find the probability that a is odd.
Constraints
* 1 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the probability that a is odd. Your ... | N = input()
print "%.10f"%((N+1)/2/float(N))
|
Your friend gave you a dequeue D as a birthday present.
D is a horizontal cylinder that contains a row of N jewels.
The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.
In the beginning, you have no jewel in your hands.
You can perform at most K operations on... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
There are N slimes lining up in a row. Initially, the i-th slime from the left has a size of a_i.
Taro is trying to combine all the slimes into a larger slime. He will perform the following operation repeatedly until there is only one slime:
* Choose two adjacent slimes, and combine them into a new slime. The new sli... | #include <iostream>
using namespace std;
int n;
long long a[404], b[404], d[404][404];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i], b[i] = b[i - 1] + a[i];
for (int i = 1; i < n; i++) for (int j = 1; j + i <= n; j++) {
d[j][j + i] = 1e18;
for (int k = j; k < j + i; k++) d... |
In the State of Takahashi in AtCoderian Federation, there are N cities, numbered 1, 2, ..., N. M bidirectional roads connect these cities. The i-th road connects City A_i and City B_i. Every road connects two distinct cities. Also, for any two cities, there is at most one road that directly connects them.
One day, it ... | #define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
//template
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(a);i>(b);i--)
#define ALL(v) (v).begin(),(v).end()
typedef long long int ll;
const int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-1... |
A railroad running from west to east in Atcoder Kingdom is now complete.
There are N stations on the railroad, numbered 1 through N from west to east.
Tomorrow, the opening ceremony of the railroad will take place.
On this railroad, for each integer i such that 1≤i≤N-1, there will be trains that run from Station i t... | #include <bits/stdc++.h>
using namespace std;
int main(){
int N;
vector<int> C(510), S(510), F(510);
cin >> N;
for(int i=0; i<N-1; i++) cin >> C[i] >> S[i] >> F[i];
for(int j=0; j<N; j++){
int t = 0;
for(int i=j; i<N-1; i++){
if(t < S[i]){
t = S[i];
} else {
while(t % F[i] ... |
We have a grid with H rows and W columns of squares. Snuke is painting these squares in colors 1, 2, ..., N. Here, the following conditions should be satisfied:
* For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.
* For each i (1 ≤ i ≤ N), the squares painted i... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
Snuke loves working out. He is now exercising N times.
Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.
Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.
Constraints
* 1 ≤ N ≤ 10... | a = 1
for i in range(1,int(input())+1):
a = (a*i)%(10**9+7)
print(a)
|
AtCoDeer the deer is seeing a quick report of election results on TV. Two candidates are standing for the election: Takahashi and Aoki. The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes. AtCoDeer has checked the report N times, and when he c... | n = input()
t, a = 1, 1
for i in range(n):
xs = map(int, raw_input().split())
m = max((t + xs[0] - 1) / xs[0], (a + xs[1] - 1) / xs[1])
t, a = xs[0] * m, xs[1] * m
print t + a
|
I have a sequence defined as follows:
* All even-numbered terms are equal to the previous term multiplied by 2.
* All odd-numbered terms are equal to the previous term divided by 3.
Create a program that reads the first term a of this sequence and outputs the sum s (10) from the first term to the tenth term.
Inp... | import java.io.*;
public class Main {
public static void main(String[] argv) throws IOException {
//*
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String s = in.readLine();
if (s == null) {
break;
... |
In April 2008, Aizuwakamatsu City succeeded in making yakitori with a length of 20 m 85 cm. The chicken used at this time is Aizu local chicken, which is a specialty of Aizu. Aizu local chicken is very delicious, but it is difficult to breed, so the production volume is small and the price is high.
<image>
Relative... | //45
#include<iostream>
using namespace std;
int main(){
for(int q,b,c,cc,qq;cin>>q>>b>>c>>cc>>qq,q;){
int a=0;
int n=b/cc;
int r=b-n*cc;
for(;;){
int nr=r;
int nn=n;
while(nr<c){
nr+=cc;
nn--;
}
if(nn<0||a+1+nn<q||a+1>qq)break;
a++;
n=nn;
r=nr-c;
... |
The educational program (AHK Education) of the Aiz Broadcasting Association broadcasts a handicraft program for children, "Play with Tsukuro". This time I will make a box with sticks, but I would like to see if I can make a rectangular parallelepiped using the 12 sticks I prepared. However, the stick must not be cut or... | #include<bits/stdc++.h>
using namespace std;
int main(){
int a[12];
for(int i = 0;i < 12;i++) cin >> a[i];
sort(a,a+12);
if(a[0] == a[3] && a[4] == a[7] && a[8] == a[11]){
cout << "yes" << endl;
}
else cout << "no" << endl;
return 0;
} |
Railroad Trip
There are N cities in the JOI country, numbered 1, 2, ..., and N, respectively. In addition, there are N − 1 railroads, which are numbered 1, 2, ..., and N − 1, respectively. The railroad i (1 ≤ i ≤ N − 1) connects the city i and the city i + 1 in both directions.
There are two ways to get on the JOI ra... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int p[100000];
int a[100000], b[100000], c[100000];
int t[100000];
int main()
{
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++){
scanf("%d", &p[i]);
p[i]--;
}
for (int i = 0; i < n - 1; i++){
scanf("%d %d %d", &a[i], &b[i], &c[i]);
}
for (in... |
In mathematics, some plain words have special meanings. The word "net" is one of such technical terms. In mathematics, the word "net" is sometimes used to mean a plane shape which can be folded into some solid shape.
The following are a solid shape (Figure 1) and one of its net (Figure 2).
<image>| <image>
---|---
Fi... | #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define FOR(i,a,n) for(ll i=a;i<(ll)(n);i++)
struct Dice {
int b,f,l,r,u,d;
void RollN()
{
// --y;
int buff = d;
d = f;
f = u;
u = b;
b = buff;... |
There is a mysterious planet called Yaen, whose space is 2-dimensional. There are many beautiful stones on the planet, and the Yaen people love to collect them. They bring the stones back home and make nice mobile arts of them to decorate their 2-dimensional living rooms.
In their 2-dimensional world, a mobile is defi... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 100000... |
Eulerian Flight Tour
You have an airline route map of a certain region. All the airports in the region and all the non-stop routes between them are on the map. Here, a non-stop route is a flight route that provides non-stop flights in both ways.
Named after the great mathematician Leonhard Euler, an Eulerian tour is ... | #include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<complex>
#include<bitset>
#include<stack>
#include<unordered_map>
using namespace std;
... |
Making Lunch Boxes
Taro has been hooked on making lunch boxes recently. Taro has obtained a new lunch box recipe book today, and wants to try as many of the recipes listed in the book as possible.
Enough of the ingredients for all the recipes are at hand, but they all are in vacuum packs of two. If only one of them i... | #include <bits/stdc++.h>
using Int = int64_t;
const Int inf = 1LL << 53;
int main() {
for(;;) {
Int n, m;
std::cin >> n >> m;
if( n == 0 && m == 0 ) {
break;
}
auto xss = std::vector<std::string>(n);
for(Int i = 0; i < n; ++i) {
std::string ss;
std::cin... |
A company “ACM Foods” is preparing for opening its chain shop in a certain area, but another company “ICPC Pizza” is also planning to set up its branch shop in the same area. In general, two competitive shops gain less incomes if they are located so close to each other. Thus, if both “ACM Foods” and “ICPC Pizza” went o... | #include<cstdio>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
int main(){
for(int cas=1,n,m;scanf("%d%d",&n,&m),n;cas++){
int t=0;
int win[21]={n};
while(win[m]==0){
int next[21]={};
rep(i,m){
next[i+1]+=win[i]/2;
next[ 0 ]+=win[i]/2;
next[ i ]+=win[i]%2;
}
rep(i,m+1) w... |
Problem F: Farey Sequence
slip likes to look at the numbers. Just looking at the remaining time while downloading the file is enough to kill the time. Such a slip was taught an interesting sequence by a friend. The definition of the sequence is as follows.
The general term is expressed as Fn. Fn is an arrangement of ... | // 6/2
// 2-6-4. 素数のこすう
// エラトステネスの篩
#include <bits/stdc++.h>
#define rep(i, n) for (ll i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int INF = 1e9;
// Sieve of Eratosthenes
// https://youtu.be/UTVg7wzMWQc?t=2774
struct Sieve {
int n;
vector<int> f, primes;
Sieve... |
A permutation of N numbers from 1 to N A1, A2, ……, AN is given. You can perform the operation reverse (i, j) to reverse the order of the numbers in the interval [i, j] (1 ≤ i ≤ j ≤ N) for this permutation. For example, if reverse (2, 4) is applied to [1, 2, 3, 4, 5], it becomes [1, 4, 3, 2, 5]. Calculate how many opera... | #include <cstdio>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
typedef long long LL;
int n;
LL encode(const vector<char> &v){
LL a = 0;
for(int i = 0; i < n; ++i){
a |= (LL)v[i] << (i << 2);
}
return a;
}
vector<char> decode(LL x){
vector<char> v(n);
for(int i = 0; i < n; ++i){... |
After many years of research, Ikta has acquired the ability to predict the future! The time and money he spent on this research was enormous, but it's finally time to be rewarded. To get the money back, Ikta decided to start investing in stocks.
Ikta does not currently own any shares, but owns x yen. He has invested i... | #include <iostream>
using namespace std;
int n,d,p[10][10],ans;
void saiki(int sum,int x,int day,int I){
int f=1;
for(int i=I;i<n;i++)
if(p[day][i]/p[day-1][i]&&x/p[day-1][i]) {
f=0;
saiki(sum+p[day][i],x-p[day-1][i],day,i);
}
if(f)ans=max(ans,sum+x);
}
int main(){
cin>>n>>d>>ans;
for(in... |
Problem statement
It was a month ago. Nikunishi, an elementary school student, did not do his summer vacation homework. Therefore, the independent study decided to investigate the strength of the eggs at home.
In this study, we define the strength of an egg as H when it does not crack when dropped from height H and c... | #include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climit... |
D: Shiritori Compression
problem
Ebi-chan and Kana-chan did a shiritori. Ebi-chan is looking at the memo of the word that came out in Shiritori.
Ebi-chan wants to remove redundant continuous subsequences from this word sequence w_1, w_2, ..., w_N until they no longer exist. The redundant continuous subsequence that ... | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;
template<typename A,typename B>inline ... |
Problem
There are $ 2 $ teams, Team UKU and Team Ushi. Initially, Team UKU has $ N $ people and Team Uku has $ M $ people. Team UKU and Team Ushi decided to play a game called "U & U". "U & U" has a common score for $ 2 $ teams, and the goal is to work together to minimize the common score. In "U & U", everyone's phys... | #include <iostream>
using namespace std;
int main(){
long long N, M;
cin >> N >> M;
long long N_ = N, M_ = M;
// if(N > 2*M || M > 2*N){
//cout << 0 << endl;
//return 0;
//}
int ans = 0;
long long n = 2*N, m = 2*M;
while(n > 0 && m > 0){
m -= N;
if(m <= 0) break;
++ans;
M = min(m,M)... |
A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).
<image>
Fig. 1
A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertic... | import sys
n = int(input())
nodes = [[-1, None, None] for _ in range(n)]
depths = [None for _ in range(n)]
for _ in range(n):
nid, k, *children = list(map(int, sys.stdin.readline().split()))
if k > 0:
nodes[nid][1] = children[0]
children.append(None)
for i in range(k):
cid = children... |
A state with $n$ flags of ON or OFF can be represented by a sequence of bits where $0, 1, ..., n-1$ th flag corresponds to 1 (ON) or 0 (OFF). The state can be managed by the corresponding decimal integer, because the sequence of bits is a binary representation where each bit is 0 or 1.
On the other hand, a mask is a s... | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
//INSERT ABOVE HERE
signed main(){
using BS = bitset<64>;
int n;
cin>>n;
vector<BS> ms(n);
for(int i=0;i<n;i++){
int k;
cin>>k;
for(int j=0;j<k;j++){
int x;
cin>>x;
ms[i].s... |
Knights' tournaments were quite popular in the Middle Ages. A lot of boys were dreaming of becoming a knight, while a lot of girls were dreaming of marrying a knight on a white horse.
In this problem we consider one of these tournaments.
Let's us call a tournament binary, if it runs according to the scheme described... | import sys
def inverseMod(a, b):
MOD = 1000000009
if a == 1:
return b
div = MOD / a + 1
return inverseMod((a * div) % MOD, (b * div) % MOD)
def solve():
K, MOD = int(raw_input()), 1000000009
if K == 1:
print '2'
print '2'
else:
half = 1<<(K-1)
for _ ... |
Little Chief loves math. Most of all, he loves equations. He can solve any equation in the whole world. Recently he found one interesting and easy equation
x1^d+x2^d+x3^d ≡ m (mod N)
Where x1, x2 and x3 are non negative integer numbers.
But, as always, this was easy enough for him and he solved it in just a few seconds... | def fn():
mod = 1000000007
u,d,m,n = map(int,raw_input().split())
a = []
for i in range(3):
t = []
for j in range(n):
t.append(0)
a.append(t)
for i in range(n):
t1 = pow(i,d,n)
t2 = (u-i)/n + 1
t2 %= mod
a[0][... |
Nobody knows, but N frogs live in Chef's garden.
Now they are siting on the X-axis and want to speak to each other. One frog can send a message to another one if the distance between them is less or equal to K.
Chef knows all P pairs of frogs, which want to send messages. Help him to define can they or not!
Note : Mo... | def f(x):
return x[1]
n, k, p= map(int, raw_input().split())
a = map(int, raw_input().split())
l = [] #index, position, max_dist
for i in range(n):
l.append([i, a[i], 0])
l = sorted(l, key = f, reverse = True)
#print l
l[0][2] = l[0][1] + k
for i in range(1,n):
if (l[i-1][1] - l[i][1] <= k):
l[i][2]... |
Mike is given an undirected graph G of N vertices and M edges. A non-negative integer Xi is assigned to the i'th vertex of G, for 1 ≤ i ≤ N.
Mike was asked to assign labels to each edge of the graph so that the following condition is satisfied:
Let's suppose that the j'th edge of G connects vertices Uj and Vj. Th... | import sys
x = lambda : [int(n) for n in sys.stdin.readline().rstrip().split()]
def bfs(i, mode):
stack = [i+1]
while len(stack)!=0:
current = stack.pop()
if graph.has_key(current):
for node in graph[current]:
val = graph[current][node]^answer[current-1]
... |
DevuLand is a very strange place. There are n villages in it. Some of the villages are occupied by dinosaurs while the remaining ones by villagers.
You are given the information of DevuLand
by an array D of size n. If D[i] is non-negative, it means that there are D[i] villagers in that village.
Otherwise, it means t... | # Devajit Asem
# PRLADDU
t = int(raw_input())
def display(a):
for i in a:
print i,
print
for i in range(t):
n = int(raw_input())
D = map(int,raw_input().split())
c=0
k=0
for i in xrange(n):
c+=D[i]
k+=abs(c)
print k |
At the end of a busy day, The Chef and his assistants play a game together. The game is not just for fun but also used to decide who will have to clean the kitchen. The Chef is a Game Master, so his concern is how to manage the game but not how to win the game like his assistants do.
The game requires players to find... | n=input()
for x in range(n):
b=raw_input()
c=b.split()
for y in range(len(c)):
c[y]=int(c[y])
pos=c[1]
for y in range(c[2]):
d=raw_input()
e,f=d.split()
e=int(e)
f=int(f)
if(e<=pos and f>=pos):
pos=e+f-pos
print pos |
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from ... | #include <bits/stdc++.h>
using namespace std;
int ddx[] = {1, 0};
int ddy[] = {0, 1};
int n, m, peso;
vector<long long int> aa, bb;
vector<double> vec;
double ans = DBL_MAX;
bool can(double atual) {
double a = peso + atual;
bool at = false;
for (int i = 0; i < int(vec.size()); i++) {
a = (a - (a / vec[i]));
... |
Vasya has two arrays A and B of lengths n and m, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, ... | /*
*
* @author Mukesh Singh
*
*/
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
@SuppressWarnings("unchecked")
public class Main {
//solve test cases
void solve() throws Exception {
//int T = in.nextInt();
//for(int tid = 1; tid <= T; ++tid)
solveT();
}
void solv... |
Let's call the following process a transformation of a sequence of length n.
If the sequence is empty, the process ends. Otherwise, append the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of all the elements of the sequence to the result and remove one arbitrary element from t... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, cnt = 0;
scanf("%d", &n);
if (n == 3)
printf("1 1 3");
else {
int x = n;
for (i = 1; x > 3; i <<= 1) {
int y = x - x / 2;
x /= 2;
for (j = 1; j <= y; ++j) printf("%d ", i), cnt++;
}
if (x == 3) printf("... |
Sonya had a birthday recently. She was presented with the matrix of size n× m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right.
Let's call a submatrix (i_1, j_1, i_2, j_2) (1≤ i_1≤ i_2≤ ... | #include <bits/stdc++.h>
using namespace std;
inline int gi() {
int x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = (x << 3) + (x << 1) + ch - 48;
ch = getchar();
}
return x * f;
}
template <typename T>
inline boo... |
This problem differs from one which was on the online contest.
The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.
The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other wo... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
scanf("%d", &n);
int a[n + 10];
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
scanf("%d", &m);
int b[m + 10];
for (int i = 1; i <= m; i++) scanf("%d", &b[i]);
int local, ans = 0, indx;
int Max[m + 10];
memset(Max, 0, sizeof Max)... |
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are n solutions, the i-th of them should be tested on a_i tests, testing one solution on one test takes 1 second. The solutions are judged in the order from 1 to n. There are k testing p... | #include <bits/stdc++.h>
using namespace std;
int arr[1010];
bool interest[1010];
int main() {
int n, i, j, k, x, y, ans, curr, temp, m, rose = 0;
scanf("%d %d", &n, &m);
for (i = 1; i <= n; i++) {
scanf("%d", &arr[i]);
}
double systest = 0.00;
int cek = round(systest);
pair<int, int> p[m + 5];
for ... |
There are n stones arranged on an axis. Initially the i-th stone is located at the coordinate s_i. There may be more than one stone in a single place.
You can perform zero or more operations of the following type:
* take two stones with indices i and j so that s_i ≤ s_j, choose an integer d (0 ≤ 2 ⋅ d ≤ s_j - s_i)... | #include <bits/stdc++.h>
using namespace std;
int m, n, k;
long long t[300001];
pair<long long, int> s[300001];
vector<pair<int, long long> > st;
vector<pair<pair<int, int>, long long> > ans;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
for (int i = 1; i <= n; i++) {... |
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class PigWolf implements Runnable {
int n;
int m;
private void solve() throws IOException {
n = nextInt();
m = nextInt();
char[][] a = n... |
Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:256000000")
using namespace std;
const long double PI = 3.14159265358979323846;
const long double eps = 1e-5;
const int INF = numeric_limits<int>::max();
const long long LINF = numeric_limits<long long>::max();
const long long mod = 1000 * 1000 * 1000 + 7;
vector... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.