input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).
You've got two strings — s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at... | #include <bits/stdc++.h>
using namespace std;
vector<int> LP(const string& S, const string& T) {
const int M = int((T).size());
vector<int> last_pos_in_T(26, 0);
const int N = int((S).size());
vector<int> res(N, -1);
for (int i = 0, j = 0; i < N; ++i) {
int ch_id = S[i] - 'a';
if (j < M && S[i] == T[j... |
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"
Dr. Suess, How The Grinch Stole Christmas
Christmas celebrations are coming to Whoville. Cindy Lou Who and her paren... | #include <bits/stdc++.h>
using namespace std;
int n, t, p, sp[500000 + 10], sol[500000 + 10];
char s[500000 + 10];
bool isOK(int x) {
sp[0] = x;
for (int i = 1; i <= n; i++) sol[i] = 0;
for (int i = 1; i <= n; i++) {
if (s[i] == '.')
sp[i] = sp[i - 1];
else if (s[i] == 'H')
sp[i] = sp[i - 1] -... |
Dima came to the horse land. There are n horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3.
Right now the horse land is going through an election campaign. So the horse... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 300005;
vector<int> adj[maxn];
int deg[maxn];
int c[maxn];
void dfs(int u, int p, int col) {
c[u] = col;
for (int v : adj[u]) {
if (v == p || c[v] != -1) continue;
dfs(v, p, !col);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);... |
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold pe... | #include <bits/stdc++.h>
using namespace std;
long long n, k;
long long c1, c2;
long long cache[52][52][2][201];
long long cache1[52][52][2][201];
long long mod = 1e9 + 7;
long long fact[300005];
long long inv(long long x) {
long long r, y;
for (r = 1, y = mod - 2; y > 0; x = (x * x) % mod, y /= 2)
if (y % 2 ==... |
At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, becaus... | #include <bits/stdc++.h>
using namespace std;
long long fast_power(long long val, long long deg, long long mod = 1000000007) {
if (!deg) return 1 % mod;
if (deg & 1) return fast_power(val, deg - 1, mod) * val % mod;
long long res = fast_power(val, deg >> 1, mod);
return (res * res) % mod;
}
long long MMI(long l... |
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will co... | a, b = map(int, raw_input().split())
cnt = a / b
a %= b
while a:
cnt += b / a
b %= a
a, b = b, a
print cnt |
Sereja is interested in intervals of numbers, so he has prepared a problem about intervals for you. An interval of numbers is a pair of integers [l, r] (1 ≤ l ≤ r ≤ m). Interval [l1, r1] belongs to interval [l2, r2] if the following condition is met: l2 ≤ l1 ≤ r1 ≤ r2.
Sereja wants to write out a sequence of n interva... | #include <bits/stdc++.h>
using namespace std;
const int NMAX = 321, MOD = 1e9 + 7;
int64_t dp[2][NMAX][NMAX];
int64_t tdp[2][NMAX][NMAX];
int main() {
ios::sync_with_stdio(false);
int n, m, x;
cin >> n >> m >> x;
if (n > m) {
cout << "0\n";
return 0;
}
dp[0][0][0] = tdp[0][0][0] = 1;
for (int i = ... |
Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.
The morning has ... | import java.util.*;
public class inna390 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n,x,y, xmax=-1,ymax=-1;
int[] xarray = new int[101], yarray = new int[101];
Scanner in = new Scanner(System.in);
n= in.nextInt();
while(n-- > 0) {
x = in.nextInt();
y = in.next... |
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the ... | import java.util.Scanner;
public class Kicker {
static int p1[], p2[], p3[], p4[];
static void init() {
p1 = new int[2];
p2 = new int[2];
p3 = new int[2];
p4 = new int[2];
Scanner sc = new Scanner(System.in);
String[] line = sc.nextLine().split(" ");
p1[0] = Integer.parseInt(line[0]);
p1[1] = Inte... |
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long N, X;
cin >> N >> X;
vector<int> C;
C.resize(N);
for (int i = 0; i < N; ++i) {
cin >> C[i];
}
sort(C.begin(), C.end());
long long res = 0;
for (int i = 0; i < N; ++i) {
res += C[i] * X;
X = max(1LL, X - 1);
}
cout << ... |
Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties:
* for all x <image> the following inequality holds l ≤ x ≤ r;
* 1 ≤ |S| ≤ k;
* lets denote the i-th... | #include <bits/stdc++.h>
using namespace std;
long long f(vector<long long> nums) {
long long k = 0;
for (auto i : nums) k ^= i;
return k;
}
void doo(long long l, long long r, long long k) {
if (r - l + 1 >= 5) {
if (k >= 4) {
if (l % 2) ++l;
cout << "0\n4\n";
for (int(i) = 0; (i) < (4); (... |
How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: d-sorting. This sorting is applied to the strings of length at least d, where d is some positive integer. The characters of the string are so... | #include <bits/stdc++.h>
using namespace std;
char s[1000005], t[1000005];
int n, k, d;
int P[1000005], Ans[1000005], G[1000005];
void solve() {
scanf("%d %d", &k, &d);
for (int i = 0; i < n; ++i) P[i] = Ans[i] = i;
int u = 0;
for (int i = 0; i < d; ++i)
for (int j = i; j < k; j += d) P[u++] = j;
P[n] = P... |
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one can... | import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import... |
After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not ne... | //package codeforcesround311;
import java.io.*;
import java.util.*;
public class q2 {
static ArrayList<Integer> g[];
static boolean[] a;
static int[] depth;
static int[] count;
public static void main(String[] args) throws Exception
{
BufferedR... |
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Robot {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in... |
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin... | #include <bits/stdc++.h>
using namespace std;
using LL = int64_t;
using pii = pair<int, int>;
const double PI = 2 * asin(1);
struct Edge {
int w, id, flag;
Edge(int w = 0, int id = 0, int flag = 0) : w(w), id(id), flag(flag) {}
bool operator<(const Edge &e) const {
if (w == e.w) return flag > e.flag;
retu... |
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes ... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const long long mod = 1000000007;
int A[N], rmq[N][25], getL[N];
void go(int n) {
for (int i = 0; i < n; i++) rmq[i][0] = i;
for (int i = 1; i < N; i++) getL[i] = log2(i);
for (int j = 1; (1 << j) <= n; j++) {
for (int i = 0; i + (1 << j) -... |
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider... | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* @auther chao
* @date 16/3/27
*/
public class CF0327 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Map<Integer , Integer> xMap = new HashMap<>();
... |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | lin1 = input().split()
h = input().split()
for i in range(len(h)):
h[i] = int(h[i])
n_friends = int(lin1[0])
h_fence = int(lin1[1])
total = 0
for i in h:
if i > h_fence: total += 2
else: total += 1
print(total) |
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo... | import java.util.Arrays;
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
String linea = console.nextLine();
String[] arr1 = linea.split(" ");
int[] arr2 = new int[arr1.length];
for (i... |
Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.
Initially Irina... | #include <bits/stdc++.h>
using namespace std;
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c)) v.push_back(move(x));
return v;
}
void err(vector<string>::iterator it) {}
template <typename T, typename... Args>
void err(vector<string>::it... |
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.
Vladik knows n airports. All the airports are located on a straight line. Each airport has uni... | import java.io.*;
import java.util.*;
public class A {
void solve() {
int n = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
String s = in.next();
char finCompany = s.charAt(b-1);
char startCompany = s.charAt(a-1);
if (finCompany == startCompany){
... |
Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alpha... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 5;
const int MOD = 1e9 + 7;
int sum[MAXN][30], M[MAXN][MAXN], dp[MAXN], maxx[30], dp2[MAXN];
string a;
int main() {
ios::sync_with_stdio(false);
int n;
int i, j, k;
int ans = 0;
cin >> n;
cin >> a;
for (i = 1; i <= 26; i++) cin >> maxx[i... |
The Easter Rabbit laid n eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
* Each of the seven colors should be used to paint at least one egg.
* Any four eggs lying ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
string s = "ROYGBIV";
int i = 0;
while (t--) {
cout << s[i++];
if (i == 7) i = 3;
}
return 0;
}
|
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const double g = 10.0, eps = 1e-9;
const int N = 1000 + 10, maxn = 16, inf = 9999999;
int n;
bool query(int x, int y) {
if (x < 0 || y > n) return 0;
cout << 1 << " " << x << " " << y << endl;
fflush(stdout);
s... |
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n ... | n = int(input())
text = input()
ll = list(text.split())
num = []
for i in range(len(ll)):
num.append(sum(1 for c in ll[i] if c.isupper()))
print(max(num))
|
It is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number ai written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a numbe... | #include <bits/stdc++.h>
using namespace std;
long long n, a[2005], b[2005], n1, n2, f[2][2005][13], g[2][2005][13],
c[2005][2005], pw[2005], t;
long long calc(long long n, long long m) {
if (m == 0) return (n == 0);
return pw[n] * c[n + m - 1][m - 1] % 998244353;
}
signed main() {
pw[0] = 1;
c[0][0] = 1;
... |
Only T milliseconds left before the start of well-known online programming contest Codehorses Round 2017.
Polycarp needs to download B++ compiler to take part in the contest. The size of the file is f bytes.
Polycarp's internet tariff allows to download data at the rate of one byte per t0 milliseconds. This tariff is... | #include <bits/stdc++.h>
using namespace std;
constexpr int N = 1e7 + 5;
constexpr long long LINF = 1e18;
int main() {
ios::sync_with_stdio(false);
long long f, t, t0;
cin >> f >> t >> t0;
long long a1, t1, p1;
cin >> a1 >> t1 >> p1;
long long a2, t2, p2;
cin >> a2 >> t2 >> p2;
auto bs = [&](long long d... |
Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.
At each step he selects... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9, MOD = INF + 7;
const int N = 22, M = (1 << N);
int adj[N], neigh[M];
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int v, u;
cin >> v >> u;
v--, u--;
a... |
You are given a sequence of positive integers a1, a2, ..., an.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a s... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cerr.tie(nullptr);
int n;
cin >> n;
list<int> a;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.push_back(x);
}
auto it = a.begin();
while (it != --a.end(... |
You're given Q queries of the form (L, R).
For each query you have to find the number of such x that L ≤ x ≤ R and there exist integer numbers a > 0, p > 1 such that x = ap.
Input
The first line contains the number of queries Q (1 ≤ Q ≤ 105).
The next Q lines contains two integers L, R each (1 ≤ L ≤ R ≤ 1018).
Ou... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class sad_powers {
static long root(long a) {
long high = 1000000000;
long low = 0;
long ans = 0;
while (low <= high) {
long mid = (high + low) / 2;
... |
Grisha come to a contest and faced the following problem.
You are given an array of size n, initially consisting of zeros. The elements of the array are enumerated from 1 to n. You perform q operations on the array. The i-th operation is described with three integers l_i, r_i and x_i (1 ≤ l_i ≤ r_i ≤ n, 1 ≤ x_i ≤ n) a... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
i... |
Russian translation
Let's consider some weird country with N cities and M bidirectional roads of 3 types. It's weird because of some unusual rules about using these roads: men can use roads of types 1 and 3 only and women can use roads of types 2 and 3 only. Please answer the following very interesting question: what ... | import collections
import heapq
def mst(graph, n):
total = 0
seen_m = set([1])
seen_f = set([1])
q = graph[1]
heapq.heapify(q)
while q:
used = False
kind, node = heapq.heappop(q)
# if node in seen_m and node in seen_f: continue
if kind in (-1, -3) and node not in... |
Big P has recently become very famous among girls .
Big P goes to a party and every girl present there wants to dance with him. However, Big P cannot dance with all of them, because there are many of them.
Now if a girl gets to dance with Big P, she considers herself to be " 1-Lucky ". A person that dances with some... | (n, m) = map(int, raw_input().split())
list = [-1] * n
list[0] = 0
tree = []
for i in range(n):
tree.append([])
for i in range(m):
(a, b) = map(int, raw_input().split())
tree[a].append(b)
tree[b].append(a)
queue = [0]
while(queue):
current = queue.pop(0)
for next in tree[current]:
if list[next] < 0:
list[ne... |
This task is very simple.You are given two string A and B and you have to find how many times you can form string B from string A. You are only allow to delete some character from string A and Change postion of characters .You are not allow to use same index character of A two times in the same string to form string B.... | noc = input()
mod = 1000000007
from collections import Counter
while noc:
noc-=1
count = 1
st1 = raw_input()
st2 = raw_input()
cst1 = Counter(st1)
for x in xrange(len(st2)):
count = ((count%mod)*(cst1[st2[x]]%mod))%mod
cst1[st2[x]]-=1
print count |
Statement: Write a code to display all the non-prime numbers upto N.
Input: Only the value of N.
Output: The numbers which are not prime upto N (including N), each in a new line.
Constraints: 1 ≤ N ≤ 10^4
SAMPLE INPUT
25
SAMPLE OUTPUT
4
6
8
9
10
12
14
15
16
18
20
21
22
24
25
Explanation
In the above case, input ... | def sieve(n):
primes=[]
multiples=set()
for i in xrange(2,n+1):
if i not in multiples:
primes.append(i)
multiples.update(range(i*i, n+1,i))
return primes
n=input()
lst=sieve(n)
for i in xrange(2,n+1):
if i not in lst:
print i |
Taru and Chandu both are getting bored. So Taru thinks to play a game and he gives a number to Chandu and asks him to find the number of combinations formed by divisors in form of prime.
For example:-
For N = 36 divisor in form of prime are ( 2 , 2 , 3 , 3 )
Number of combinations formed by prime divisor of 36 a... | from itertools import combinations
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
if __name__ == '__main__':
t=int(raw_input())
while... |
PIET's EC department students are working on a set of conductors to create a circuit with maximum resistance.
The simplest circuit consists of a single conductor (i.e., a single piece of wire). Each such circuit is labeled using the string "X".
Students are using two different ways to connect two simpler circuits int... | import sys,string,re
for __ in range(input()) :
circuit = raw_input()
val = list(map(int,sys.stdin.readline().split()))
stack , top , bptr , fptr = [] , -1 , len(val)-1 , 0
for i in range(len(circuit)-1,-1,-1) :
if circuit[i] == 'X' :
stack.append(1)
elif circuit[i] == 'A' :
... |
Sanket is a very organized person. He likes to organize everything to increase his efficiency. Whenever he sees a list of numbers he like to tag the number in ascending order. Recently he has realized he is wasting a lot of time doing that and thus want you to help him do it faster.
Given a list of numbers [23, 45, 87,... | __author__ = 'Suvojit Manna'
t = raw_input()
while True:
try:
n = raw_input()
arr = [int(i) for i in raw_input().split()]
ordMap = {x: i for i, x in enumerate(sorted(set(arr)))}
arr = map(lambda y: ordMap[y], arr)
for x in arr:
print x,
print "\n",
ex... |
There are a total of n people in Prateek's class, numbered from 1 to n.
Every person has some field of interest for their projects.
There are a number people who have the same field of interest.
Now, you are given a number of pairs of the form (x,y).
This means that the students numbered x and y have interest in the ... | def dfs(v):
global mark,c_c
q=[]
q.append(v)
s=0
while q:
top=q.pop()
#s=1
mark[top]=c_c
for j in G[top]:
if mark[j]==-1:
q.append(j)
s+=1
mark[j]=mark[top]
d[c_c]=s
t=input()
mo=10**9+7
... |
Given three positive integers N, A and B (A < B < N), find the sum of all positive integers less than N, which are divisible by either A or B.
For example, when N = 20, A = 4 and B = 7, the possible values are 4, 7, 8, 12, 14, and 16. Their sum is 61.
Input Format
The only line of the input file contains three space s... | #! /usr/bin/python
s = raw_input()
lst = s.split(' ')
n = int(lst[0])
a = int(lst[1])
b = int(lst[2])
sum = 0
for x in xrange(a,n,1):
if (((x % a) == 0) or ((x % b) == 0)):
sum = sum + x
print sum |
Rajesh has been challenge by his friend to find the number which have properties like,
Here take no 12 such that
square of 12(12*12)=144
and 21 which is reverse of 12 have square(21*21)= 441 whose reverse is equal to 144
and now Rajesh is not getting any way how to solve the problem.So he makes a list of the number... | import math
t=input()
for i in range(0,t):
n=input()
s=n*n
s=str(s)
#print s
p=str(n)
p=p[::-1]
p=int(p)
p=p*p
#print p
p=str(p)
if(p==s):
print"No"
continue
p=p[::-1]
#print p
if(p==s):
print int(math.sqrt(int(p[::-1])))
else:
print "No" |
How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?
* 0 \leq A_i \leq 9
* There exists some i such that A_i=0 holds.
* There exists some i such that A_i=9 holds.
The answer can be very large, so output it modulo 10^9 + 7.
Constraints
* 1 \leq N \leq 10^6
* N is an in... | N = int(input())
ans = 10**N - 2*(9**N) + 8**N
print(ans % 1000000007)
|
There are N blocks arranged in a row. Let us paint these blocks.
We will consider two ways to paint the blocks different if and only if there is a block painted in different colors in those two ways.
Find the number of ways to paint the blocks under the following conditions:
* For each block, use one of the M colors... | #include <iostream>
using namespace std;
long long n, m, k, t = 0;
long long p[200001], q[200001], r[200001];
const long long M = 998244353;
long long pow(long long a, long long b) {
long long w = 1, x = a;
while (b) {
if (b & 1)
w = w * x % M;
x = x * x % M;
b >>= 1;
}
return w;
}
int main()
{
cin ... |
Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.
Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):
* There exists a non-negative integer p such that X= a_k \times (p+0.5).
Find the number of semi-co... | #include <bits/stdc++.h>
using namespace std;
#define int long long
int gcd(int a, int b){
if(b == 0){
return a;
}
else{
return gcd(b, a % b);
}
}
int lcm(int a, int b){
return (a / gcd(a, b)) * b;
}
signed main(){
int N, M, i;
scanf("%lld%lld", &N, &M);
vector<int> a(N);
for(i = 0; i < N; i++){
scanf... |
Given are a prime number p and a sequence of p integers a_0, \ldots, a_{p-1} consisting of zeros and ones.
Find a polynomial of degree at most p-1, f(x) = b_{p-1} x^{p-1} + b_{p-2} x^{p-2} + \ldots + b_0, satisfying the following conditions:
* For each i (0 \leq i \leq p-1), b_i is an integer such that 0 \leq b_i \le... |
public class Main {
private static void solve() {
int p = ni();
int[] a = na(p);
int[][] fif = enumFIF(p - 1, p);
int[] ret = new int[p];
for (int i = 0; i < p; i++) {
if (a[i] == 0)
continue;
int f = 1;
for (int j = p - 1; j >= 0; j--) {
int sign = (p + j) ... |
You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.
Here, a ACGT string is a string that contains no characters other than `A`, `C`, `G` and `T`.
Constraints
* S is a string of length between 1 and 10 (inclusive).
* Each c... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
Scanner sc = new Scanner(System.in);
//入力表示
String S = sc.next();
int count=0;
int ans =0;
char [] a= S.toCharArray();
for(int i=0;i<a.length; i++) {
if(a[i]=='A' ||a[i]=='C' ||a[i... |
You are given a string S of length N and another string T of length M. These strings consist of lowercase English letters.
A string X is called a good string when the following conditions are all met:
* Let L be the length of X. L is divisible by both N and M.
* Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \... | gcd = lambda a,b: a if b==0 else gcd(b,a%b)
n,m = map(int,input().split())
s = input()
t = input()
d = gcd(n,m)
if s[::n//d]==t[::m//d]:
print(n*m//d)
else:
print(-1) |
When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.
You are given N numbers X_1, X_2, ..., X_N, where N is an even number. For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..... | #include <bits/stdc++.h>
using namespace std;
const int N=200000+5;
int main()
{
int n,a[N],b[N];
cin >> n;
for(int i=0;i<n;i++) scanf("%d",&a[i]),b[i]=a[i];
sort(b,b+n);
int x,y;
y=b[n/2],x=b[n/2-1];
for(int i=0;i<n;i++)
{
if(a[i]<=x) printf("%d\n",y);
else if(a[i]>=y) p... |
Joisino the magical girl has decided to turn every single digit that exists on this world into 1.
Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).
She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and... | h,w = map(int,input().split())
c = [list(map(int,input().split())) for i in range(10)]
A = [list(map(int,input().split())) for i in range(h)]
for k in range(10):
for i in range(10):
for j in range(10):
c[i][j] = min(c[i][j],c[i][k]+c[k][j])
ans = 0
for i in range(h):
for j in A[i]:
... |
You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.
Fortunately, you are a skilled magician, capable of causing expl... | // D - Widespread
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
#define rp(i,n) for(int i=0;i<(n);++i)
#define roundup(a,b) (((a)+(b)-1)/(b))
int main(){
int N,A,B; cin>>N>>A>>B;
vector<LL> H(N); rp(i, N) cin>>H[i];
int ans = INT_MAX;
LL ab = (LL)A - B;//additional damage
int L = 0, R = 1e9... |
There are N cities. There are also K roads and L railways, extending between the cities. The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities. No two roads connect the same pair of cities. Similarly, no two railways connect the s... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200 * 1000 + 20;
int n, k, l, a, b, g[MAXN], ans[MAXN], cnt;
vector <int> adj[MAXN], adj2[MAXN], tmp;
map <int, int> mp;
bitset <MAXN> connect;
bool vis[MAXN], vis2[MAXN];
void dfs(int v) {
vis[v] = true;
g[v] = cnt;
connect[v] = 1;
for (int u: adj[v... |
Snuke got positive integers s_1,...,s_N from his mother, as a birthday present. There may be duplicate elements.
He will circle some of these N integers. Since he dislikes cubic numbers, he wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product s_is_j is not cubic. For example, when s_1=1,s_2=1,s_3=... | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL a[100010],b[100010];
int n,ans;
map<LL,int>mp;
LL sqr(LL x){return x*x;}
int main(){
scanf("%d",&n);
for(int i=1; i<=n; i++){
LL x;
scanf("%lld",&x);
for(LL j=2;j*j*j<=x;j++) for(;x%(j*j*j)==0;x/=j*j*j);
mp[x]++;
a[i]=x;
LL y=1;
for(L... |
Aizu is famous for its buckwheat. There are many people who make buckwheat noodles by themselves.
One day, you went shopping to buy buckwheat flour. You can visit three shops, A, B and C. The amount in a bag and its unit price for each shop is determined by the follows table. Note that it is discounted when you buy bu... | #include <stdio.h>
int main() {
int stack[50], sp = 0, n, i, sum;
while (scanf("%d", &stack[sp++]) != EOF)
;
for (i = 0; i < sp; i++) {
int ans = 1000000;
n = stack[i];
if (n == 0)
break;
for (int a = 0; a <= 50; a++) {
for (int b = 0; b <= 50; b++) {
for (int c = 0; c <= ... |
Interest rates are attached to the money deposited in banks, and the calculation method and interest rates vary from bank to bank. The combination of interest and principal is called principal and interest, but as a method of calculating principal and interest, there are "single interest" that calculates without incorp... | import static java.util.Arrays.deepToString;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
Scanner sc = new Scanner(System.in);
public void run() {
for (;sc.hasNext();) {
int n = sc.nextInt();
if (n == 0) break;
int y = sc.nextInt();
... |
Gas stations in the White Tiger service area have $ N $ lanes assigned numbers from $ 1 $ to $ N $. The first car in each lane can refuel.
Cars entering the gas station will choose the lane with the fewest cars in line and line up at the end of the line. If there are multiple such lanes, choose the one with the lowest... | #include <iostream>
#include <vector>
#include <array>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <tuple>
#include <bitset>
#include <memory>
#include <cmath>
#include <algorithm>
#include ... |
There is a cube which consists of n × n × n small cubes. Small cubes have marks on their surfaces. An example where n = 4 is shown in the following figure.
<image>
Then, as shown in the figure above (right), make a hole that penetrates horizontally or vertically from the marked surface to the opposite surface.
You... | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0; i<(n); i++)
#define FOR(i,x,n) for(int i=x; i<(n); i++)
#define ALL(n) begin(n),end(n)
#define MOD (1000000007)
#define INF (1e9)
#define INFL (1e18)
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
template<class... |
A wise king declared a new calendar. "Tomorrow shall be the first day of the calendar, that is, the day 1 of the month 1 of the year 1. Each year consists of 10 months, from month 1 through month 10, and starts from a big month. A common year shall start with a big month, followed by small months and big months one aft... | import java.util.Scanner;
public class Main {
final int ny = 19*5+20*5;
final int sy = 20*10;
final long mill = tonum(1000, 1, 1);
long ytod(int y) {
y = y-1;
int last = y%3;
return (y/3)*(ny+ny+sy) + last * ny;
}
long mtod(int y, int m) {
m = m-1;
if(y % 3 == 0) {
return m * 20;
} else {... |
Suppose that P1 is an infinite-height prism whose axis is parallel to the z-axis, and P2 is also an infinite-height prism whose axis is parallel to the y-axis. P1 is defined by the polygon C1 which is the cross section of P1 and the xy-plane, and P2 is also defined by the polygon C2 which is the cross section of P2 and... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const dou... |
Problem
Given the three integers n, m, k
n1% 10 + n1 + m% 10 + n1 + 2m% 10 + ... + n1 + (k-1) m% 10
Calculate. a% b represents the remainder when a is divided by b.
Constraints
Input meets the following conditions
* 0 ≤ n ≤ 1018
* 0 ≤ m ≤ 109
* 1 ≤ k ≤ 109
Input
n m k
One line is given n, m, k.
Output
Prin... | #include <iostream>
using namespace std;
typedef long long ll;
int main() {
ll n,m,k;
cin >> n >> m >> k;
n%=10;
m%=4;
int a=n,d[4];
for(int i=0; i<4; i++){
d[i]=a;
a=a*n%10;
}
ll ans=0;
for(int i=0; i<4; i++) {
ans+=k/4*d[m*i%4];
if(i<k%4) ans+=d[m*i%4];
}
cout << ans << e... |
Rock-Scissors-Paper is a game played with hands and often used for random choice of a person for some purpose. Today, we have got an extended version, namely, Hyper Rock-Scissors-Paper (or Hyper RSP for short).
In a game of Hyper RSP, the players simultaneously presents their hands forming any one of the following 15 ... | #include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
using namespace std;
#define FOR(i,k,n) for(int i=(k); i<(int)n; +... |
Champernown constant is an irrational number represented in decimal by "0." followed by concatenation of all positive integers in the increasing order. The first few digits of this constant are: 0.123456789101112...
Your task is to write a program that outputs the K digits of Chapnernown constant starting at the N-th ... | import java.util.Scanner;
/**
* チャンパーノウン定数クラス
* 0.1234567891011121314...
* 1-indexed
*
*/
public class Main {
//10^18
//at(DIGIT_LIMIT) = 594771241830065 [3] 5
long DIGIT_LIMIT = 1000000000000000000L;
//DIGIT_LIMITを含む整数MAX_NUMBER
//この整数の先頭は 999999999999999985 番目である
//[10^17, MAX_NUMBER]
long MAX_NUMBE... |
The Sun is a great heavenly body. The Sun is worshiped by various religions. Bob loves the Sun and loves any object that is similar to the Sun. He noticed that he can find the shape of the Sun in certain graphs. He calls such graphs "Sunny".
We define the property "Sunny" mathematically. A graph G=(V,E) with a vertex ... | #include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <vector>
#include <valarray>
#include <array>
#include <queue>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <complex>
#include <random>
using namespace ... |
Dr. Akita, who lives in the neighborhood, is a historical researcher in the field and recently discovered a new ancient document about Ono no Komachi.
It is widely known that Ono no Komachi has given General Fukakusa, who wants to be dating, on condition that he keeps going for 100 nights, but he claims that this disc... | #include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>... |
E: Do You Divide It? / Do you want to chop it up?
story
Mr. T has been terribly troubled by the problem of plane figures in programming contests he has participated in in the past, and has had a strong grudge against plane figures ever since.
Above all, I have mixed feelings about polygons drawn on a two-dimensional... | #include<bits/stdc++.h>
#define EQ(a,b) (abs((a)-(b)) < EPS)
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define fs first
#define sc second
#define pb push_back
#define sz size()
#define all(a) (a).begin(),(a).end()
using namespace std;
typedef long double D;
typedef complex<D> P;
typedef pair<P,P> L;
typedef vector... |
problem
Play the card-based game $ Q $ times. The cards are numbered $ 1 \ cdots N $, and each numbered card is large enough to play the game. In the $ i $ game, two cards are first dealt as a hand. The numbers on each card are $ x_i $ and $ y_i $. Cards can be exchanged according to the rules. The $ j $ th $ (1 \ le ... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long long W;
const W INF = 1LL << 58;
struct edge {
int to;
W cost;
};
typedef pair<W, int> P;
typedef vector<vector <edge > > Graph;
void dijkstra(vector<int> st, const Graph& G, vector<W>& d) {
priority_queue< P, vector<P>, greater<P> >... |
Extraterrestrial Life Genome Database Returns
In 2301 AD, the Department of Life Sciences of the Federal Republic of Space was studying the genome sequences of space organisms. As a result of recent research, it has become clear that the number of times a specific pattern appears in the genome sequence has a great inf... | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
using ll = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b)a=b;};
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b)a=b;};
template<typename T, T MOD, T B>
struct RollingHash{
vector<T> hash, p... |
Range Count Query
Given the sequence a_1, a_2, .., a_N.
In the query, answer the number of terms whose value is l or more and r or less.
input
N Q
a_1 a_2 ... a_N
l_1 r_1
l_2 r_2
::
l_q r_q
output
ans_1
ans_2
::
ans_q
On line i, output the answer to the i-th query, that is, the number of j such as l_i \ leq ... | #include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
using namespace std;
typedef long long int ll;
typedef pair<int,int> P;
#define yn {puts("Yes");}else{puts("No");}
#define MAX_N 200005
int main() {
... |
Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:
* find(s, t): report the minimum element in as, as+1, . . . ,at.
* update(i, x): change ai to x.
Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 10000... | #include<iostream>
#define INF 2147483647
using namespace std;
int A[100000];
void Update(int i, int x) {
A[i] = x;
}
void Find(int x, int y) {
int s, t, min = INF;
if (x < y) { s = x; t = y; }
else { s = y; t = x; }
for (int i = s; i <= t; i++) {
if (min > A[i]) min = A[i];
}
cout << min << endl;
}
int ma... |
Amy is a bright kid. She recently learnt the numbers from 0 to 9, and spends all her time these days, trying to write larger numbers. One day she wrote a number on a paper, and turned it upside down. It surprised and amazed her that the writing on the paper still made sense.
So, now she has created a game for herself, ... | number=int(raw_input())
swapper={'0':'0','6':'9','9':'6','8':'8',"1":"1"}
for _ in xrange(number):
num=raw_input().strip()
s=""
for x in reversed(num):
if x not in swapper:
print "NO"
break
s+=swapper[x]
else:
print "YES"
print s |
Given an integer N. Integers A and B are chosen randomly in the range [1..N]. Calculate the probability that the Greatest Common Divisor(GCD) of A and B equals to B.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test case consis... | from fractions import gcd
from sys import stdin
def p(n):
s = int(n ** .5)
c = sum(n/i for i in xrange(1, s+1)) * 2 - s**2
g = gcd(c, n ** 2)
return '{}/{}'.format(c / g, n**2 / g)
print(
'\n'.join(
p(int(ln))
for i, ln in enumerate(stdin) if i
)
) |
Alvin and Berto have gotten tired of eating chocolates, so now they have decided to eat candies instead.
Alvin has A apple candies, and Berto has B banana candies. (I know, they have weird tastes.) Alvin and Berto always wants the split of candies to be as fair as possible. The problem is, Alvin only wants apple candie... | from fractions import gcd
ls = []
for dfj in range(input()):
a,b,c,d = [int(i) for i in raw_input().split()]
g = gcd(c,d)
ls.append(min((a-b)%g,(b-a)%g))
for i in ls:
print i |
Rohit dreams he is in a shop with an infinite amount of marbles. He is allowed to select n marbles. There are marbles of k different colors. From each color there are also infinitely many marbles. Rohit wants to have at least one marble of each color, but still there are a lot of possibilities for his selection. In his... | solution = []
def fact(n,r):
res=1
if r>n-r:
r = n-r
for i in range(r):
res*=(n-i)
res/=i+1
return res
def main():
T = int(raw_input().strip())
for i in xrange(T):
global fact
global solution
val = raw_input().strip().split()
if int(... |
A Quad is a data container that consists of 4 bits, represented by a hexadecimal number. It has 2 halves - the upper half and the lower half.
Consider a binary number with digits B1,B2,B3,B4 where B1 is the most significant digit and B4 is the least significant digit. The upper half consists of bits B1 and B2, and the ... | def binary(a):
b=""
for i in range(4):
b=str(a%2)+b
a=a/2
return b
n=input()
q=list(raw_input())
for i in range(len(q)):
q[i]=binary(int(q[i],16))
n1=""
n2=""
for i in range(len(q)):
n1+=q[i][:2]
n2+=q[i][2:]
qn=[0]*(2*n+1)
rem=0
for i in range(len(n1)):
k=2*n-i-1
qn[... |
While evaluating a expression of N distinct factors i.e (A1 * A2 * ..... * An) , Chef wanted to know in how may ways this expression can be evaluated by parenthesizing two factors at a time.
Input
The first line of the input contains an integer T denoting the number of test cases, for each test case enter the string ... | def fact(n):
if(n<=1):
return 1
else:
return fact(n-1)*n
t=input()
while t:
t=t-1
r=len(raw_input().strip())-1
print fact(2*r)/(fact(r)*fact(r+1)) |
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string.
Your task is to find a sequence of operations after which one of the strings ... | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<pair<int, int>> construct(string& s, string& t) {
deque<pair<char, int>> qs;
deque<pair<char, int>> qt;
int n = s.length();
int m = t.length();
for (int i = 0; i < n; ++i) {
char c = s[i];
int cnt = 1;
... |
There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.
Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).
When a slime with a value x eats a slime with a value y, the eaten slime disappears, and ... | import sys
import os
def solve(slimes):
if len(slimes) == 1:
return slimes[0]
havePos = False
haveNeg = False
for s in slimes:
if s > 0:
havePos = True
elif s < 0:
haveNeg = True
if havePos and haveNeg:
return sum(map(abs, slimes))
elif... |
You are given integers d and p, p is prime.
Also you have a mysterious device. It has memory cells, each contains an integer between 0 and p-1. Also two instructions are supported, addition and raising to the d-th power. Both are modulo p.
The memory cells are numbered 1, 2, ..., 5000. Initially cells 1 and 2 contai... | #include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 7;
const long long INF = 1e18L + 7;
template <class n, class second>
ostream &operator<<(ostream &p, pair<n, second> x) {
return p << "<" << x.first << ", " << x.second << ">";
}
template <class n>
auto operator<<(ostream &p, n y) ->
typename ena... |
Polycarp's phone book contains n phone numbers, each of them is described by s_i — the number itself and m_i — the number of times Polycarp dials it in daily.
Polycarp has just bought a brand new phone with an amazing speed dial feature! More precisely, k buttons on it can have a number assigned to it (not necessary f... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline void cmin(T &a, T b) {
((a > b) && (a = b));
}
template <class T>
inline void cmax(T &a, T b) {
((a < b) && (a = b));
}
char IO;
template <class T = int>
T rd() {
T s = 0;
int f = 0;
while (!isdigit(IO = getchar())) f |= IO == '-';
do s... |
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.
The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.
Input
The first line of the input ... | def check(n):
if (n // 2) % 2 == 1:
return 0
return 1
n = int(input())
if n % 2 == 1:
print(check(n))
else:
print(check(n - 1))
|
You are given an array of n integers: a_1, a_2, …, a_n. Your task is to find some non-zero integer d (-10^3 ≤ d ≤ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least ⌈n/2⌉). Not... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, pos = 0, neg = 0;
cin >> n;
long long a[n];
for (long long i = 0; i < n; i++) {
cin >> a[i];
pos += (a[i] > 0);
neg += (a[i] < 0);
}
long long lim = (n + 1) / 2;
if (pos >= lim)
cout << "1" << endl;
else if (neg >= l... |
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:
<image> By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n ... | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Sol2 {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
char[][] board = new char[n][n];
... |
The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal proba... | #include <bits/stdc++.h>
using namespace std;
template <int m>
struct modint {
unsigned x;
modint() : x(0) {}
modint(long long arg) {
arg %= m;
if (arg < 0) {
x = arg + m;
} else {
x = arg;
}
}
modint& operator+=(const modint& other) {
x += other.x;
if (x >= m) {
x -=... |
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen... | #include <bits/stdc++.h>
using namespace std;
long long int a[110][110][2];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int i, j, ans = 0, mod = 100000000, k, n1, n2, k1, k2;
cin >> n1 >> n2 >> k1 >> k2;
a[0][0][0] = 1;
a[0][0][1] = 1;
for (i = 0; i <= n1; i++) {
for (j = 0... |
You are given a sequence of n digits d_1d_2 ... d_{n}. You need to paint all the digits in two colors so that:
* each digit is painted either in the color 1 or in the color 2;
* if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
string s;
cin >> s;
vector<int> v[10];
for (int i = 0; i < n; ++i) {
int x = s[i] - '0';
v[x].push_back(i);
}
int... |
Suppose there is a h × w grid consisting of empty or full cells. Let's make some definitions:
* r_{i} is the number of consecutive full cells connected to the left side in the i-th row (1 ≤ i ≤ h). In particular, r_i=0 if the leftmost cell of the i-th row is empty.
* c_{j} is the number of consecutive full cells ... | n, m = map(int, input().split())
row = list(map(int, input().split()))
col = list(map(int, input().split()))
grid = [['?'] * m for _ in range(n)]
for i in range(n):
lng = row[i]
for j in range(lng):
grid[i][j] = 'b'
if lng < m:
grid[i][lng] = 'w'
for i in range(m):
lng = col[i]
for j... |
For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) ≥ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 ≥ 5.
... | def findsubarray(n,ll):
for i in range(0,n-1):
if abs(ll[i]-ll[i+1])>1:
return 1,i+1,i+2
return 0,None,None
tests = int(input())
for i in range(0,tests):
numberlen = int(input())
numbers = input().split()
numberss = list(map(int,numbers))
result, left,right = findsub... |
[SIHanatsuka - EMber](https://soundcloud.com/hanatsuka/sihanatsuka-ember)
[SIHanatsuka - ATONEMENT](https://soundcloud.com/hanatsuka/sihanatsuka-atonement)
Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.
One day, Nora's adop... | #include <bits/stdc++.h>
using namespace std;
int n, a[65];
int mask[65], cnt[1 << 15];
bool bl[65];
int fa[65];
int qpow(int x, int y) {
int ret = 1;
while (y) {
if (y & 1) ret = (long long)ret * x % 1000000007;
y >>= 1;
x = (long long)x * x % 1000000007;
}
return ret;
}
int C(int n, int m) {
if ... |
You are given a set of strings S. Each string consists of lowercase Latin letters.
For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the followin... | #include <bits/stdc++.h>
using namespace std;
int n, k, a[1000001], f[1000001], g[1000001], sz[1000001], fa;
vector<pair<char, int>> d[1000001];
char ch;
void dfs(int x, int pre) {
f[x] = f[pre] + 1;
g[x] = min(f[x], g[pre] + sz[pre]);
if (sz[x]) f[x] = min(f[x], g[x] + 1);
sort(d[x].begin(), d[x].end());
for... |
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose s... | def f(grid):
for i in range(9):
for j in range(9):
if grid[i][j] == '1':
grid[i][j] = '2'
def main():
t = int(input())
for _ in range(t):
grid = [[x for x in input()] for __ in range(9)]
f(grid)
for row in grid:
print(''.join(row))
main() |
This is an interactive problem.
We have hidden an integer 1 ≤ X ≤ 10^{9}. You don't have to guess this number. You have to find the number of divisors of this number, and you don't even have to find the exact number: your answer will be considered correct if its absolute error is not greater than 7 or its relative err... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
void *wmem;
char memarr[96000000];
template <class S, class T>
inline S min_L(S a, T b) {
return a <= b ? a : b;
}
template <class S, class T>
inline S max_L(S a, T b) {
return a >= b ? a : b;
}
template <class T>
inline void walloc1d(T **a... |
Madeline has an array a of n integers. A pair (u, v) of integers forms an inversion in a if:
* 1 ≤ u < v ≤ n.
* a_u > a_v.
Madeline recently found a magical paper, which allows her to write two indices u and v and swap the values a_u and a_v. Being bored, she decided to write a list of pairs (u_i, v_i) with t... | #include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
vector<int> a(n);
vector<int> mass1(n);
vector<int> p(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
mass1[i] = a[i];
}
sort(mass1.begin(), mass1.... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | def t(b):
if b:
print("YES")
return
print("NO")
for _ in range(int(input())):
a = int(input())
l = sorted(list(map(int, input().split())))
for i in range(a - 1):
if l[i + 1] - l[i] >= 2:
t(False)
break
else:
t(True)
|
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.
Let's represent the city as an area of n × n square blocks. Yura needs to move from the block with coordinates (s_x,s_y) to the ... | from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys
'''
@lru_cache(None)
def fact(x):
if x<2:
return 1
return fact(x-1)*x
@lru_cache(None)
def per(i,j):
return... |
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
void setIO(string name = "") {
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
if ((int)(name).size()) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
const int inf = 1... |
There are n cells, numbered 1,2,..., n from left to right. You have to place a robot at any cell initially. The robot must make exactly k moves.
In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell i, it must move to e... | #include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
const int N = 5005;
const int p = 1e9 + 7;
int n, k, q;
int a[N];
ll ans;
ll num[N], dp[N][N];
int main(){
scanf("%d%d%d", &n, &k, &q); ++k;
for(int i = 1; i <= n; ++i) scanf("%d", ... |
There are n coins labeled from 1 to n. Initially, coin c_i is on position i and is facing upwards ((c_1, c_2, ..., c_n) is a permutation of numbers from 1 to n). You can do some operations on these coins.
In one operation, you can do the following:
* Choose 2 distinct indices i and j.
* Then, swap the coins on ... | #include <bits/stdc++.h>
const int N=200005;
struct note{
int x,y;
}opt[N];
int t[N],a[N],n,cnt,vis[N],ed[N],s[N],tot,siz[N];
void Swap(int x,int y){
opt[++tot]={x,y};
std::swap(a[x],a[y]);
}
void solve(int x){
int nn=0;
for (int i=a[x];i!=x;i=a[i])
t[++nn]=i;
for (int i=1;i<=nn;i++)
Swap(t[i],x);
}
void mer... |
Baby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it:
* pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range;
* stick some of the elements together in the same order they were in the array; ... | /*
bts songs to dance to:
Filter
*/
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1514D
{
public static void main(String hi[]) throws Exception
{
... |
You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked no... | #include <bits/stdc++.h>
#define nl '\n'
#define pb push_back
#define ll long long
#define VMAX 100001
#define NMAX 35005
#define INF 10000000000000000
using namespace std;
ifstream f("pirati.in");
ofstream g("pirati.out");
const int MOD=1000000007;
int n;
ll dp[205][205];
int dist[205][205];
long long lgpow(ll a,ll b... |
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the s... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const int MAXX = 5010;
int number[MAXX][MAXX], acum[MAXX][MAXX];
string x, y;
int solve() {
int ret = 0;
memset(number, 0, sizeof(number));
memset(acum, 0, sizeof(acum));
for (int i = 0; i < x.size(); i++) {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.