input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Nitesh recently discovered a new game CODATHON with the help of a very intelligent alien friend Jupiter.
In this game a student had various challenges and each challenge had infinite number of problems.
The scoring system in this game was quite different. There are 2 ways of scoring on a given problem:
If you are in t... | import sys
f = sys.stdin
MOD = 1000000007
T = int(f.readline())
while T:
A,B = [int(x) for x in f.readline().split()]
ans = A * B - A - B
ans %= MOD
if ans < 0 :
ans += MOD
print ans
T -= 1 |
A daily train consists of N cars. Let's consider one particular car. It has 54 places numbered consecutively from 1 to 54, some of which are already booked and some are still free. The places are numbered in the following fashion:
The car is separated into 9 compartments of 6 places each, as shown in the picture. So, ... | first = raw_input()
inp = first.split()
x = int(inp[0])
y = int(inp[1])
train = []
ans = 0
for i in range(y):
train.append(str(raw_input()))
strin = str(train[i])
empty = []
empty.append(int( 6 - (int(strin[0])+int(strin[1])+int(strin[2])+int(strin[3])+int(strin[52])+int(strin[53]))))
empty.append(int( 6... |
Valentine's Day is coming and our friend Mr.IDC has fallen in love with a girl. He just could not control his feelings and went to propose her.
When he proposed her the girl gave him a challenge and asked him to solve it and the condition was if he will solve the challenge successfully then only she will accept his pro... | for _ in range(input()):
n,m=map(int,raw_input().split())
if n<m:
print n*(n+1)/2
elif n==m:
print n*(n-1)/2
else:
print (m*(m-1)/2)*(n//m)+(((n%m)*(n%m+1))/2) |
Chef Ceil has some matchsticks in his kitchen.
Detail of matchsticks:
There are N matchsticks in total. They are numbered from to 0 to N-1 inclusive. All matchsticks have same length. But they may have different rates of burning. For i^th matchstick, we denote bi as the time required for that matchstick to completely b... | intMax = 10**8+1
def treeQuery(tree1, tree2, start, end, rangeStart, rangeEnd, index):
if rangeStart<=start and rangeEnd>=end:
return tree1[index], tree2[index]
if end<rangeStart or start>rangeEnd:
return intMax, -1
middleIndex = (start + end) / 2
a,c = treeQuery(tree1, tree2, start, mid... |
"I heard that you're settled down
That you found a girl and you're married now.
I heard that your dreams came true.
Guess she gave you things I didn't give to you."
Adele just got news about her old lover. She is in her study, reminiscing all the memories they shared and feeling lonely.
After some initi... | a=raw_input()
c=0
m=0
s=''
sTemp=''
for i in a:
if i=='(':
c+=1
sTemp=''
else:
if i==')' and c>m:
s=sTemp
sTemp=''
m=c
c-=1
else:
if i==')':
c-=1
sTemp=''
else:
... |
On the icy planet Zorg, the Vogons are putting together a zoo. One cage will house a collection of Kubudu dragons. Unlike the limited number of blood types found in other creatures, Kubudu dragons have a large variety of blood types. Each dragon’s blood type is fixed when it is born and is given by a positive integer.
T... | N,K = map(int, raw_input().split())
L = sorted(set(map(int, raw_input().split())))
cmax = 0
cur_index = 0
cur_val = L[cur_index]
#import time
while 1:
#print "loop,",L
if cur_index == len(L)-1:
break
j = cur_index
cur_count = 1
loop_val = L[j]
L[j]=0
#print "{} {} {}".format(j, lo... |
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to l... | #include <bits/stdc++.h>
using namespace std;
string str, ans;
int myMap[1000];
struct myPair {
int cnt;
char let;
} mp;
vector<myPair> myVect;
bool operator<(const myPair a, const myPair b) { return a.cnt < b.cnt; }
bool mark[1000];
int main() {
int i, j, k, asa = 0;
cin >> str >> k;
for (i = 0; i < str.leng... |
Vasya has got a magic matrix a of size n × m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersec... | #include <bits/stdc++.h>
using namespace std;
struct edge {
int x, w;
edge() {}
edge(int x, int w) : x(x), w(w) {}
};
inline void read(int &x) {
char ch;
int f = 1;
x = 0;
do {
ch = getchar();
if (ch == '-') f = -f;
} while (ch < '0' || ch > '9');
do {
x = (x << 3) + (x << 1) + (ch & 15);
... |
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 × 8, but it still is N × N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;... |
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 ≤ n,k ≤ 10^5), the length ... | # coding: utf-8
# Your code here!
import sys
n,k = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
cnt = 0
prev = 0
for i in range(len(A)):
ans = A[i] - prev
if ans != 0:
print(ans)
prev = A[i]
cnt += 1
if cnt == k:
break
for _ in range(k-cn... |
Today at the lesson of mathematics, Petya learns about the digital root.
The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Stack;
public class ROUGH {
static long m=998244353;
static... |
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.
There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo... | from sys import stdin
n, m = map(int, stdin.readline().split())
print(n * 3 + min(m - 1, n - m))
|
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
int a[maxn], s[maxn];
int g[maxn], f[maxn];
int main() {
int n, m, k;
cin >> n >> m >> k;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i <= m; ++i) {
int x, y;
cin >> x >> y;
if (x <= k) g[x] = max(g[x], y);
}
s... |
Authors guessed an array a consisting of n integers; each integer is not less than 2 and not greater than 2 ⋅ 10^5. You don't know the array a, but you know the array b which is formed from it with the following sequence of operations:
1. Firstly, let the array b be equal to the array a;
2. Secondly, for each i f... |
import java.util.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class Temp{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
... |
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ... | n = int(raw_input())
h1 = list(map(int, raw_input().split()))
h2 = list(map(int, raw_input().split()))
dp1 = [0] * n
dp2 = [0] * n
dp1[0] = h1[0]
dp2[0] = h2[0]
for i in range(1, n):
dp1[i] = max(dp2[i-1] + h1[i], dp1[i-1])
dp2[i] = max(dp1[i-1] + h2[i], dp2[i-1])
print(max(dp1[n-1], dp2[n-1])) |
Let's define p_i(n) as the following permutation: [i, 1, 2, ..., i - 1, i + 1, ..., n]. This means that the i-th permutation is almost identity (i.e. which maps every element to itself) permutation but the element i is on the first position. Examples:
* p_1(4) = [1, 2, 3, 4];
* p_2(4) = [2, 1, 3, 4];
* p_3(4) ... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
long long int mi = INT_MAX, ma = INT_MIN, gcd, i, j, k, w, d, x, y, x1, y1, p,
q, r, n, m, root, sum;
cin >> n >> m;
long long int a[m];
for (i = 0; i < m; i++) cin >> a[i];
long long in... |
You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n.
The graph is considered harmonious if and only if the following property holds:
* For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a pat... | #include <bits/stdc++.h>
using namespace std;
void dfs(vector<int> graph[], int u, int comp[], int k, bool visit[]) {
int size = graph[u].size();
visit[u] = true;
comp[u] = k;
for (int i = 0; i < size; i++) {
if (!visit[graph[u][i]]) {
dfs(graph, graph[u][i], comp, k, visit);
}
}
}
int main() {
... |
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | t = int(input())
for _ in range(t):
s = input()
i = 0
R = []
while i < len(s):
# print(s[i:i+5])
if i+4<len(s) and s[i:i+5] == "twone":
# print('paso')
R.append(i+2+1)
i+=5
elif i+2<len(s) and (s[i:i+3] == "one" or s[i:i+3] == "two"):
... |
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l ..... | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
const LL H = 998244353;
LL n, q, s[200010], sum[200010], h[2][200010];
char str[200010];
LL pw(LL x, LL p) {
if (!p) return 1;
LL t = pw(x, p / 2);
if (p % 2)
return t * t % H * x % H;
else
return t * t % H;
}
int main() {
scanf("%lld... |
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm... |
/**
*
* @author xerxes
*/
import java.io.*;
import java.lang.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
BufferedReader reader;
public static void main(String[] args) throws IOException {
Main ob = new Main();
ob.Run();
System.exit(0);
}
... |
Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as "Your beautiful necklace — do it yourself!". It contains many necklace parts and some magic glue.
The necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magi... | #include <bits/stdc++.h>
using namespace std;
const int N = 1100000;
int n, a[N], b[N];
struct node {
int to;
int u, v;
node() {}
node(int x, int y, int z) : to(x), u(y), v(z) {}
};
int fir[N];
vector<node> e[N];
vector<int> rev[N], print;
vector<bool> vis[N];
void dfs(int from) {
for (int &i = fir[from]; i <... |
There is an undirected tree of n vertices, connected by n-1 bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex a and its tail is at vertex b. The snake's body occupies all vertices on the unique simple path between a and b.
The snake wants to know if it can reverse itself — tha... | #include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
ostream& operator<<(ostream& os, const pair<A, B>& x) {
return os << "(" << x.first << "," << x.second << ")";
}
namespace tree {
struct Edge {};
int n;
vector<Edge> edges;
vector<vector<pair<int, int>>> adj;
void makeTree(int _n) {
n =... |
There is a square of size 10^6 × 10^6 on the coordinate plane with four points (0, 0), (0, 10^6), (10^6, 0), and (10^6, 10^6) as its vertices.
You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.
Now you are wondering how many ... | //package round665;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class E3 {
InputStream is;
PrintWriter out;
String INPUT = "";
long numIntersections(int[][] hors, ... |
As you all know, the plum harvesting season is on! Little Milutin had his plums planted in an orchard that can be represented as an n by m matrix. While he was harvesting, he wrote the heights of all trees in a matrix of dimensions n by m.
At night, when he has spare time, he likes to perform various statistics on his... | #include <bits/stdc++.h>
int n, m;
std::vector<int> r, c;
int stk[1000001], pos[1000001], top, map[101][101];
int get(int i, int j) {
printf("? %d %d\n", i, j);
fflush(stdout);
int x;
scanf("%d", &x);
return x;
}
std::vector<int> solve(std::vector<int> r, std::vector<int> c) {
if (r.size() >= c.size()) {
... |
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 ≤ j ≤ k, j≠ i), for which (b_i ⊕ b_j) is the smallest among all such j,... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
int size[6011100];
int l[6011100], r[6011100];
int id;
int ans;
int a[6011100];
void insert(int x) {
int cur = 0;
size[cur]++;
for (int i = 29; i >= 0; --i) {
if (l[cur] == -1) l[cur] = id++;
if (r[cur] == -1) r[cur] = id++;
... |
This is an interactive problem.
n people sitting in a circle are trying to shuffle a deck of cards. The players are numbered from 1 to n, so that players i and i+1 are neighbours (as well as players 1 and n). Each of them has exactly k cards, where k is even. The left neighbour of a player i is player i - 1, and their... | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
... |
You are given an array a_1, a_2, …, a_n consisting of n positive integers and a positive integer m.
You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.
Let's call an array m-divisible if for each two adjacent numbers in the array (two numbers on the pos... | #include<bits/stdc++.h>
#define ll long long
#define rep(i, m, n) for (int i = m; i <= n; i++)
#define per(i, m, n) for (int i = m; i >= n; i--)
#define pii pair<int, int>
#define pb push_back
#define mp make_pair
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e5 + 5;
int a[maxn], cnt[maxn];
int main(... |
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.
To make a toast, each friend needs nl ... | party = list(map(int, input().split()))
friends, bottles, ml, limes, lime_slices, salt, friend_ml, friend_salt = party
total_gas = bottles * ml
total_limes = limes * lime_slices
rotation_ml = friend_ml * friends
q_tosts = -1
while all(x >= 0 for x in (salt, total_gas, total_limes)):
total_gas -= rotation_ml
... |
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 ≤ ... | import sys
import bisect
#import math
#import itertools
def get_line(): return list(map(int, sys.stdin.readline().strip().split()))
def in1(): return int(input())
def decimalToBinary(n): return bin(n).replace("0b", "")
for _ in range(in1()):
t=get_line()
a1,a2=get_line()
b1,b2=get_line()
f1,f2=get_lin... |
Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following:
function rangeIncrement(l,... | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.io.Writer;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.TreeMap;
impor... |
John Doe has four arrays: a, b, k, and p. Each array consists of n integers. Elements of all arrays are indexed starting from 1. Array p is a permutation of integers 1 to n.
John invented a game for his friends and himself. Initially a player is given array a. The player must consecutively execute exactly u operations... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
bool ch(int num) {
int cur = 3;
while (cur <= num) {
if ((cur & num) == cur) {
return 0;
}
cur <<= 1;
}
return 1;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, u, r;
cin >> n >> u >> r;
vector<in... |
Fibonacci numbers are the sequence of integers: f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ..., fn = fn - 2 + fn - 1. So every next number is the sum of the previous two.
Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he perf... | #include <bits/stdc++.h>
using namespace std;
int f(int a, int b) {
int cnt = 1;
while (a != b) {
if (a <= 0 || b <= 0) break;
if (a > b) {
cnt += (a - 1) / b;
a -= ((a - 1) / b) * b;
} else {
cnt += (b - 1) / a;
b -= ((b - 1) / a) * a;
}
}
return a * b == 1 ? cnt : -1;
}... |
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the e... | #include <bits/stdc++.h>
using namespace std;
int main() {
int x, y, a, b;
cin >> x >> y >> a >> b;
vector<pair<int, int> > v;
vector<pair<int, int> > w;
for (int i = a; i <= x; i++) {
for (int j = b; j <= y; j++) {
if (i > j) w.push_back(make_pair(i, j));
}
}
cout << w.size() << endl;
for... |
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the ri... | #include <bits/stdc++.h>
using namespace std;
const int M = 100 + 20;
pair<int, int> a[M];
char dir;
vector<int> domino;
vector<pair<int, int> > adj[M];
bool mark[M], check[M];
int cnt, start = -1, p[M];
void dfs(int v) {
while (!adj[v].empty()) {
int u = adj[v].back().first;
int ind = adj[v].back().second;
... |
<image>
Input
The input contains two integers a1, a2 (0 ≤ ai ≤ 32), separated by a single space.
Output
Output a single integer.
Examples
Input
1 1
Output
0
Input
3 7
Output
0
Input
13 10
Output
1 | num = input().split()
print(int(num[0]) + int(num[1][::-1]))
|
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get th... | import java.util.*;
import java.math.*;
public class A
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
char[] S = in.next().toCharArray();
boolean[] alph = new boolean[26];
int wilds = 0;
int N = S.length;
for (int i = 0; i < N; i++)
if (S[i] == '?')
wilds++;
e... |
Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. GCD(a, b) is the greatest common divisor of numbers a and b.
You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, s... | #include <bits/stdc++.h>
using namespace std;
long long a[10000 + 5];
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
void exgcd(long long a, long long b, long long &x, long long &y) {
if (b == 0) {
x = 1;
return;
}
long long xp, yp;
exgcd(b, a % b, xp, yp);
... |
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.
Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Input
The ... | n, p = map(int, input().split())
for i in range(n):
arr = []
for j in range(n):
arr.append("0")
arr[i] = str(p)
answer = " ".join(arr)
print(answer) |
Iahub got lost in a very big desert. The desert can be represented as a n × n square matrix, where each cell is a zone of the desert. The cell (i, j) represents the cell at row i and column j (1 ≤ i, j ≤ n). Iahub can go from one cell (i, j) only down or right, that is to cells (i + 1, j) or (i, j + 1).
Also, there a... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 100000 + 10;
struct Pos {
int x, y;
bool operator<(const Pos &b) const {
return x < b.x || (x == b.x && y < b.y);
}
} pos[MaxN];
int n, m;
vector<Pos> v, nv;
int nowx, st, ed, p, q;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; +... |
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.
The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is ... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
bool cmp(pair<long long, long long> a, pair<long long, long long> b) {
if (a.first == b.first)
return a.second < b.second;
else
return a.first < b.first;
}
long long exp(long long a, long long b) {
long long ans = 1;
while (b != 0) {... |
You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character.
Let's introduce several definitions:
* A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj.
* The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l].
* The suffix of string s o... | def zeta(s):
n = len(s)
z = [0]*n
l,r = 0,0
for i in range(1,n):
if(i<=r): z[i] = min(r-i+1,z[i-l])
while(i+z[i]<n and s[z[i]]==s[i+z[i]]):
z[i]+=1
if(i+z[i]-1>r):
l=i
r = i+z[i]-1
return z
s = input()
n = len(s)
z = zeta(s)
l = [0]*n
for i in z:
l[i]+=1
cum = [l[-1]]
for i in range(n-2,-1,-1):
cu... |
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and... | n = int(input())
l = input().split()
g = [0]*100000
for i in l:
g[int(i)-1] += 1
'''
p = []
a = []
for i in range(100000):
b = g[i]
if b!=0:
a.append((i+1)*b)
else:
if a != []:
p.append(a)
a = []
def f(v):
if v==[]:
return 0
elif len(v)==1:
... |
Dreamoon saw a large integer x written on the ground and wants to print its binary form out. Dreamoon has accomplished the part of turning x into its binary format. Now he is going to print it in the following manner.
He has an integer n = 0 and can only perform the following two operations in any order for unlimited ... | #include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
const int mod = 1000000007;
const int INF = 1000000010;
int n;
char S[5020];
int L[5010];
int C[5010];
int RV;
pair<int, int> RM;
int lookup[5010];
int val[5010][15];
int hp[5010][5010];
int H[13][(1 << 13) + 3];
void kmr(... |
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | a, b = map(int, input().split())
c = list(map(int, input().split()))
d = 0
while d < b - 1:
d += c[d]
if d == b - 1:
print("YES")
else:
print("NO") |
Finally it is a day when Arthur has enough money for buying an apartment. He found a great option close to the center of the city with a nice price.
Plan of the apartment found by Arthur looks like a rectangle n × m consisting of squares of size 1 × 1. Each of those squares contains either a wall (such square is denot... | #include <bits/stdc++.h>
using namespace std;
int n, m;
char g[2005][2005];
bool check(int x, int y) {
if (g[x][y] == '.' || x < 0 || y < 0 || x >= n || y >= m) return 0;
if (g[x][y - 1] == '.' && g[x - 1][y - 1] == '.' && g[x - 1][y] == '.')
return 1;
if (g[x - 1][y] == '.' && g[x - 1][y + 1] == '.' && g[x][... |
Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false.
Implication is written by using character '<image>', and the arguments and the result of the implication are written as '0' (false) and '1' (true... | n = int(input())
c = list(map(int, input().split()))
idx = [i for i in range(n) if c[i] == 0]
one = [i for i in range(n) if c[i] == 1]
if len(idx) >= 1 and idx[-1] == n-1:
if len(idx) >= 2 and idx[-2] == n-2:
if len(idx) >= 3 and idx[-3] <= n-3:
if idx[0] == 0:
print("YES")
... |
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positiv... | def bin_search(tar, mini):
start = 1
end = 2000000002
while(start <= end):
mid = (start+end)/2
if tar/mid < mini:
end = mid-1
continue
if tar/(mid+1) < mini: return tar/mid
start = mid+1
return float('inf')
def calc(a, b):
first = bin_search(... |
Recently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from 1 to 3n, and a... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
using namespace std;
template <class T>
void pv(T a, T b) {
for (T i = a; i != b; ++i) cout << *i << " ";
cout << endl;
}
int f[1 << 20];
int n, N, k;
struct S {
int a, b, c;
S() {}
S(int a, int b, int c) : a(a), b(b), c(c) { ord(); }
void ... |
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the onl... | a=[0]*2001
b=[0]*2001
n=int(input())
for i in range(n):
x,y=map(int,input().split())
a[x+y]+=1
b[x-y]+=1
s=0
for i in a:
s=s+(i-1)*i//2
for i in b:
s=s+(i-1)*i//2
print(s) |
Little Artem is given a graph, constructed as follows: start with some k-clique, then add new vertices one by one, connecting them to k already existing vertices that form a k-clique.
Artem wants to count the number of spanning trees in this graph modulo 109 + 7.
Input
First line of the input contains two integers n... | #include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
ostream &operator<<(ostream &s, const pair<A, B> &p) {
return s << "(" << p.first << "," << p.second << ")";
}
template <typename T>
ostream &operator<<(ostream &s, const vector<T> &c) {
s << "[ ";
for (auto it : c) s << it << " ";
... |
Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int a[100000];
for (int i = 0; i < n; i++) cin >> a[i];
int b[100000];
for (int i = 0; i < n; i++) cin >> b[i];
int r[100000], l[100000];
int min = 0;
int tmp = 0;
for (int i = 1; i < n; i++) {
tmp -= b[i - 1];
if (t... |
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.
<image> English alphabet
You are given a... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, j, k, f;
string s;
char cap[15] = {'A', 'H', 'I', 'M', 'O', 'T', 'U', 'V',
'W', 'X', 'Y', 'o', 'v', 'w', 'x'};
cin >> s;
i = 0;
j = s.length() - 1;
while (i <= j) {
if (s[i] == s[j]) {
for (k = 0; k < 15; k++)... |
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not n... | import java.util.*;
import java.io.*;
public class CF372B {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
void solve() throws IOException {
char[] arr = nextString().toCharArray();
int len = arr.length;
... |
Ostap Bender is worried that people started to forget that he is the Great Combinator. Now he wants to show them his skills in combinatorics. Now he studies the permutations of length n. He has a list of m valid pairs, pair ai and bi means that he is allowed to place integers bi at position ai.
He knows that the numbe... | #include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "RDLU";
long long ln, lk, lm;
void etp(bool f = 0) {
puts(f ? "YES" : "NO");
exit(0);
}
void addmod(int &x, int y, int mod = 1000000007) {
x += y;
if (x >= mod) x -= mod;
... |
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.
The fare is constructed in the following manner. There are three types of tickets:
1. a tic... | #include <bits/stdc++.h>
const int MOD = 1e9 + 7;
using namespace std;
template <typename T>
T max1(T a, T b) {
return a > b ? a : b;
}
template <typename T>
T min1(T a, T b) {
return a < b ? a : b;
}
template <typename T>
T max1(T a, T b, T c) {
return max1(a, max1(b, c));
}
template <typename T>
T min1(T a, T b... |
A new bus route is opened in the city <image>. The route is a closed polygon line in the place, with all segments parallel to one of the axes. m buses will operate on the route. All buses move in a loop along the route in the same direction with equal constant velocities (stopping times are negligible in this problem).... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9, inf = 1e9 + 9;
struct segment {
double l, r;
bool operator<(const segment &temp) const { return l < temp.l; }
};
segment sg[1000000], now;
int cnt_sg;
struct point {
double x, y;
};
point pt[110000];
int n, m;
double low, high, mid, T;
int low... |
Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. MoJaK doesn't ... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long sc = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') sc = sc * 10 + ch - '0', ch = getchar();
return sc * f;
}
int main() {
int n ... |
Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.
Let the queue to the cashier contain n people, at that each of them is characterized by a positive integer ai — that is the time needed to work with this customer. What is special about this... | import java.io.*;
import java.util.*;
public class TwoOutOfThree {
long[][] r;
int[] a;
final long inf = Long.MAX_VALUE / 2;
int n;
long go(int i, int t) {
if (i >= n) {
if (t == n)
return 0;
else
return a[t];
}
if (r[i][t] != -1) {
return r[i][t];
}
r[i][t] = inf;
if (t == n... |
You have a bag of balls of n different colors. You have ai balls of the i-th color.
While there are at least two different colored balls in the bag, perform the following steps:
* Take out two random balls without replacement one by one. These balls might be the same color.
* Color the second ball to the color ... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * w;
}
const long long p = 10000... |
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then... | #include <bits/stdc++.h>
using namespace std;
int n, i, R, x, c[333333];
void add(int x) {
for (; x; x -= x & -x) c[x]++;
}
int qu(int x) {
if (!x) return 0;
int V = 0;
for (; x <= n; x += x & -x) V += c[x];
return V;
}
int main() {
scanf("%d", &n);
R = n;
printf("1");
for (int i = 1; i <= n; i++) {
... |
It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right.
Unfortunately, Joe ... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("unroll-loops")
using namespace std;
template <typename A>
ostream &operator<<(ostream &cout, vector<A> const &v);
template <typename A, typename B>
ostream &operato... |
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.
For some indices i (1 ≤ i ≤ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v;
int a[n];
int b[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
v.push_back(a[i]);
b[i] = a[i];
}
sort(b, b + n);
string s;
cin >> s;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '1') {
... |
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences o... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.Scanner;
import java.util.LinkedList;
import java.util.ArrayList;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author dima
*... |
You are given a bipartite graph G = (U, V, E), U is the set of vertices of the first part, V is the set of vertices of the second part and E is the set of edges. There might be multiple edges.
Let's call some subset of its edges <image> k-covering iff the graph <image> has each of its vertices incident to at least k e... | #include <bits/stdc++.h>
using namespace std;
int n1, n2, m, deg[5010], id[5010], mn = 0x3f3f3f3f;
namespace MaxFlow {
const int N = 5000, M = 2000000;
int head[N], cur[N], dep[N], cnt, S, T, res;
struct node {
int to, next, val;
} edge[M];
void ae(int u, int v, int w) {
edge[cnt].next = head[u], edge[cnt].to = v, ... |
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m... | import java.util.*;
public class SuitAndTie {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[] a=new int[2*n];
Integer[][] ind=new Integer[n][2];
int[] dist=new int[n];
for(int i=0;i<2*n;i++) {
int x=scan.nextInt()-1;
a[i]=x;
if(ind[x][0... |
Ross, Chandler and Joey are best friends. One day they went to pond and Joey suggest them to play the game "Bamboozle". In this game they have N balls with each numbered from 0-9, but first ball is numbered from 1-9. Ross tells sub-strings 'S' formed by those balls and Chandler throws S stones into the pond. At last, J... | s=raw_input()
len1=len(s)
mul_ten=1
sum1=1
total_sum=len1*int(s[len1-1])
for i in range(len1-2,-1,-1):
mul_ten=(mul_ten*10)%1000000007
sum1=sum1+mul_ten
total_sum=(total_sum+(sum1*(i+1))*int(s[i]))%1000000007
print total_sum%1000000007 |
Fatland is a town that started with N distinct empires, namely empires 1, 2, ..., N. But over time, the armies of some of these empires have taken over other ones. Each takeover occurred when the army of empire i invaded empire j. After each invasion, all of empire j became part of empire i, and empire j was renamed as... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def root(i):
global x
while i != x[i]:
i = x[i]
return i
n = raw_input().strip()
if len(n.split()) > 1:
(n, m) = map(int, n.split())
else:
n = int(n)
m = int(raw_input().strip... |
Having gained some experience with Prime Numbers, Robin now seeks Revenge from Bruce. So, while they are on their way from the Airport to the Summit, Robin comes up with a new Prime based Puzzle for Bruce.
He asks him to find rad(n) for t numbers which he lists before Bruce and then form a sorted table on the values o... | limit=100000
rad={}
buf={}
for i in range(1,limit+1):
rad[i]=1
for j in range(1,limit+1):
buf[j]=""
for i in range(2,limit+1):
if rad[i]==1:
for j in range(i,limit+1,i):
rad[j]=rad[j]*i
hey=rad[i]
buf[hey]=buf[hey]+" "+str(i)
str=""
for i in buf.keys():
str=str+buf[i]
str=str.split(" ")
str[0]=1
... |
Ruchi is doing her undergrad in Maths from a reputed college in New Delhi. Recently her professor gave her a problem which is baffling her for a long time. So she asks your help.
Problem is:
Given order of n x n matrix is it possible to find two matrices such that when there corresponding elements are combined in the... | for _ in range(input()):
if input() in [2, 6]:
print "No"
else:
print "Yes" |
A Magic Fraction for N is one that has the following properties:
It is a proper fraction (The value is < 1)
It cannot be reduced further (The GCD of the numerator and the denominator is 1)
The product of the numerator and the denominator is factorial of N. i.e. if a/b is the fraction, then a*b = N!
Examples of Magic F... | i=0;
arr=[]
while i<=500:
arr.append(True)
i+=1
i=2
while i<=500:
if arr[i]==True:
j=2*i
while j<=500:
arr[j]=False
j+=i
i+=1
p=[]
p.append(1)
i=1
while i<=500:
p.append(2*p[i-1])
i+=1
ans=0
s=input()
n=int(s);
cnt=0
if n is 1:
print ("0")
else:
i=2
while i<=n:
if arr[i]==True:
cnt+=1
an... |
Our hero - Maga is going to make a new contest for making the best teams. He is really excited about it. There will be S students in the contest. First N students in the final standings will be awarded.
He has a list( favourite students list ) what contains the best students in informatics Olympiad. His favorite stud... | matrix = [[0 for x in range(1007)] for x in range(1007)]
n=int(1001)
k=int(1001)
for i in range(0,n+1):
temp=min(i,k)
temp=temp+1
for j in range(0,temp):
if(j==0):
matrix[i][j]=1
elif(j==i):
matrix[i][j]=1
else:
matrix[i][j]=matrix[i-1][j-1]+matrix[i-1][j]
testcase=raw_input()
testcase=int(testcase)
f... |
The professor is conducting a course on Discrete Mathematics to a class of N students. He is angry at the lack of their discipline, and he decides to cancel the class if there are fewer than K students present after the class starts.
Given the arrival time of each student, your task is to find out if the class gets ca... | for _ in range(input()):
n,k=map(int,raw_input().split())
a=map(int,raw_input().split())
c=0
for i in range(n):
if(a[i]<=0):
c+=1
if(c>=k):
print "NO"
else:
print "YES" |
Recently Watson learned the concept of coprime numbers and now he wonders given an array A1, A2 . . . AN what is the size of the largest subset of the array such that the each pair of elements in the subset is coprime.
Watson asks Sherlock for help and in turn Sherlock needs you.
Input
First line contains T, the num... | def prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
primes = [i for i in range(2, 51) if prime(i)]
def f(n):
ans = 0
for p in primes:
if n % p == 0:
ans += 1
return ans
def gcd(a, b):
while b:
a, b = b, a % b
return a
... |
Many of us are familiar with collatz sequence. Know the problem is, There is a fight going between the students of the class they have splitted up into two groups the odd rulers and the even rulers. To resolve this fight sir will randomly pick up the numbers and are written on the board. Teacher stated that if the tota... | for _ in range(input()):
num = input()
oddsum = 1
evensum = 0
totsteps = 0
while num > 1:
if num % 2 == 0:
evensum += num
num /= 2
else:
oddsum += num
num = (3 * num) + 1
totsteps += 1
evenrem = evensum % totsteps
oddrem = oddsum % totsteps
if oddrem > evenrem:
print "Odd Rules"
elif oddrem... |
Xenny had a list of N strings of equal length. He wanted to sort them by the first M characters only. That means, while sorting the list of strings, he only wanted to consider the first M characters of each string.
Help Xenny to find out the K^th string in the list after he sorts them.
Note: Xenny wanted to perform st... | for i in range(input()):
l=[int(x) for x in raw_input().split()]
l1=[]
l2=[]
l3=[]
l4=[]
for j in range(l[0]):
a=raw_input()
l1.append(a)
for k in range(0,len(l1)):
l2.append(l1[k][0:l[2]])
l3.append(l1[k][l[2]:])
for m in range(0,len(l2)):
l4.append(l2[m])
l2.sort()
h=l4.index(l2[l[1]-1])
print(l4... |
In a two-dimensional plane, we have a rectangle R whose vertices are (0,0), (W,0), (0,H), and (W,H), where W and H are positive integers. Here, find the number of triangles \Delta in the plane that satisfy all of the following conditions:
* Each vertex of \Delta is a grid point, that is, has integer x- and y-coordinat... | #include <bits/stdc++.h>
#define long long long int
using namespace std;
// @author: pashka
int gcd(int a, int b) {
while (b > 0) {
int c = a % b;
a = b;
b = c;
}
return a;
}
map<pair<int, int>, int> mem;
int get(int x, int y) {
x = abs(x);
y = abs(y);
return gcd(x, y... |
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`.
Constraints
* 2 ≤ N ≤ 200000
* 1 ≤ A_i ≤ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 ... A_N
Output
If the elements... | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
HashSet<Integer> a = new HashSet<>();
int A = 0;
for(int i = 0; i < N; i++) {
A=sc.nextInt();
a.add(A);
}
if(a.size() == N) {
System.out.... |
We have N non-negative integers: A_1, A_2, ..., A_N.
Consider painting at least one and at most N-1 integers among them in red, and painting the rest in blue.
Let the beauty of the painting be the \mbox{XOR} of the integers painted in red, plus the \mbox{XOR} of the integers painted in blue.
Find the maximum possibl... | #include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main(){
ios::sync_with_stdio(0),cin.tie(0);
int n;
cin >> n;
int a[n],x=0,b[60]={0};
for(int i=0;i<n;i++){
cin >> a[i];
x^=a[i];
}
for(int i=0;i<n;i++){
for(int j=0;j<60;j++){
if(... |
Snuke received a positive integer N from Takahashi. A positive integer m is called a favorite number when the following condition is satisfied:
* The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.
Find all favorite numbers and print the sum of those.
Con... | import java.io.*;
import java.util.*;
class Main {
static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}... |
There is a sequence of length 2N: A_1, A_2, ..., A_{2N}. Each A_i is either -1 or an integer between 1 and 2N (inclusive). Any integer other than -1 appears at most once in {A_i}.
For each i such that A_i = -1, Snuke replaces A_i with an integer between 1 and 2N (inclusive), so that {A_i} will be a permutation of 1, 2... | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int , int> P2;
typedef pair<pair<int , int> , int> P3;
typedef pair<pair<int , int> , pair<int , int> > P4;
#define PB(a) push_back(a)
#define MP(a , b) make_pair((a) , (b))
#define M3P(a , b , c) make_pair(make_pair((a) , (b)) , (c))
#d... |
You are given a string S of length N consisting of lowercase English letters. We will cut this string at one position into two strings X and Y. Here, we would like to maximize the number of different letters contained in both X and Y. Find the largest possible number of different letters contained in both X and Y when ... | import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
int N = scn.nextInt();
String S = scn.next();
int[] visited1 = new int[26];
int[] visited2 = new int[26];
int c1=0, c2=0, max=-1;
for(int i=0;i<N;i++){
char ch=S.charAt... |
There are N non-negative integers written on the blackboard: A_1, ..., A_N.
Snuke can perform the following two operations at most K times in total in any order:
* Operation A: Replace each integer X on the blackboard with X divided by 2, rounded down to the nearest integer.
* Operation B: Replace each integer X on t... | #include<cstdio>
#include<cstring>
#include<iostream>
#include<stdlib.h>
#include<ctime>
#include<string>
#include<cmath>
#include<algorithm>
#include<complex>
#include<vector>
#include<set>
#include<map>
#include<queue>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define LL long long
#... |
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.
They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card.
Let th... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, a[];
long psum[], sum = 0;
n = sc.nextInt();
a = new int[n];
psum = new long[n];
for (int i = 0; i < n; ++i) {
a[i] = sc.nextInt();
sum += a[i];
psum[i] = sum;
... |
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.
Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:
* Operation: Rotate the die 90° tow... | import java.math.BigDecimal;
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
long X = sc.nextLong();
if (X <= 6) {
System.out.println(1);
} else {
long numOfSet = X / 11; // set is (6... |
Mikan's birthday is coming soon. Since Mikan likes graphs very much, Aroma decided to give her a undirected graph this year too.
Aroma bought a connected undirected graph, which consists of n vertices and n edges. The vertices are numbered from 1 to n and for each i(1 \leq i \leq n), vertex i and vartex a_i are connec... | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
#define eb emplace_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
using vint=vector<int>;
using pint=pair<int,int>... |
Aizuwakamatsu City is known as the "City of History". About 400 years ago, the skeleton of the castle town was created by Gamo Ujisato, but after that, it became the central city of the Aizu clan 230,000 stones, whose ancestor was Hoshina Masayuki, the half-brother of Tokugawa's third shogun Iemitsu. Developed. Many to... | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <climits>
static int const N = 100;
int main()
{
for(;;) {
int n, m;
std::cin >> n;
if ( n == 0 )
break;
std::cin >> m;
int G[N][N] = {};
for( int i=0; i<N; ++i )
std::fill( G[i], G[i] + N, INT_MAX );
for( ... |
In 40XX, the Earth was invaded by aliens! Already most of the Earth has been dominated by aliens, leaving Tsuruga Castle Fortress as the only remaining defense base. Suppression units are approaching the Tsuruga Castle Fortress one after another.
<image>
But hope remains. The ultimate defense force weapon, the ultra... | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <list>
#include <iostream>
#include <sstream>
#include <climits>
#include <cfloat>
#include <complex>
using namespace std;
typedef com... |
You are given a string and a number k. You are suggested to generate new strings by swapping any adjacent pair of characters in the string up to k times. Write a program to report the lexicographically smallest string among them.
Input
The input is given in the following format.
s
k
The first line provides a st... | #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(ll i=0;i<n;i++)
#define repl(i,l,r) for(ll i=(l);i<(r);i++)
#define per(i,n) for(ll i=n-1;i>=0;i--)
#define perl(i,r,l) for(ll i=r-1;i>=l;i--)
#define fi first
#define se second
#define pb push_back
#define ins insert
#define pqueue(x) priority_queue<x,v... |
An art exhibition will be held in JOI. At the art exhibition, various works of art from all over the country will be exhibited.
N works of art were collected as candidates for the works of art to be exhibited. These works of art are numbered 1, 2, ..., N. Each work of art has a set value called size and value. The siz... | #include <iostream>
#include <algorithm>
#include <vector>
using lint = long long;
constexpr lint INF = 1LL << 60;
void solve() {
int n;
std::cin >> n;
std::vector<std::pair<lint, lint>> ps(n);
for (auto& p : ps) std::cin >> p.first >> p.second;
std::sort(ps.begin(), ps.end());
lint ans = 0... |
Prof. Hachioji has devised a new numeral system of integral numbers with four lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5", "6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system.
The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1, respectively, and ... | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
int mcxi_to_i(string s) {
int ans = 0;
int keta = 1;
for(unsigned int i=0; i<s.size(); i++) {
switch(s[i]) {
case 'm': ans += 1000 * keta; keta = 1; break;
case 'c':... |
Your task in this problem is to create a program that finds the shortest path between two given locations on a given street map, which is represented as a collection of line segments on a plane.
<image>
Figure 4 is an example of a street map, where some line segments represent streets and the others are signs indicat... | #include <cstdio>
#include <iostream>
#include <vector>
#include <list>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <iterator>
#include <cstdlib>
#include <cstring>
#include <sstream>
using namespace std;
#define... |
Draw in Straight Lines
You plan to draw a black-and-white painting on a rectangular canvas. The painting will be a grid array of pixels, either black or white. You can paint black or white lines or dots on the initially white canvas.
You can apply a sequence of the following two operations in any order.
* Painting p... | #include<stdio.h>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<assert.h>
#include<set>
#include<cmath>
#include<queue>
#include<cstdlib>
#include<iostream>
#include<bitset>
#define pii pair<int,int>
#define fi first
#define se second
#define pb push_back
#define rep(i,j,k) for(int i=(in... |
<!--
Problem E
-->
Cube Surface Puzzle
Given a set of six pieces, "Cube Surface Puzzle" is to construct a hollow cube with filled surface. Pieces of a puzzle is made of a number of small unit cubes laid grid-aligned on a plane. For a puzzle constructing a cube of its side length n, unit cubes are on either of the f... | #include<cstdio>
#include<vector>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
#define f(i,n) for(int i=0;i<(int)n;i++)
#define N 1010000
vector<int>b;
vector<int>s;
vector<int>r;
int n, k;
char a[N];
int main(void) {
int a[6][4][2];
int r[6][4][2];
int num[24][4];
... |
Issac H. Ives hosted a party for girls. He had some nice goods and wanted to distribute them to the girls as the presents. However, there were not enough number of presents and thus he needed to decide who would take them. He held a game for that purpose.
Before the game, Issac had all the girls divided into two teams... | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
//Girls' Party
public class Main{
int N, res;
Set<String>[] v;
void dfs(int nb, int ng, int z, String s){
if(nb<=res)return;
if(ng==0){
res = nb; return;
}
if(v[z].contains(s))return;
v[z].add(s);
int n = s.length(), d = (N-... |
N people run a marathon. There are M resting places on the way. For each resting place, the i-th runner takes a break with probability P_i percent. When the i-th runner takes a break, he gets rest for T_i time.
The i-th runner runs at constant speed V_i, and the distance of the marathon is L.
You are requested to com... | #include<stdio.h>
#include<algorithm>
using namespace std;
int p[110];
int t[110];
int v[110];
double dp[110][110];
double prob[110][110];
int main(){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
for(int i=0;i<a;i++){
scanf("%d%d%d",p+i,t+i,v+i);
for(int j=0;j<=b;j++)for(int k=0;k<=b;k++)dp[j][k]=0;
dp[0][0]=1;
for(... |
You are a secret agent from the Intelligence Center of Peacemaking Committee. You've just sneaked into a secret laboratory of an evil company, Automated Crime Machines.
Your mission is to get a confidential document kept in the laboratory. To reach the document, you need to unlock the door to the safe where it is kept... | #include<cstdio>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
int gcd(int a,int b){ return b?gcd(b,a%b):a; }
int main(){
int n,m; scanf("%d%d",&n,&m);
rep(i,m){
int l; scanf("%d",&l);
n=gcd(n,l);
}
puts(n==1?"Yes":"No");
return 0;
} |
You and your grandma are playing with graph automata, which is generalization of cell automata.
A graph automaton is expressed by a graph. The vertices of the graph have a time-dependent value, which can be either 0 or 1. There is no more than one edge between any of two vertices, but self-loops might exist.
The valu... | #include<bits/stdc++.h>
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
/*Gauss_Jordan(2?????°???????????§???)
O(n^3)
Ax=b????§£??? A?????£?????????
?§£???????????¨??????????????????????????????
?§£???????????§????????¨?????????n+1??????????????????
N???????????°??§M??????????¨??????... |
E: Arai's --Arai's-
problem
Arai's is a female idol group that has been popular since the school idol era. Nowadays, it is active at the world level as a large group to which many "Arai" belong. And today, it was decided to start a new project. They decided to try to further increase sales by forming several small un... | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
using ll = long long;
template<int V>
struct MinConstFlow {
using C = int;
using T = int;
const T INF = 1<<28;
using P = pair<T, int>;
struct Edge {
int to, rev;
C cap;
T cost;... |
You received a card with an integer $S$ and a multiplication table of infinite size. All the elements in the table are integers, and an integer at the $i$-th row from the top and the $j$-th column from the left is $A_{i,j} = i \times j$ ($i,j \geq 1$). The table has infinite size, i.e., the number of the rows and the n... | #include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
int S;
int ans = 0, con = 0;
map<int,int> mp;
cin>>S;
for(int i = 1; i <= S; i++){
for(int j = i, sum = i; sum <= S; j++){
mp[sum]++;
// cout<<"i "<<i<<" j "<<j<<" "<<sum<<endl;
sum += j+1;
... |
Problem
At the boys' school where Bit-kun attends, a Kippo game is played during the lunch break.
This school's Kippo game is famous for being a little strange.
First, prepare a $ N $ book ticket. The length of the $ i $ first ticket is $ a_i $.
The first move and the second move eat Kippo alternately.
If you eat a gr... | #include <bits/stdc++.h>
using namespace std;
void prians(bool answer) {
if(answer)
cout << "First" << endl;
else
cout << "Second" << endl;
}
long long n, d;
long long a[300005] = {0};
long long ans = 0;
int main() {
cin >> n >> d;
for(int i = 0; i < n; ++i) cin >> a[i];
for(int i = 0; i < n; ++i) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.