input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they f... | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
while (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
... |
You are given a grid, consisting of 2 rows and n columns. Each cell of this grid should be colored either black or white.
Two cells are considered neighbours if they have a common border and share the same color. Two cells A and B belong to the same component if they are neighbours, or if there is a neighbour of A tha... | import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
/*
*/
public class Main{
static long MOD=998244353;
public static int check(int a,int b){
if(a==0){
if(b==0){
return 0;
}else {
return 1;
}
}else if(a==1){... |
You are given two integers l and r (l ≤ r). Your task is to calculate the sum of numbers from l to r (including l and r) such that each number contains at most k different digits, and print this sum modulo 998244353.
For example, if k = 1 then you have to calculate all numbers from l to r such that each number is form... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = (119 << 23) + 1;
long long a[20], k;
pair<long long, long long> f[20][1 << 10];
long long pow_[20];
inline long long calc(long long x) {
long long res = 0;
while (x) {
if (x & 1) ++res;
x >>= 1;
}
return res;
}
pair<long long, long long... |
You are given a bracket sequence s consisting of n opening '(' and closing ')' brackets.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()(... | #include <bits/stdc++.h>
using namespace std;
int n, ans;
int prefSuf[1000010][2];
string s;
void getPS(int k, char cl, char op) {
stack<char> st;
bool ok = 1;
for (int i = 1; i <= n; ++i) {
if (!ok) {
prefSuf[i + k * (n - 2 * i + 1)][k] = -1e9;
continue;
}
if (st.empty()) {
if (s[i]... |
You are given an array a_1, a_2, …, a_n.
You need to perform q queries of the following two types:
1. "MULTIPLY l r x" — for every i (l ≤ i ≤ r) multiply a_i by x.
2. "TOTIENT l r" — print \varphi(∏ _{i=l}^{r} a_i) taken modulo 10^9+7, where \varphi denotes Euler's totient function.
The [Euler's totient funct... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void maxtt(T &t1, T t2) {
t1 = max(t1, t2);
}
template <typename T>
void mintt(T &t1, T t2) {
t1 = min(t1, t2);
}
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "URDL";
long long ln, lk, lm;
void etp(b... |
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.
Help Kurt find the maximum possible product of digits among all integers from 1 to n.
Input
The only input line contains the integer n (1 ≤ n ≤ 2⋅10^9).
Output
Print the... | #include <bits/stdc++.h>
using namespace std;
void file() {}
void fast() {
std::ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
}
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
long long setbit(long lo... |
This problem is same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to th... | #include <bits/stdc++.h>
using namespace std;
long long n, x, ans;
map<int, int> a, b;
int main() {
cin >> n;
ans = 1;
for (int i = 1; i <= n; i++) {
cin >> x;
a[x]++;
b[a[x]]++;
if (a[x] * b[a[x]] == i && i != n) {
ans = i + 1;
}
if (a[x] * b[a[x]] == i - 1) {
ans = i;
}
... |
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th... | def main():
from sys import stdin
input = stdin.readline
# input = open('25-B.txt', 'r').readline
n, k = map(int, input().split())
s = input()[:-1]
dp = [[0] * 26 for i in range(n + 1)]
dp[0][0] = 1
for ch in s:
j = ord(ch) - ord('a')
for i in range(n, 0, -1):
... |
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The... | import java.util.Arrays;
import java.util.Scanner;
public class C577 {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long k = in.nextInt();
long a[] = new long[n];
for(int i = 0; i < n; i++){
a[i] = in.nextLo... |
In the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of N planets. Between them, there are M bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached usi... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void cetak(T t) {
cout << t << ')' << endl;
}
template <typename T, typename... V>
void cetak(T t, V... v) {
cout << t;
if (sizeof...(v)) cerr << ", ";
cetak(v...);
}
int MOD = 1e9 + 7;
const int mx = 1e5 + 10;
const int N = 1 << 17;
template <... |
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many ... | import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int as... |
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats... | import java.util.Arrays;
import java.util.Scanner;
public class contest
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0)
{
int a[]=new int[3];
a[0]=sc.nextInt();
a[1]=sc.nextInt();
a[2]=sc.nextInt();
Arrays.sort(a);
if(a[2]<=a[0]+a[1])
... |
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is s... | #include <bits/stdc++.h>
using namespace std;
int main() {
int(n);
scanf("%d", &n);
vector<pair<int, int> > a(n);
vector<pair<int, int> > b(n);
vector<pair<int, int> > c;
vector<pair<int, int> > d;
for (int i = 0; i < (n); ++i) {
scanf("%d%d", &(a[i].first), &(a[i].second));
scanf("%d%d", &(b[i].f... |
You are given a matrix n × m, initially filled with zeroes. We define a_{i, j} as the element in the i-th row and the j-th column of the matrix.
Two cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there... | #include <bits/stdc++.h>
using namespace std;
const int N = 310, M = 2e6 + 10;
template <typename T>
inline void gi(T &x) {
x = 0;
bool f = 0;
char ch = getchar();
while (ch < '0' || ch > '9') f |= (ch == '-'), ch = getchar();
while ('0' <= ch && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
if (f) x = ... |
You are given a string S and an array of strings [t_1, t_2, ..., t_k]. Each string t_i consists of lowercase Latin letters from a to n; S consists of lowercase Latin letters from a to n and no more than 14 question marks.
Each string t_i has its cost c_i — an integer number. The value of some string T is calculated as... | #include <bits/stdc++.h>
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC optimize("no-stack-protector")
const int inf = 0x3f3f3f3f, Inf = 0x7fffffff;
const long long INF = 0x7fffffffffffffff;
const double eps = 1e-10;
template <typename _Tp>
_Tp gcd(const _Tp &a, const _Tp &b) {
return (!b) ? a : gc... |
Bill likes to play with dominoes. He took an n × m board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and no two... | #include <bits/stdc++.h>
using namespace std;
const int M = 2e5 + 5;
int n, m;
char s[M];
long long Ans = 0;
vector<char> Map[M];
int Num(int x, int y) { return (x - 1) * m + y; }
int cnt = 0, gp[M][2], To[M];
vector<int> G[M];
bool notr[M];
void add(int x0, int y0, int x1, int y1) {
G[Num(x0, y0)].push_back(Num(x1, ... |
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so o... | #include <bits/stdc++.h>
using namespace std;
void require(bool cond, const string& message = "Runtime error") {
if (!cond) {
cerr << message << endl;
assert(false);
}
}
int solve(string st, int dig, string& a, string& b) {
vector<int> d1(10), d2;
for (int i = 0; i < int(st.size()); ++i) ++d1[st[i] - '0... |
As Gerald ..., in other words, on a New Year Eve Constantine prepared an unusual present for the Beautiful Lady. The present is the magic New Year snowflake that can make any dream come true.
The New Year snowflake consists of tiny ice crystals, which can be approximately regarded as points on the plane. The beauty of... | #include <bits/stdc++.h>
using namespace std;
struct point {
int x, y;
friend bool operator<(const point &p, const point &q) {
if (p.x != q.x) return p.x < q.x;
return p.y < q.y;
}
void read() { scanf("%d%d", &x, &y); }
point() {}
point(int x, int y) : x(x), y(y) {}
} a[200010], ans[210];
int n;
int... |
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + ... | import java.io.*;
import java.util.*;
public class CF1454F extends PrintWriter {
CF1454F() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
byte[] bb = new byte[1 << 15]; int i, n;
byte getc() {
if (i == n) {
i = n = 0;
try { n = in.read(bb); } ... |
This is an interactive problem.
Homer likes arrays a lot and he wants to play a game with you.
Homer has hidden from you a permutation a_1, a_2, ..., a_n of integers 1 to n. You are asked to find any index k (1 ≤ k ≤ n) which is a local minimum.
For an array a_1, a_2, ..., a_n, an index i (1 ≤ i ≤ n) is said to be... | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class A {
void solve() throws IOException {
int n = nextInt();
int l = 0;
int r = n;
int[] a = new int[n];
if (n == 1) {
ans(0);
return;
}
a[0] = query(0);
... |
Input
The first line of the input contains a single integer N (1 ≤ N ≤ 24). The next N lines contain 5 space-separated integers each. The first three integers will be between 0 and 2, inclusive. The last two integers will be between 0 and 3, inclusive. The sum of the first three integers will be equal to the sum of ... | #include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<unordered_map>
#include<unordered_set>
#include<random>
#include<set>
#include<assert.h>
#include<string>
#include<time.h>
using namespace std;
using lld = long long int;
using ulld = unsigned long long int;
using pii = pair<int, int>;
usin... |
Eshag has an array a consisting of n integers.
Eshag can perform the following operation any number of times: choose some subsequence of a and delete every element from it which is strictly larger than AVG, where AVG is the average of the numbers in the chosen subsequence.
For example, if a = [1 , 4 , 3 , 2 , 4] and ... | #include <bits/stdc++.h>
using namespace std;
template<typename S, typename T>
ostream& operator<<(ostream& out, const pair<S, T> p) {
out << "(" << p.first << "," << p.second << ")";
return out;
}
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v) {
for (auto a: v)
out <<... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | n = int(input())
a = sorted(list(map(int, input().split())))[::-1]
b = sum(a)//2
sum1 = count = 0
for i in a:
sum1+=i
count+=1
if sum1>b:
break
print(count) |
Nick likes strings very much, he likes to rotate them, sort them, rearrange characters within a string... Once he wrote a random string of characters a, b, c on a piece of paper and began to perform the following operations:
* to take two adjacent characters and replace the second character with the first one,
*... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 51123987;
const int maxn = 152;
const int maxs = 5005;
const int maxa = 52;
string st;
int f[maxs][maxa][maxa];
int P[maxn][maxn];
int la[maxn], lb[maxn], lc[maxn];
int Q[maxs];
int n, ret, Qs = 0, Ps = 0;
inline void Add(int &x, int y) {
x += y;
if (x >... |
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".
The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west ... | #include <bits/stdc++.h>
using namespace std;
long long c[1010][1010];
long long rows[1010], cols[1010];
int main() {
int N, M;
scanf("%d%d", &N, &M);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
scanf("%d", &c[i][j]);
}
}
long long row = 1ll << 62, col = 1ll << 62;
for (int j =... |
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the... | s = raw_input
n, m = map(int, s().split())
x = pow(3, n, m)-1
if x<0: x+=m
x%=m
print x |
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen point... | from sys import stdin
a,b=map(int,stdin.readline().split());a+=1
z=[1]+list(map(int,stdin.readline().split()));i,j=1,1;ans=0
r=lambda x:(x*(x+1))//2
while i<a:
if j<=i:j=i
while j<a and abs(z[j]-z[i])<=b:j+=1
if j-i-1>=2:ans+=r(j-i-2)
i+=1
print(ans) |
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | import sys
#sys.stdin = open('in', 'r')
#sys.stdout = open('out', 'w')
def Out(x):
sys.stdout.write(str(x) + '\n')
def In():
return sys.stdin.readline().strip()
def main():
s = str(input())
Map = {}
for word in s:
if word not in Map:
Map[word] = 1
else:
... |
You have a rectangular n × m-cell board. Some cells are already painted some of k colors. You need to paint each uncolored cell one of the k colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and can o... | #include <bits/stdc++.h>
using namespace std;
long long n, m, k, i, j, lim[9][9], lim2[9][9], a[9][9], s, mod = 1e9 + 7;
vector<long long> v;
long long dfs(long long x, long long y, long long cnt) {
if (x > n) return 1;
if (y > m) return dfs(x + 1, 1, cnt);
long long ans = 0, i;
lim[x][y] = lim[x - 1][y] | lim[... |
Fox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:
* To make a "red bouquet", it needs 3 red flowers.
* To make a "green bouquet", it needs 3 green flowers.
* To make a "blue bouquet", it needs 3 ... | a,b,c = map(int,input().split())
max_mix = min(a,b,c)
res = -99999999999999
for i in range (0,min(3,max_mix)+1):
pos = (i+(a-i)//3 + (b-i)//3 + (c-i)//3)
res=max(res,pos)
print(res) |
In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. — Wikipedia.
It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to... | #include <bits/stdc++.h>
using namespace std;
int T, N, A, P, H;
long long max_dist(long long a, long long n, long long p, int had) {
if (a * n < p) {
long long ans = a;
if (had) ans = max(ans, p - a * n);
return ans;
}
long long sum = a * n / p, tmp = a - p % a;
long long first = a * (p / a - 1);
... |
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) — the number of the row and the number of the co... | #include <bits/stdc++.h>
using namespace std;
int main() {
int c1, r1, c2, r2, R, P, K;
scanf("%d%d%d%d", &r1, &c1, &r2, &c2);
if (r1 == r2 && c1 == c2)
R = 0;
else if (r1 == r2 || c1 == c2)
R = 1;
else
R = 2;
K = max(abs(c2 - c1), abs(r2 - r1));
if ((r1 + c1) % 2 == (r2 + c2) % 2) {
if (a... |
This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points.
Manao has developed a model to predict the stock price of a company over the next n days and wants to design a... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const long long inf = -1e18;
long long a[maxn], f[maxn], h[maxn];
long long n, k, ans;
int main() {
ios_base::sync_with_stdio(0);
cin >> n >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) f[i] = h[i] = inf;
f[... |
Mashmokh is playing a new game. In the beginning he has k liters of water and p coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of m vertices. Each vertex of the tree contains a water tank that is empty in the beginning.
The game begins with the fact that Mashmokh chooses... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
long long m, k, p;
vector<long long> g[100010];
long long cost[100010];
long long acum[100010];
long long depth[100010];
long long key;
long long maxD;
long long calc(long long idx, long long mid) {
return ((acum[idx + 1] - acum[mid]) + depth... |
Valera loves his garden, where n fruit trees grow.
This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days,... | #include <bits/stdc++.h>
using namespace std;
bool comp(pair<int, int> p1, pair<int, int> p2) { return p1.first < p2.first; }
int main(int argc, char **argv) {
int n, ret, a, b;
vector<pair<int, int> > vp;
scanf("%d%d", &n, &ret);
for (int k = (0); k < (int)(n); k++) {
scanf("%d%d", &a, &b);
vp.push_bac... |
Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of... | #include <bits/stdc++.h>
using namespace std;
const long double PI = 4 * atan((long double)1);
const long long INF = 1e18;
const long long mod = 1e9 + 7;
const long long N = 2005;
long long n;
long long a[N][N];
vector<vector<long long> > b1(N, vector<long long>(N, 0));
vector<vector<long long> > b2(N, vector<long long... |
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
* Each piece should contain at least l numbers.
* The difference between the maximal and the minimal number on the piece... | import java.util.*;
import java.math.*;
import java.io.*;
public class CF487B {
class RMQ {
int n, lg, sign;
int[][] table;
public RMQ(int nn, int ss) { // -1 for min, 1 for max
sign = ss;
lg = 32 - Integer.numberOfLeadingZeros(n = nn);
table = new int[lg][n];
}
void init(int[] a) {
for(int i = ... |
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | n,m=map(int,input().split())
s="."*(m-1)+"#"
#print(s)
for i in range(n):
if i%2==0:print("#"*m)
else:
print(s)
s=s[::-1] |
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:... | n = raw_input().replace('4','0').replace('7','1')
digits = len(n)
q = int(n,2)
base = 2 ** (digits) - 1
print base + q
|
Volodya and Vlad play the following game. There are k pies at the cells of n × m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border ... | import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int pies=sc.nextInt();
boolean win=false;
for(int i=0;i<pies;i++){
int r=sc.nextInt();
... |
Vasily has recently learned about the amazing properties of number π. In one of the articles it has been hypothesized that, whatever the sequence of numbers we have, in some position, this sequence is found among the digits of number π. Thus, if you take, for example, the epic novel "War and Peace" of famous Russian au... | #include <bits/stdc++.h>
const int N = 1e3 + 2, M = 2.5e4 + 2, K = 52, p = 1e9 + 7;
int dp[K][M][2][2], c[M][10], f[M], dl[M], s[N], s1[K], s2[K];
int n, m, i, j, k, tou = 1, wei, cc, d, ds, x;
bool ed[M];
inline void add(int &x, int y) {
if ((x = x + y) >= p) x -= p;
}
int sol(int a[], int typ) {
int ans = 0;
me... |
Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s... | import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int s = sc.nextInt();
Person[] p = new Person[N];
for(int i = 0; i < N; ++i) {
p[i] = new Person(sc.nextInt(), sc.nextInt());
}
Arrays.sort(p... |
Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are n intersections in the city connected by n - 1 bidirectional roads.
There are m friends of Famil Door living in the city. The i-th friend lives at the intersection ui and works at the intersection v... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, m;
int fa[N][20], size[N], dep[N];
long long sum[N], s[N];
struct Edge {
int t, nxt;
} e[N << 1];
int head[N], cnt;
void add(int u, int v) {
e[++cnt].t = v;
e[cnt].nxt = head[u];
head[u] = cnt;
}
void get_tree(int x) {
dep[x] = dep[fa... |
Alex was programming while Valentina (his toddler daughter) got there and started asking many questions about the round brackets (or parenthesis) in the code. He explained her a bit and when she got it he gave her a task in order to finish his code on time.
For the purpose of this problem we consider only strings cons... | #include <bits/stdc++.h>
using namespace std;
int n, ord1[501000], ord2[501000], SA[501000], LCP[501000], Rank[501000],
C[501000], st[501000], IT[524288 + 524288 + 2];
int Next[501000][20];
set<int> Set;
struct AA {
int a, b;
} w[501000];
char p[501000];
void Suffix_Array() {
int i, MM = max(255, n), LL = 1, cc... |
Bearland has n cities, numbered 1 through n. There are m bidirectional roads. The i-th road connects two distinct cities ai and bi. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).
The distance between cities a and b is defined as the minimum... | #include <bits/stdc++.h>
using namespace std;
const int N = 402;
int n, m, dp[N][N];
vector<int> g[N];
double p[N], mxD[N];
bool v[N];
double solve(int second) {
double ret = 1.0 / n;
for (int d = 1; d <= n; ++d) {
memset(p, 0, sizeof p);
memset(v, 0, sizeof v);
vector<int> cur;
for (int i = 1; i <=... |
Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town.
In Treeland there are 2k universities which are located in different towns.
Recently, the president signed the decree to connect universities by high-speed network.The Min... | import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.Vector;
public class Main {
public static void main(String[] args) throws IOException {
Reader in = new Reader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(... |
You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.
You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such tha... | #include <bits/stdc++.h>
using namespace std;
struct Edge {
int x, y;
};
int f[200011];
vector<int> g[200011];
vector<Edge> ret;
set<int> sset;
set<int> tset;
int n, m;
int s, t, ds, dt;
int find(int x) {
if (f[x] == x) return f[x];
return f[x] = find(f[x]);
}
void unionset(int a, int b) {
int x = find(a), y = ... |
One day, Hongcow goes to the store and sees a brand new deck of n special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store.
This game takes some number of turns to complete. On a turn, Hongcow may do one of t... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const int INF = 2e9;
const long long INF64 = 3e18;
const double EPS = 1e-9;
const double PI = acos(-1);
const long long MD = 1551513443;
const long long T = 25923;
const int N = 100001;
const int M = 16;
const bool DEBUG = 1;
int n, r[M], b[M]... |
Given a rooted tree with n nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest.
The root of a tree in the forest is the node in that tree which does not have a parent. We ... | #include <bits/stdc++.h>
using namespace std;
static const int MOD = 1000000007;
static const long long MODL = 1000000000000000003LL;
static const double eps = 1e-8;
template <class T>
inline T MIN(const T x, const T y) {
return (x < y) ? x : y;
}
template <class T>
inline T MAX(const T x, const T y) {
return (x > ... |
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.
Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova ... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool chkmin(T &a, const T &b) {
return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool chkmax(T &a, const T &b) {
return a < b ? a = b, 1 : 0;
}
const int oo = 0x3f3f3f3f;
const double eps = 1e-14;
const int maxq = 100100;
const in... |
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first... | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
vector<int> G[N];
int alice[N], bob[N];
void dfs(int x, int fa, int *d) {
d[x] = d[fa] + 1;
for (int i = 0; i < (int)G[x].size(); ++i) {
if (G[x][i] != fa) {
dfs(G[x][i], x, d);
}
}
}
int main() {
int n, x;
cin >> n >> x;
for ... |
Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two s... | import java.util.*;
import java.io.*;
public class Main {
static class pair implements Comparable<pair>{
int a;
int b;
int c;
public pair(int a, int b,int c){
this.a=a;
this.b=b;
this.c=c;
}
public int compareTo(pair p){
... |
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at,... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005 * 2;
const long long modulo = 1000000007;
int n;
vector<int> g[MAXN];
bool cycle_used[MAXN];
bool used[MAXN];
vector<int> path;
set<int> st_path;
vector<int> circle_sizes;
int parent[MAXN];
int sizes[MAXN];
void dsu_init() {
for (int i = 0; i < MAX... |
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he ... | #include <bits/stdc++.h>
using namespace std;
int n;
long long x, y, z, ans, tmp;
priority_queue<long long, vector<long long>, greater<long long> > pq;
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%I64d", &tmp);
pq.push(tmp);
}
if (n % 2 == 0) {
x = pq.top();
pq.pop();
... |
Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it c... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
void process(vector<int> &v) {
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
}
int cc(vector<int> v, int l, int r) {
v.insert(v.begin(), l);
v.push_back(r);
assert(v.size() >= 2);
int len = r - l;
int mx = 0;
... |
A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.
In the constructing process m bidirectional ski r... | #include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
int dx[] = {-1, 0, 1, 0, 1, 1, -1, -1};
int dy[] = {0, 1, 0, -1, 1, -1, 1, -1};
int n, m;
struct ufind {
int p[100005], t;
void init() { memset(p, 0, sizeof(p)); }
void set_friend(int i, int j) {
for (; p[t = i]; i = p[i], p[t] = (p[i... |
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one lo... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public ... |
In the NN country, there are n cities, numbered from 1 to n, and n - 1 roads, connecting them. There is a roads path between any two cities.
There are m bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by bus, you c... | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int n, m, q, t, tt, a[N], dfn[N], r[N], dep[N], fa[N][25], f[N][25], qq[N][2],
rt[N], s[N * 20], ls[N * 20], rs[N * 20], ans[N], ff[N];
pair<int, int> e[N];
vector<int> g[N];
void dfs1(int x, int p) {
dfn[x] = ++t;
fa[x][0] = p;
dep[x] = dep[... |
As always, this time again, Suresh and Ramesh went to the tailor for shortening of their father's Pent. And guess what after a bite of Perk they went insane and got it shorten more then what was expected!
This time, Suresh's father wanted to punish him so that he will be busy for sometime, this way Suresh and Ramesh w... | n=int(raw_input())
a=map(int,raw_input().split())
q=int(raw_input())
for i in range(q):
l,r=map(int,raw_input().split())
x=sum(a[(l-1):r])
print x |
Vivek was roaming around in the electronics shop, where he saw a box called as BlackBox. He was intrigued by its function, so he bought it. It's functionality states that for given integer input N ≤ 1000 - it outputs the sum of all the digits in factorial of N (N!).
Now Vivek wants to extend its functionality for la... | '''
# 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!'
from math import factorial
t=input()
while t>0:
t-=1
n=input()
f=factorial(n)
f=str(f)
s=0
for i in f:
s+=int(i)
print s |
Assume the cricket ground to be an infinite grid and there can be more than 11 players in a team. It is known that the batsmen stand at the point (0,0). The field placement follows the following pattern
1st fielder is to be placed at 1 step to the east of batsman.
2nd fielder is to be placed at 2 steps to the north of... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
# your code goes here
import math
def isprime(a):
n=int(math.ceil(math.sqrt(a)))
if a==2 or a==3 :
return True
if a==1:
return False
else:
for i in range(2,n+1):
i... |
Foo was not amongst the most brilliant students of his class. So, he has some pending exams to clear. As the exams are approaching, this time he vowed to pass in all of them. This will only happen if he is not under stress. Foo's stress can be calculated using a simple function called Foo_function which depends upon th... | def f(t,cf):
s,p=0,3
for i in range(4):
s+=cf[i]*(t**p)
p-=1
return s
c=int(raw_input())
while c>0:
c-=1
cf=map(int,raw_input().split(' '))
k=cf[4]
if cf[3]>k:
print "0"
#continue
else:
t=long((k*1.0/cf[0])**(1.0/3.0))
while f(t,cf)>k:
t-=1
print t |
In the city of Madrid, there are two types of roads - Boulevard and Woonerf.
As the people of Madrid are fond of eating, there is exactly one pizzeria on the intersection of each Boulevard and Woonerf.
John decides to take Maria to a pizzeria for a lunch. Maria comes from a rich family while John has a modest backgro... | from sys import stdin
n,m = map(int,stdin.readline().split())
ans = 0
for i in xrange(n):
a = map(int,stdin.readline().split())
x = min(a)
if x > ans:
ans = x
print ans |
Milly and Pranjul are playing a game in which Pranjul will give an index of a chocolate. Then, Milly has to tell him the box number in which that chocolate is in. There are N such boxes and Ci chocolates are there in i^th the box. Description of index is given below :
Suppose there are A1, A2 … AN chocolates in 1^st, ... | def findIndex(val,list,min,max):
if min == max :
return min
avg = (min+max)/2
if val == list[avg]:
return avg
if val > list[avg]:
if val < list[avg+1]:
return avg+1
if avg<max:
return findIndex(val,list,avg+1,max)
return avg
else:
if val > list[avg-1]:
return avg
if avg>min:
return findIn... |
Rahul has set upon the quest for a new logo of his company. He has created the following continuous logo:
/\
/ \
/ /\ \
/ / \ \
/ / /\ \ \
\ \ \/ / /
\ \ / /
\ \/ /
\ /
\/
However, his sister, Rashi, likes the following discontinuous design more
/\
/ \
/ /\ \
/ / \ \
\... | def paintRequire(num):
return (4*(num*(num+1)/2))
def otimumPaint(avaPaint,optPaint):
# print("optimum paint: %s and total paint: %s"%(optPaint,paintRequire(optPaint)))
if(paintRequire(optPaint) <= avaPaint):
return True
else:
return False
tc = int(raw_input())
while tc >0:
x = int... |
Now Flash is in serious trouble. Both Reverse_flash and Zoom are on their way to attack him. But Flash's energy is not enough to face them. Our all time genius Harrison Wells had created a replica mixture and gave it to Flash. Now Flash got 'N' replicas of himself including him. This would have helped him to face them... | from fractions import gcd
n=input()
for i in range(0,n):
x=input()
li=raw_input()
li=map(int,li.split(" "))
li=(set(li))
li=sorted(li)
lcm=1
for j in li:
x=gcd(lcm,j)
lcm=(lcm*j)/x
print(lcm%1000000007) |
Pussycat Sonya has an array A consisting of N integers. She can replace some adjacent elements Ai and Ai+1 by their sum. Sonya can perform this operation any number of times she wants. What is the maximal number of elements with the same value Sonya can get and what are the values it could be?
Input:
The first line of... | class count_num:
def __init__(self):
self.max_count = 1
def recursive(self,row,count,elem,matrix):
self.max_count = max(self.max_count,count)
for r in range(row,k):
for c in range(r,k):
if elem == matrix[r][c]:
self.recursive(c+1,count+1,elem,matrix)
k = int(raw_input().strip())
#line1 = "951 952 9... |
Tom goes out on the day "HOLI" wearing a checked shirt. After having a good time he returns with colors all over his shirt.
He cuts his shirt int a M*M checks, such that M is of the form 2N. Each check on his shirt has got a single color (Exactly one). The jth check on the ith row has got the same color as the (i+j)th... | for t in range(input()):
n=input()
print pow(2,n) |
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
* `0 l r b c`: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c.
* `1 l r`: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353.
Constraints
* 1 \leq N, Q \leq 500000
* 0 \leq a_i, c < 998244353
* 1 \le... | #!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify
import itertools
import math, fractions
import sys, copy
def L(): return sys.stdin.readline().split()... |
There are S sheep and W wolves.
If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.
If the wolves will attack the sheep, print `unsafe`; otherwise, print `safe`.
Constraints
* 1 \leq S \leq 100
* 1 \leq W \leq 100
Input
Input is given from Standard Input in the fol... | import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int sheep = sc.nextInt(), wolf=sc.nextInt();
if(wolf>=sheep) System.out.println("unsafe");
else System.out.println("safe");
}
}
|
Let us consider a grid of squares with N rows and N columns. Arbok has cut out some part of the grid so that, for each i = 1, 2, \ldots, N, the bottommost h_i squares are remaining in the i-th column from the left. Now, he wants to place rooks into some of the remaining squares.
A rook is a chess piece that occupies o... | /**
* author: tourist
* created: 20.11.2019 23:31:54
**/
#undef _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
string to_string(pair<A, B> p);
template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);
template <typename A, type... |
We have a sequence of N integers: x=(x_0,x_1,\cdots,x_{N-1}). Initially, x_i=0 for each i (0 \leq i \leq N-1).
Snuke will perform the following operation exactly M times:
* Choose two distinct indices i, j (0 \leq i,j \leq N-1,\ i \neq j). Then, replace x_i with x_i+2 and x_j with x_j+1.
Find the number of differe... | #include <bits/stdc++.h>
using namespace std;
const int maxn=2000005;
const int mod = 998244353;
int n, m;
long long fact[maxn],inv[maxn];
long long r(int x, int p)
{
long long ret=1,w=x;
while(p)
{
if(p&1)
ret=ret*w%mod;
w=w*w%mod;
p>>=1;
}
return ret;
}
long long b(int x, int y)
{
return fact[x]*(inv... |
You are given a connected graph with N vertices and M edges. The vertices are numbered 1 to N. The i-th edge is an undirected edge of length C_i connecting Vertex A_i and Vertex B_i.
Additionally, an odd number MOD is given.
You will be given Q queries, which should be processed. The queries take the following form:
... | #include<cstdio>
#define K 1000001
#define M 50005
#define N 300003
inline int abv(int x){return x<0?-x:x;}
int gcd(int x,int y){return y?gcd(y,x%y):x;}
int a[M],b[M],c[M],f[N],h,i,j,k,m,n,o,p,q,s[N];bool g[2][K];
int find(int u){return f[u]==u?u:f[u]=find(f[u]);}
inline void merge(int u,int v){if((u=find(u))!=(v=find(... |
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by rem... | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
string s;
int n;
int main()
{
cin>>s;
n=s.size();
if(s[n-1]=='1'||s[0]=='0')
{
cout<<-1<<endl;
return 0;
}
for(int i=0;i<n-1;i++)
{
if(s[i]!=s[n-i-2])
{
cout<<-1<<endl;
return 0;
}
}
int p=1;
for(int i=n-1;i--;)
{
... |
You planned a trip using trains and buses. The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket. Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.
Find the minimu... | #include <bits/stdc++.h>
using namespace std;
int main() {
int s, t, v, w;
cin >> s >> t >> v >> w;
cout << min(s, t) + min(v, w) << endl;
}
|
Square1001 has seen an electric bulletin board displaying the integer 1. He can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the min... | #include<iostream>
using namespace std;
int main()
{
int a,b,x=1,i;
cin>>a>>b;
for(i = 1;i<=a;i++)
x=min(x*2,x+b);
cout<<x<<endl;
}
|
You are given three integers A, B and C. Determine whether C is not less than A and not greater than B.
Constraints
* -100≤A,B,C≤100
* A, B and C are all integers.
Input
Input is given from Standard Input in the following format:
A B C
Output
If the condition is satisfied, print `Yes`; otherwise, print `No`.
... | a,b,c=map(int,input().split());print('YNeos'[a>c or b<c::2]) |
Snuke received a triangle as a birthday present. The coordinates of the three vertices were (x_1, y_1), (x_2, y_2), and (x_3, y_3).
He wants to draw two circles with the same radius inside the triangle such that the two circles do not overlap (but they may touch). Compute the maximum possible radius of the circles.
C... | #include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<string>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<climits>
#include<set>
#define REP(i, n) for(int i = 0;i < n;i++)
#define REPR(i, n) for(int i = n;i >= 0;i--)
#define FOR(i, m, n) for(int i = m;i < n;i++... |
We have a large square grid with H rows and W columns. Iroha is now standing in the top-left cell. She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.
However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there ... | #include <iostream>
#include <cstdio>
#include <cstring>
#define MOD 1000000007
using namespace std;
const int MAXN = 100005;
int fac[MAXN*2],inv[MAXN*2],n,m,a,b;
typedef long long ll;
inline int ksm(int x,int k)
{
int ret=1;
while(k){
if(k&1)ret=(ll)ret*x%MOD;
x=(ll)x*x%MOD;
k>>=1;
}
return ret;
}
inline voi... |
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the fra... | #include <cstdio>
#include <map>
#include <string>
#include <queue>
#include <utility>
#include <iostream>
using namespace std;
typedef pair<int,string> P;
int main(){
int d[4] = {-1,1,-4,4};
map<string,int> ans;
ans["01234567"] = 0;
queue<P> que;
que.push(P(0,"01234567"));
while(que.si... |
Do the following for a four-digit number N consisting of numbers 0-9.
1. Let L be the number obtained as a result of arranging the numerical values of each of the N digits in descending order.
2. Let S be the number obtained as a result of arranging the numerical values of each of the N digits in ascending order.
... | while True:
n = int(raw_input())
if not n: break
s = [("%04d" % n)[i] for i in range(4)]
if len(set(s)) == 1:
print "NA"
continue
cnt = 0
while n != 6174:
cnt += 1
s = [("%04d" % n)[i] for i in range(4)]
n = int("".join(reversed(sorted(s)))) - int("".join(sorted(s)))
print cnt |
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximu... | #include<stdio.h>
int n,k;
int ar[100000];
int x;
int r,l;
int m,t;
int i,j;
int used;
int max(int a,int b){
if(a>=b)return a;
else return b;
}
int main(){
while(1){
scanf("%d %d",&n,&k);
if(n==0&&k==0)return 0;
used=0;
for(i=0;i<n+1;i++)ar[i]=0;
for(i=0;i<k;i++){
scanf("%d",&x);
ar[x]=1;
}
r=1... |
Brave Ponta and his best friend, Brave Gonta, have come to Luida's bar in search of friends to embark on an epic adventure. There are many warriors, monks and wizards in the tavern who are itching to go on an adventure.
Gonta, who is kind-hearted, cared for Ponta and said, "You can choose your friends first."
On the ... | #include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define repp(i, n) rep(i, 0, n)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
using namespace std;
typedef pair<int, int> P;
typedef pair<string, int> psi;
signed main(){
int n;
... |
Vampire
Mr. C is a vampire. If he is exposed to the sunlight directly, he turns into ash. Nevertheless, last night, he attended to the meeting of Immortal and Corpse Programmers Circle, and he has to go home in the near dawn. Fortunately, there are many tall buildings around Mr. C's home, and while the sunlight is blo... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <string.h>
using namespace std;
int main(void)
{
while(true) {
int r,n,y[40],b[41];
double res=500.0;
memset(y, 0, sizeof(y));
memset(b, 0, sizeof(b));
scanf("%d%d", &r, &n);
if(!r && !n) br... |
There is a one-dimensional cellular automaton consisting of N cells. Cells are numbered from 0 to N − 1.
Each cell has a state represented as a non-negative integer less than M. The states of cells evolve through discrete time steps. We denote the state of the i-th cell at time t as S(i, t). The state at time t + 1 is... | #include <bits/stdc++.h>
typedef long long LL;
#define SORT(c) sort((c).begin(),(c).end())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
using namespace std;
LL n,m,a,b,c,t;
vector<vector<LL> > matprod(vector<vector<LL> > mata,vector<vector<LL> > matb)
{
vector<vector<LL> > ans;
ans.res... |
Problem
"Ritsumeikan University Competitive Programming Camp" will be held this year as well. I am very much looking forward to this annual training camp. However, I couldn't stand my desires and splurged before the training camp, so I couldn't afford it. So I decided to use the cheapest Seishun 18 Ticket to get to Mi... | #include <bits/stdc++.h>
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int days[2][12]={
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31},
};
ll cnd[7];
int is_uruu(ll y,int m=-1,int d=-1){
if(y%400LL==0LL)return 1;
if(y%100LL==0LL)return... |
Benjamin Forest VIII is a king of a country. One of his best friends Nod lives in a village far from his castle. Nod gets seriously sick and is on the verge of death. Benjamin orders his subordinate Red to bring good medicine for him as soon as possible. However, there is no road from the castle to the village. Therefo... | #include<cmath>
#include<queue>
#include<cstdio>
#include<algorithm>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
const double EPS=1e-7;
const double INF=1e77;
struct point{
double x,y;
point():x(0),y(0){}
point(double x,double y):x(x),y(y){}
point operator+(const point &a)const{ return point(x+... |
Natsume loves big cats. One day, Natsume was invited by the stray cats she was always close to to go to the mysterious bookstore where the cats were open. When I heard that the bookstore sells books with many pictures of cats, Natsume decided to follow her happily.
I didn't know Natsume, but the bookstore that was tak... | #include "bits/stdc++.h"
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef long long ll;
#define dump(x) cerr << #x << " = " << (x) << endl
#define rep(i,n) for(int i=0;i<(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb push_back
int dist( pii a,pii b){
int y=a.first-b.f... |
Problem statement
There is a permutation with $ 1,2, ..., N $ sorted. I want to select two different numbers $ i $, $ j $ and replace them repeatedly to make them sorted (in the order of $ 1,2, ..., N $). Every time you replace the numbers $ i $, $ j $, you need $ c_ {i, j} $.
Let $ f (p) $ be the minimum cost requir... | #include<iostream>
#include<map>
#include<queue>
#include<vector>
#include<sstream>
#include<functional>
#include<stdio.h>
#include<string>
#include<string.h>
#define INF 2147483647
#define MP make_pair
using namespace std;
string start(int N){
string st[9];
st[0]="0";st[1]="1";st[2]="12";st[3]="123";st[4]="1234";
... |
ICPC World Finals Day 3
On that day, Mr. Tee was investigating the percentage of language used within the team. Unusually, our team does not unify the languages used. Research has shown that two are using C ++ and one is using Java. Now, let's make this a pie chart (pie chart).
pie1.png
Oh, it looks like Java isn'... | #include<cmath>
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
#include<complex>
#include<cassert>
#include<climits>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define inf (INT_MAX)
#define EPS (1e-10)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_B... |
Example
Input
2
()
1 2
Output
1 | #include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#define debug(...) fprintf(stderr, __VA_ARGS__)
using namespace std;
template<class T> void read(T &x) {
x = 0; int f = 1, ch = getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10-'0'+ch;ch=getchar(... |
quiz
You are the director of a quiz show. N people will appear in the quiz show as answerers, each numbered from 1 to N.
Questions will be M + 1 questions, and each question is numbered from 1 to M + 1. Questions are given in numerical order, and points are given only to the person who answers correctly first by pres... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define reps(i, s, n) for (int i = (int)(s); i < (int)(n); i++)
const ll mod = ll(1e9) + 7;
const int INF = int(1e9);
int vector_finder(std::vector<int> vec, int number)
{
... |
D: Is greed the best?
story
In Japan, where there are 1, 5, 10, 50, 100, 500 yen coins, it is known that the number of coins can be minimized by using as many coins as possible when paying a certain amount. ..
If the amount of coins is different from that of Japan, it is not always possible to minimize it by paying ... | #include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
ll A, B;
int main() {
cin >> A >> B;
for (ll i = 1; i <= A; i++) {
ll gaku = ceil(i * (long double)B / (long double)A) * A;
if ((gaku % B) + (gaku / B) > gaku / A) {
cout << gaku << endl;
return 0;
}
}
cout << -1 << endl;
... |
Tashizan Hikizan (Calculation Training)
square1001 You gave E869120 two numbers, $ A $ and $ B $, as birthday presents.
E869120 You decided to use these two numbers for calculation training.
Specifically, E869120 does the following for these numbers exactly $ N $ times:
* Replace $ A $ with $ A-B $ on odd-numbered ... | #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
typedef long long int ll;
map<int,pair<ll,ll>>mp;
int main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
ll n; cin >> n;
ll a,b; cin >> a >> b;
mp[0]=make_pair(a,b);
for(int i=0;i<12;i++){
if(i%2==0){
a=a-b;
... |
$N$ persons visited a restaurant. The restaurant is open from 0 to $T$. The $i$-th person entered the restaurant at $l_i$ and left at $r_i$. Find the maximum number of persons during the business hours.
Constraints
* $ 1 \leq N \leq 10^5 $
* $ 1 \leq T \leq 10^5 $
* $ 0 \leq l_i < r_i \leq T $
Input
The input is gi... | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define MOD 1000000007
#define maxn 100010
void solve() {
int n, t;
cin >> n >> t;
vector<int> v(t + 2);
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
v[a] += 1, v[b] += -1;
}
... |
Aditi recently discovered a new magic trick. First, she gives you an integer N and asks you to think an integer between 1 and N. Then she gives you a bundle of cards each having a sorted list (in ascending order) of some distinct integers written on it. The integers in all the lists are between 1 and N. Note that the s... | for cas in xrange(input()):
n, c, Fc1, Fc2 = input(), 1, 1, 2
while Fc2 <= n:
Fc1, Fc2, c = Fc2, Fc1+Fc2, c+1
print c |
Chef has a sequence of N numbers. He like a sequence better if the sequence contains his favorite sequence as a substring.
Given the sequence and his favorite sequence(F) check whether the favorite sequence is contained in the sequence
Input
The first line will contain the number of test cases and are followed by t... | import sys
t = int(sys.stdin.readline())
for frutta in range(t):
lN = int(sys.stdin.readline())
l1 = map(int,sys.stdin.readline().split())
lF = int(sys.stdin.readline())
l2 = map(int,sys.stdin.readline().split())
sePuede = True
for x in l2:
sePuede = sePuede and (x in l1)
if (sePuede):
print "Yes"
els... |
Did you ever hear about 'Dragon Food' ? Its used to refer to the chocolates bought for your loved ones :). Po offers dragon food to master Shifu, who is a famous cook in the valley of food. In return, Shifu hands over the dragon scroll to Po, which is said to hold the ingredients of the secret recipe. To open the drago... | __author__ = 'deveshbajpai'
def solve(n,a,b):
bin_a = bin(a).split('b')[1]
bin_b = bin(b).split('b')[1]
cn1_bin_a = countNoOf1(bin_a)
cn1_bin_b = countNoOf1(bin_b)
v = n-(cn1_bin_a+cn1_bin_b)
result = ""
if v==0:
result = '1'*n
elif v>0:
result = '1'*(cn1_bin_a+cn... |
Problem description.
JNTU College is conducting an Warmup contest for students to bring out their approaches of solving a problem. A Challenged B that he could not solve the problem.So help B in solving the problem.
Given a series of numbers with only 3 and 4.Your task is very simple i.e.. find the nth... | read = lambda: map(int, raw_input().split())
read_s = lambda: map(str, raw_input().split())
def dfs(x, nums):
if x > 1e10: return
nums.append(x)
dfs(x * 10 + 4, nums)
dfs(x * 10 + 3, nums)
nums = []
dfs(0, nums)
nums.sort()
n, = read()
print nums[n] |
There are K nuclear reactor chambers labelled from 0 to K-1. Particles are bombarded onto chamber 0. The particles keep collecting in the chamber 0. However if at any time, there are more than N particles in a chamber, a reaction will cause 1 particle to move to the immediate next chamber(if current chamber is 0, then ... | a,n,k=map(int,raw_input().split())
for i in range(k):
print (a%(n+1))
a=a/(n+1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.