input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length — the first one from string a, the second one from string b. The choi... | #include <bits/stdc++.h>
using namespace std;
char a[200020];
char b[200020];
int d[30];
int e[30];
long long c[30];
long long s[30];
double z;
int n;
int main() {
scanf("%d", &n);
scanf("%s", a);
scanf("%s", b);
for (int i = 0; i < n; i++) {
s[a[i] - 'A'] += i, d[a[i] - 'A']++;
c[b[i] - 'A'] += i, e[b[... |
You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails need... | import java.io.*;
import java.util.*;
//java.is.awesome
public class R22qDSegments {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt();
Pair p[] = new Pair[n];
for(int i = 0; i < n; i++)
p[i] = new Pa... |
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:
* a1 = p, where p is some integer;
* ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is som... | import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
public class AlmostArithmeticalProgression {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
Integ... |
You've got an array, consisting of n integers a1, a2, ..., an. Also, you've got m queries, the i-th query is described by two integers li, ri. Numbers li, ri define a subsegment of the original array, that is, the sequence of numbers ali, ali + 1, ali + 2, ..., ari. For each query you should check whether the correspon... | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Ladder {
static int mod = 1000000007;
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Re... |
Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the c... | #include <bits/stdc++.h>
using namespace std;
int Abs(int x) {
if (x < 0) return -x;
return x;
}
vector<pair<int, int> > g[128];
int a[128], x[128], y[128];
int n, d;
int cost[128], dist[128];
int dijkstra() {
priority_queue<pair<int, int> > q;
q.push(make_pair(0, 0));
for (int i = 0; i < n; ++i) cost[i] = 1 ... |
Iahub wants to meet his girlfriend Iahubina. They both live in Ox axis (the horizontal axis). Iahub lives at point 0 and Iahubina at point d.
Iahub has n positive integers a1, a2, ..., an. The sum of those numbers is d. Suppose p1, p2, ..., pn is a permutation of {1, 2, ..., n}. Then, let b1 = ap1, b2 = ap2 and so on.... | #include <bits/stdc++.h>
using namespace std;
int INP, AM, REACHEOF;
char BUF[(1 << 12) + 1], *inp = BUF;
const long double PI = acos((long double)-1.0);
const long long MOD = 1000000007LL;
const int oo = 1000000001;
;
int n, a[25], x[25], k;
int sum[(1 << (24))], f[(1 << (24))];
int main() {
while (scanf("%d", &n) =... |
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u... | import math
n = int(raw_input())
heights = map(int, raw_input().split())
best = 1 << 20
ans = None
for i, iv in enumerate(heights):
right = (i + 1) % n
left = (i-1) % n
d = abs(iv - heights[left])
if d < best:
best = d
ans = (left, i)
d = abs(iv - heights[right])
if d < best:... |
We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.
You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)·k to add the number n to the sequence.
You can spend a cost up... | from math import *
w, m, k = list(map(int, input().split()))
cnt = 0
add = 9*10**(-1) if m < 10 else 0
for i in range(int(log10(m)), int(1e10)):
v = (9 * 10**i - (m-1-9*10**(i-1)+add if i == int(log10(m)) else 0)) * (i+1) * k
if w - v < 0:
cnt += w//((i+1)*k)
break
w -= v
cnt += v//(k*(... |
The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.
To achieve the goal, the gym teacher ordered a lot of magical buns from the dining ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 5;
int a[maxn];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
int ans = 1e9, s, d;
for (int i = 0; i <= 20000; i++) {
int l = 1e9, r = -1e9;
for (int j = 1; j <= n; j+... |
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column... | #include <bits/stdc++.h>
using namespace std;
int a[100];
int b[100];
void get(int a[], int n) {
int i;
if (n == 1) {
a[0] = 1;
} else if (n == 2) {
a[0] = 3;
a[1] = 4;
} else if (n % 2 == 0) {
for (i = 0; i < n - 1; i++) a[i] = 1;
a[n - 1] = n / 2 - 1;
} else {
for (i = 0; i < n - 2; ... |
DZY loves colors, and he enjoys painting.
On a colorful day, DZY gets a colorful ribbon, which consists of n units (they are numbered from 1 to n from left to right). The color of the i-th unit of the ribbon is i at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first.
... | #include <bits/stdc++.h>
using namespace std;
mt19937 Rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
template <typename T>
inline void chkmax(T &x, T y) {
if (x < y) x = y;
}
template <typename T>
inline void chkmin(T &x, T y) {
if (x > y) x = y;
}
inline int read() {
int x = 0;
char c = ... |
Peter has a sequence of integers a1, a2, ..., an. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment... | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Trung Pham
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReade... |
Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving ... | import java.util.*;
import java.io.*;
public class Solve{
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(new InputStreamReader(System.in));;
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
int[][] ar=new i... |
You are given an array of length n and a number k. Let's pick k non-overlapping non-empty subarrays of the initial array. Let si be the sum of the i-th subarray in order from left to right. Compute the maximum value of the following expression:
|s1 - s2| + |s2 - s3| + ... + |sk - 1 - sk|
Here subarray is a contiguou... | #include <bits/stdc++.h>
using namespace std;
int dp[30005][205][4], n, m;
int a[30005], b[30005][2];
int main() {
cin >> n >> m;
memset(dp, -0x3f, sizeof(dp));
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++)
dp[i][1][0] = max(dp[i - 1][1][0], 0) + a[i],
dp[i][1][1] = max(dp[i - 1... |
T students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least t students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!)
During a shift ... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5 + 10;
int n, m, f[MAXN], l[MAXN], r[MAXN], opp[MAXN], t, T, N, bel[MAXN], vis[MAXN];
vector<pair<int, pair<int, int> > > L;
int getf(int first) {
if (f[first] == first) return first;
f[first] = getf(f[first]);
return f[first];
}
void fail() {... |
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.
Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed... | #include <bits/stdc++.h>
using namespace std;
void solve(long long tz) {
int n;
cin >> n;
int cnt = 0;
map<pair<int, int>, int> mp;
vector<pair<char, int>> arr;
for (int i = 0; i < n; i++) {
char x;
int y;
cin >> x >> y;
arr.push_back({x, y});
if (x == '-') {
auto it = mp.find({'+'... |
While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denot... | #include <bits/stdc++.h>
using namespace std;
long long N, K, L;
int A[1000010];
int B[1000010];
long long howMany;
long long dp[1000010];
long long pref[1000010];
long long totalAns;
void f1() {
for (int i = 1; i <= N; i++) {
pref[i] = pref[i - 1] + 1;
}
totalAns += (pref[N] * (howMany % 1000000007)) % 10000... |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | x=int(input())
print((x%2==0)*((x//2-1)//2))
#fueaijskrgd/t
|
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible ... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
int main() {
long long int n;
cin >> n;
long long int m = n;
m -= (n / 2);
m -= (n / 3);
m -= (n / 5);
m -= (n / 7);
m += (n / 6);
m += (n / 10);
m += (n / 14);
m += (n / 15);
m += (n / 21);
m += (n / 35);
m -= (n / ... |
In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.
Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya'... | #include <bits/stdc++.h>
using namespace std;
bool sorty(const pair<string, long long int> &a,
const pair<string, long long int> &b) {
return a.second > b.second;
}
void initialize(bool flag[], long long int x) {
for (long long int i = 0; i < x; i++) flag[i] = false;
}
long long int t, n, m;
long long in... |
Dima is living in a dormitory, as well as some cockroaches.
At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly T seconds for aiming, and after that he will precisely strike the cockroach and finish it.
To survive the cockroach has to run into a shadow, cast by round pla... | #include <bits/stdc++.h>
using namespace std;
struct debugger {
template <typename T>
debugger& operator,(const T& v) {
cerr << v << " ";
return *this;
}
} dbg;
struct circle {
double x, y, r, a1, a2, d;
} cir[100010];
bool cmp(circle c1, circle c2) {
if (c1.a1 == c2.a1) {
if (c1.a2 == c2.a2) retu... |
Steve Rogers is fascinated with new vibranium shields S.H.I.E.L.D gave him. They're all uncolored. There are n shields in total, the i-th shield is located at point (xi, yi) of the coordinate plane. It's possible that two or more shields share the same location.
Steve wants to paint all these shields. He paints each s... | #include <bits/stdc++.h>
using namespace std;
inline char gc() {
static char buf[100000], *l = buf, *r = buf;
return l == r && (r = (l = buf) + fread(buf, 1, 100000, stdin), l == r)
? EOF
: *l++;
}
template <class T>
void rd(T &x) {
x = 0;
int f = 1, ch = gc();
while (ch < '0' || ch ... |
Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name1price1name2price2...namenpricen", where namei (name of the i-th purchase) is ... | import java.lang.*;
import java.util.*;
import java.io.*;
/**
* Created by Admin on 01.10.2016.
*/
public class B {
public static void main(String[] args) {
new B().run();
}
ArrayList<String> parse(char[] s) {
ArrayList<String> result = new ArrayList<>();
int i = 0;
whil... |
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please not... | import java.util.*;
public class Main{
public static int c = 1;
public static boolean[] boo = new boolean[4];
public static void clear(){
c++;
for (int j = 0; j<4; j++)boo[j]=false;
}
public static void main(String[] args){
Scanner p = new Scanner(System.in);
int ... |
In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).
A group of soldiers is effective if and only if their names... | n,k=map(int,raw_input().split())
U='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
v=[x+y for x in U for y in U.lower()][:n]
for i,x in enumerate(raw_input().split()):
if 'NO'==x:
v[i+k-1]=v[i]
print ' '.join(v)
|
Zane the wizard is going to perform a magic show shuffling the cups.
There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.
The problematic bone is initially at the position x = 1. Zane will confuse the audience b... | n , m , k = list(map(int,input().split()))
h = list(map(int,input().split()))
used = [0] * int(1e7)
for x in h:
used[x] = 1
t = 1
for i in range(k):
u , v = list(map(int,input().split()))
if used[t]:
print(t)
exit(0)
elif u == t:
if used[v] == 1:
print(v)
exit(0)
t = v
elif v == t:
if use... |
On the way to school, Karen became fixated on the puzzle game on her phone!
<image>
The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or col... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline T bigmod(T p, T e, T M) {
if (e == 0) return 1;
if (e % 2 == 0) {
T t = bigmod(p, e / 2, M);
return (t * t) % M;
}
return (bigmod(p, e - 1, M) * p) % M;
}
template <class T>
inline T gcd(T a, T b) {
if (b == 0) return a;
return ... |
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wan... | #include <bits/stdc++.h>
using namespace std;
int N;
vector<int> A, B, BB;
multiset<pair<int, int>> m;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
cin >> N;
for (int i = 0, x; i < N; i++) {
cin >> x;
A.push_back(x);
}
for (int i = 0, x; i < N; i++) {
cin >> x;
B.push_back(x);
BB.pus... |
Mahmoud and Ehab are in the fourth stage now.
Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, cnt = 15, pos0, pos1, s;
int a[N];
int query(int l, int r) {
printf("? ");
int i;
for (i = 1; i < l; ++i) putchar('0');
for (; i <= r; ++i) putchar('1');
for (; i <= n; ++i) putchar('0');
puts("");
fflush(stdout);
--cnt;
int ret;... |
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform:
* U — move from the cell (x, y) to (x, y + 1);
* D — move from (x, y) to (x, y - 1);
* L — move from (x, y) to (x... | import java.util.*;
import java.io.*;
public class solution
{
static int min(int a,int b)
{
if(a>b)
{
return b;
}
return a;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int l = 0;
int r = 0;
int u = 0;
int d = 0... |
Petya has n positive integers a1, a2, ..., an.
His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different di... | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
map<char, long long int> sum, first;
for (int i = 1; i <= n; i++) {
string second;
cin >> second;
long long int mf = 1;
for (int j = second.size() - 1; j >= 0; j--) {
if (j == 0) {
first[second[0]] = 1;
... |
You have a team of N people. For a particular task, you can pick any non-empty subset of people. The cost of having x people for the task is xk.
Output the sum of costs over all non-empty subsets of people.
Input
Only line of input contains two integers N (1 ≤ N ≤ 109) representing total number of people and k (1 ≤... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 5005;
const int MOD = 1000000007;
long long n, k, sol;
int dp[MAXN][MAXN], p[MAXN], l[MAXN];
vector<int> v[MAXN];
long long add(long long a, long long b) {
a += b;
if (a >= MOD) return a - MOD;
return a;
}
long long sub(long long a, long long b) {
a... |
Ehab has an array a of n integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of th... | #include <bits/stdc++.h>
using namespace std;
struct data {
long long l, x, id, ans;
data(long long _l, long long _x, long long _id) : l(_l), x(_x), id(_id){};
};
long long n, q;
long long a[100005];
vector<data> query;
set<long long> st;
long long ans = 1;
bool cmp(data &x, data &y) { return x.l < y.l; }
bool cmpI... |
You are working as an analyst in a company working on a new system for big data storage. This system will store n different objects. Each object should have a unique ID.
To create the system, you choose the parameters of the system — integers m ≥ 1 and b_{1}, b_{2}, …, b_{m}. With these parameters an ID of some object... | #include <bits/stdc++.h>
using namespace std;
struct cpx {
double r, i;
cpx(double real = 0.0, double image = 0.0) {
r = real;
i = image;
}
cpx operator+(cpx a) { return cpx(r + a.r, i + a.i); }
cpx operator-(cpx a) { return cpx(r - a.r, i - a.i); }
cpx operator*(cpx a) { return cpx(r * a.r - i * a.... |
Akash has lots of assignments to submit in his college. In one of the assignment he is given a string S of length N consisting of lowercase letters (a - z) only. Akash has to answer Q queries and for every query, he is given L, R and K. For each query he has to find the lexicographically Kth smallest character in subs... | A = ord("a")
n, q = map(int, raw_input().split())
s = raw_input().strip()
h = [26 * [0] for _ in range(n+1)]
for i in xrange(n):
d = ord(s[i]) - A
for j in range(26):
h[i+1][j] = h[i][j]
h[i+1][d] = h[i][d] + 1
for _ in xrange(q):
l, r, k = map(int, raw_input().split())
if k > r - l + 1... |
Brio got his house constructed near the National Highway. The Construction and Planning Committee has planned to construct a road near his house. Brio is worried about the Committee's plan as he fears that his house might come on the way of the road being constructed.
In such a case, he needs to request the Committee m... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
from math import sqrt
t=input()
while t>0:
t-=1
x1, y1 ,x2 ,y2 =map(int,raw_input().split())
r=input()
x=(x2-x1)
y=(y2-y1)
if x==0 and y==0:
print "REPLANN... |
Darshak (Dark) completed with his studies and became a engineer, now to earn his bread he decided to start a company, being a son of rich men he need not to think about investors.
He came up with a idea of bringing up a company so as to start with his first investment was to put up computers in his entire building ... | t = int(raw_input())
for i in range(t):
x = long(raw_input())
print (x*(x-1))/2 |
There are two kind of bots in the game BOT A and BOT B. Both are designed so as to move only in one direction in a 1-D array. Bot A can move towards left whereas bot B is constrained to move rightwards. Both are constrained to move only to the empty elements and one cannot jump over another bot. Now, a particular state... | import sys
testCase = int(raw_input())
def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
while (testCase>0):
try:
line = raw_input()
except KeyboardInterrupt:
break
if not line:
break
else:
temp = line.split(" ")
orig1 = te... |
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
Karan likes stickers. All his stickers are rect... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n = int(raw_input())
a = map(int,raw_input().split())
cnt=0
for i in range(n):
if a[i] < 300000000:
cnt+=1
print cnt |
Adriana was playing with the English alphabet. When she was done playing with the alphabet, she realised that she had jumbled up the positions of the letters. Now, given a set of words, she wondered what would be the dictionary ordering of these words based on the new alphabet ordering which she made.
In other words,... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def convertAlphabet(s, fromAlphabet, toAlphabet):
newWord = []
fromAlphaList = dict(zip(list(fromAlphabet), [i for i in range(26)]))
toAlphaList = dict(zip([i for i in range(26)], li... |
Mike lost in a coding contest just because he was not aware with the concept of palindrome properly.
So finally he learnt about it and decided to mess up with the Winners name of the contest as he will now meddle with letters of their names.
He will change all the names into palindrome and will follow these rules:
-We... | for i in range(input()):
a=raw_input()
c=0
for j in range(0,len(a)/2):
c+=abs(ord(a[j])-ord(a[len(a)-1-j]))
print(c) |
All Indian Robotic Challenge (AIRC) is going to be held in NIT Raipur.Ajeet a student of nitrr want to participate in it and win it. In airc person whose robots will reach faster to end point will win .speed of bot is 20meters/Min.Ajeet want to Know the time Required by Bot to complete the following distance .
Note:-T... | t=input()
while t:
n=input()
r=(n*60)/20
r=int(r)
print r
t-=1 |
Every one is now a days playing games on their smartphones for passing free time. Because of which there are number of game developing companies growing in the market. Not only that, each company is now flooding the market with a lot of games. With such a huge number of games in the market, for each company, with milli... | import bisect
N,M,Q = map(int,raw_input().split())
levels = []
for _ in xrange(N):
levels.append(map(int,raw_input().split()))
for _ in xrange(Q):
q=map(int,raw_input().split())
m=M
for i in xrange(N):
m = min(m,bisect.bisect_right(levels[i],q[i]))
print m |
Turing loves playing board games. Recently he played a game on the internet, that he found interesting.
You are given a square board of length N. Each unit box in the board is to be filled with a gold coin. All the players have infinite gold coins in a bank but they will be allowed to withdraw only a maximum of N coin... | rr=raw_input
for testcase in xrange(int(rr())):
N,K = map(int,rr().split())
X = N*N-K
print int(X%(N+1)!=0) |
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination wil... | x,k,d=map(int,input().split())
x=abs(x)
m=min(k,x//d)
x-=d*m
k-=m
k%=2
x-=d*k
print(abs(x)) |
Consider sequences \\{A_1,...,A_N\\} of length N consisting of integers between 1 and K (inclusive).
There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them.
Since this sum can be enormous, print the value modulo (10^9+7).
Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1... | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
int n, k;
ll modpow(ll a, ll b) {
ll r = 1;
while (b) {
if (b & 1) r = r * a % mod;
a = a * a % mod;
b >>= 1;
}
return r;
}
ll dp[200005];
int main() {
c... |
AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.
The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.
How many different PIN codes can he set this way?
... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper p... |
N of us are going on a trip, by train or taxi.
The train will cost each of us A yen (the currency of Japan).
The taxi will cost us a total of B yen.
How much is our minimum total travel expense?
Constraints
* All values in input are integers.
* 1 \leq N \leq 20
* 1 \leq A \leq 50
* 1 \leq B \leq 50
Input
Input i... | n,a,b = map(int,input().split())
print(min(b,a*n)) |
Red bold fonts show the difference from C1.
There is an infinitely large triangular grid, as shown below. Each point with integer coordinates contains a lamp.
<image>
Initially, only the lamp at (X, Y) was on, and all other lamps were off. Then, Snuke performed the following operation zero or more times:
* Choose t... | #include<bits/stdc++.h>
using namespace std;
int n,m,p,k,q,dp[64][2][3];
long long x[10010],y[10010];//dep,lim,mod
bool light(long long xx,long long yy){
bool flag=0;
for(int i=1;i<=n;i++){
if(yy-y[i]<0||yy-y[i]>x[i]-xx) continue;
flag^=(((x[i]-xx)|(yy-y[i]))==x[i]-xx);
}
return flag;
}
bool lres[3],rres[3],mre... |
Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.
Constraints
* 2\leq K\leq 100
* K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the number of ways to... | K = int(input())
print((K//2)*(-(-K//2))) |
Takahashi and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
* Choose a pile. If the i-th pile is selected and th... | #include<iostream>
#include<algorithm>
using namespace std;
const int sq = 30000;
int ans = 0, n;
int sg(int x, int k) {
if (x % k == 0)return x / k;
if (x / k > sq)return sg(x - x / k - 1, k);
else {
int m1 = x % k;
return sg(x - max(x / k + 1, m1 - m1 % (x / k + 1)), k);
}
}
int main() {
cin >> n;
for (i... |
N cells are arranged in a row. Some of them may contain tokens. You are given a string s that consists of `0`s and `1`s. If the i-th character of s is `1`, the i-th cell (from left) contains a token. Otherwise, it doesn't contain a token.
Snuke wants to perform the following operation as many times as possible. In eac... | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
ll A[500005];
ll dp[500005];
void I_m_Beast()
{
int n;
cin>>n;
assert(1<=n && n<=500000);
string s;
cin>>s;
for(int i=1;i<=n;i++) {
// cin>>A[i];
A[i]=s[i-1]-'0';... |
You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between. Print the acronym formed from the uppercased initial letters of the words.
Constraints
* s_1, s_2 and s_3 are composed of lowercase English letters.
* 1 ≤ |s_i| ≤ 10 (1≤i≤3)
Input
Input is given from Stan... | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a=sc.next();
String b=sc.next();
String c=sc.next();
String ans="";
ans+=a.charAt(0);
ans+=b.charAt(0);
ans+=c.charAt(0);
System.... |
There are N panels arranged in a row in Takahashi's house, numbered 1 through N. The i-th panel has a number A_i written on it. Takahashi is playing by throwing balls at these panels.
Takahashi threw a ball K times. Let the panel hit by a boll in the i-th throw be panel p_i. He set the score for the i-th throw as i \t... | #include <bits/stdc++.h>
#define LLI long long int
#define FOR(v, a, b) for(LLI v = (a); v < (b); ++v)
#define FORE(v, a, b) for(LLI v = (a); v <= (b); ++v)
#define REP(v, n) FOR(v, 0, n)
#define REPE(v, n) FORE(v, 0, n)
#define REV(v, a, b) for(LLI v = (a); v >= (b); --v)
#define ALL(x) (x).begin(), (x).end()
#define ... |
Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b.
Constraints
* 0 < a, b ≤ 2,000,000,000
* LCM(a, b) ≤ 2,000,000,000
* The number of data sets ≤ 50
Input
Input consists of several data sets. Each data set contains a and b separated by a single spa... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Main me = new Main();
while(in.hasNext()){
long a = in.nextInt(),b = in.nextInt();
long gcd = me.GCD(a,b);
System.out.printf("%d %d\n",gcd,a*b/gcd);
}
}
private long GCD(... |
Create a program of the square picking method, which is one of the classical random number generation methods. The square harvesting method was proposed by von Neumann in the mid-1940s.
In the square picking method, when the number of digits of the generated random number is n, the square of the initial value s is cal... | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int t = 0; t < n; t++) {
int s;
cin >> s;
cout << "Case " << t + 1 << ":" << endl;
for(int i = 0; i < 10; i++) {
s = s * s;
s = (s / 100) % 10000;
cout << s << endl;
}
}
} |
We have decided to introduce an automatic ticket gate to the railway network of a certain country. One of the difficult issues to implement is determining whether a given ticket can move between designated stations. Each ticket has a boarding station and a getting-off station. With this ticket, you can not only "get on... | //Name: Railroad
//Level: 4
//Category: グラフ,Graph,最短経路,DAG
//Note:
/**
* AからBまでの最短経路をDijkstra法で求め、そのときに使った辺のみから
* なるDAGを構成する。
* すると、cからdに最短経路で行けるかの判定は、このDAG上でcからdに行けるかの
* 判定と等価になる。
* 1クエリについて最悪全ノードの探索が必要で、これはO(S+R)になるが、
* 到達可能かどうかは1bitしか使わないのでbit parallelで高速化ができる。
* (S+R) × Q = 10^10 程度なので、数十倍程度の高速化をすれば制限時間に間に合... |
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided ... | #include <iostream>
#include <cstring>
using namespace std;
int w, h;
int map[91][91];
bool visited[91][91];
int dx[] = { 0, 1, 0, -1};
int dy[] = {-1, 0, 1, 0};
int dfs(int x, int y, int n) {
int result = n;
// 到達した時の処理: count を増やす
for (int i = 0; i < 4; i++) {
int nextX = dx[i] + x;
int nextY = dy[i] + y;
... |
Animation is one of methods for making movies and in Japan, it is popular to broadcast as a television program or perform as a movie. Many people, especially the young, love one. And here is an anime lover called Jack. We say he is an mysterious guy with uncertain age. He likes anime which are broadcasted in midnight a... | #include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
int N;
while(cin>>N&&N){
map<string,int> anime;
vector<int> time;
for(int i=0; i<N; ++i){
int weekday,start;
string name;
cin >> name >> weekday >> start;
int tmp=60*(start/1... |
A rich man has a square room with mirrors for security or just for fun. Each side of the room is eight meters wide. The floor, the ceiling and the walls are not special; however, the room can be equipped with a lot of mirrors on the walls or as vertical partitions.
Every mirror is one meter wide, as tall as the wall, ... | #include<cstdio>
using namespace std;
const int dx[]={1,-1,-1,1},dy[]={-1,-1,1,1};
int main(){
for(int n;scanf("%d ",&n),~n;){
bool mirror[17][17]={};
for(int k=0;k<n;k++){
char d;
int i,j;
scanf("%c%d%d ",&d,&j,&i);
if(d=='x') mirror[2*i][2*j+1]=true;
else mirror[2*i+1][2*j]=true;
}
int x=... |
Example
Input
6 3
1 0 0 1 0 1
1 3 2
Output
1 | import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int[] seq = new int[N];
int[] run = new int[M];
for (int i = 0; i < seq.length; i++) {
... |
Problem
N strings {S1, S2, ..., SN} are given. Then Q queries are given. There are two types of queries:
1. When a, b, c, d are input, the substring from the bth character of Sa is connected after the substring up to the d-1 character of Sc. Let this be the new Sc. Concatenate the substring from the dth character of ... | #include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climit... |
Roads in a city play important roles in development of the city. Once a road is built, people start their living around the road. A broader road has a bigger capacity, that is, people can live on a wider area around the road.
Interstellar Conglomerate of Plantation and Colonization (ICPC) is now planning to develop ro... | #include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<d... |
UTF-8 is one of the methods for coding multibyte characters.
Characters are treated as bytes on the computer. If it is only English, it can be expressed in 1 byte even if the Latin alphabet, numbers and symbols are combined, but unfortunately it is not possible to express the characters used all over the world in 1 by... | // UTPC2010 F. UTF-8
#include <iostream>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main(){
int n;
string cmp[4] = {"0xxxxxxx", "110yyyyx10xxxxxx", "1110yyyy10yxxxxx10xxxxxx", "11110yyy10yyxxxx10xxxxxx10xxxxxx"};
long long dp[1001];
while(cin >> n, n){
vector<string> vs(n)... |
Example
Input
3 3 1
0 0
Output
4 | #include<cstdio>
#include<map>
#include<vector>
#include<cassert>
#include<algorithm>
using namespace std;
const long long mod=1000000007;
map<int,vector<int> > sameX,sameY;
vector<int> xs,ys;
long long mult(long long x,long long y){
return ((x%mod)*(y%mod))%mod;
}
long long ad(long long x,long long y){
return ... |
E-Sugoroku
Bob, a fox with no friends, decided to spend his time playing sugoroku alone today. A 6-sided die with integers a_1, a_2, a_3, a_4, a_5, a_6 written on each side, a piece, and M squares on a straight line, and numbers from 1 to M are assigned in order from the left. I decided to use a board. Instructions ar... | #include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
int M;
int a[7];
int s, g;
int N[301];
bool isChecked[301];
vector<int> milestone[301]; //そのマスで出せばゴールにたどり着ける目を格納する
int iabs(int x){ return x >= 0 ? x : -x; }
bool search(int now){
if (isChecked[now]... |
Stamp Rally
Stamp Rally
The Japan Amusement Group (JAG) is planning an event at a theme park that imitates an island country. In this event, each time a participant crosses a bridge, the stamps decided for each bridge are stamped in order on the stamp book. The prepared stamp is one of the following seven types.
a ... | #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define NUM 205
#define SIZE 12
enum Type{
Open_Curve,
Close_Curve,
Open_Rect,
Close_Rect,
Expr... |
E: Taiyaki-Master and Eater
story
Tsuta is very good at making Taiyaki. Ebi-chan loves Taiyaki made by Tsuta-san. The two are happy to make and eat Taiyaki every week, but Tsuta-san's recent worries are that Ebi-chan, who is in the middle of eating, eats the food while making Taiyaki.
Mr. Tsuta, who decided to make ... | #include <bits/stdc++.h>
using namespace std;
struct BIT {
vector<vector<int>> data;
int h, w;
BIT(int h, int w):data(h+1, vector<int>(w+1)), h(h), w(w){}
void add(int y, int x, int a) {
for(int i = y; i <= h; i += i & -i) {
for(int j = x; j <= w; j += j & -j) {
data[i][j] += a;
}
}
}
... |
D: XORANDORBAN
Problem Statement
You are given a positive integer N. Your task is to determine a set S of 2^N integers satisfying the following conditions:
* All the integers in S are at least 0 and less than 2^{N+1}.
* All the integers in S are distinct.
* You are also given three integers X, A, and O, where 0 \le... | #include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}
template <typena... |
Problem statement
Of the string set $ S $ that meets the following conditions, configure $ 1 $ with the largest number of elements.
* The length of the string contained in $ S $ is $ 1 $ or more and $ N $ or less.
* The lengths of the strings contained in $ S $ are different.
* The string contained in $ S $ consists ... | n=input()
if n==1:
print "1\n0"
elif n==2:
print "2\n0\n11"
else:
print n-1
for i in xrange(n-1):
print "1"+("0"*i)+"1"
|
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ t... | // includes
#include <bits/stdc++.h>
using namespace std;
// macros
#define pb emplace_back
#define mk make_pair
#define FOR(i, a, b) for(int i=(a);i<(b);++i)
#define rep(i, n) FOR(i, 0, n)
#define rrep(i, n) for(int i=((int)(n)-1);i>=0;i--)
#define irep(itr, st) for(auto itr = (st).begin(); itr != (st).end(); ++itr)
... |
There are n children who have landed up in an unknown place where they find just some jar of cookies to eat. They also have a dog with them. The children gather all the cookies and put them in a big jar. Exhausted, they agree to go and wait until the next morning to divide up the cookies.
At one o'clock in the morning,... | t=int(input())
while t>0:
t=t-1
n=0
m=0
n=int(input())
if n == 2:
print (15)
else:
m=n+1
ans=pow(n,m)-n+1
print (ans) |
With her new hair-style, Penny has to listen to all the comments of Sheldon Cooper. She (God knows why) challenged Sheldon Cooper for a match of Chess. Penny wants to defeat Dr. Sheldon Cooper in the game of chess. Although, she tried very hard, she is in a situation and wants your help. It is your duty to help Penny. ... | #!/usr/local/bin/python2.7
print "NOT YET!"; |
Prats is learning to count.But this is not a usual counting.He has been given the task to count number of trailing 0s in a binary representation of a number.
Input
First line of input contains T, number of test cases. Each of the next T lines contains a number N.
Output
Output the number of trailing 0s in binary ... | exec(input()*"print bin(input())[::-1].find('1');") |
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will be prime.[1][2] For example 1193 is a circular prime, since 1931, 9311 and 3119 all are also prime
Input
First line contains an integer N, number of inputs. Seco... | def len(n):
l=0
while n:
n/=10
l+=1
return l
def isprime(n):
if n==2:
return 1
var=None
for i in xrange(2,n):
if n%i==0:
break
var=i
if var==n-1:
return 1
else:
return 0
def num_rot(n,f):
l=len(n)-1
while f:
... |
Princess Rupsa saw one of her friends playing a special game. The game goes as follows:
N+1 numbers occur sequentially (one at a time) from A0 to AN.
You must write the numbers on a sheet of paper, such that A0 is written first. The other numbers are written according to an inductive rule — after Ai-1 numbers have bee... | for t in xrange(int(raw_input())):
n = int(raw_input())
a = map(int, raw_input().split())
ans,k,c = a[0]*a[1],1,0
mod = (10**9) + 7
n = n+1
for i in range(2,n):
ans = (ans * 2)%mod
ans = (ans + (a[0]*a[i])%mod)%mod
c = (c + (k*a[i-1])%mod)%mod
ans = (ans + (a[i]*c)%mod)%mod
k = (k*2)%mod
print (ans*2)%... |
You are given an array that consists of n integer numbers. You have to change at most K elements of this array, so that the resulting array will be a arithmetic progression. From all the possible arithmetic progressions, you should choose most beautiful.
You can uniquely define the arithmetic progression by two number... | array_len, allowed_changes = map(int, raw_input().split())
array = map(int, raw_input().split())
MAX = 10 ** 9 + 1
best_a = MAX
best_d = MAX
for start in xrange(allowed_changes + 1):
rem = allowed_changes - start
for end in xrange(max(start + 1, array_len - rem - 1), array_len):
d = (array[end] - arra... |
Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree.... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
const int mod = 1000000007;
int n, m;
vector<int> g[N];
int v[N];
int main() {
cin >> n >> m;
memset(v, 0, sizeof(v));
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
}
for (int i = 1; i < n + 1;... |
Berland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.
Petya knows that he needs all three types of vitamins to... | n = int(input())
a = [1000000,1000000,1000000,1000000,1000000,1000000,1000000]
for i in range(n):
s = input()
k = s.split(" ")
q = int(k[0])
p = k[1]
p = sorted(p)
p = "".join(p)
if(p=='A' or p=='B' or p=='C'):
a[int(ord(p[0])-ord('A'))] = min(a[int(ord(p[0])-ord('A'))],q)... |
There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times.
Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He... |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.function.ToIntFunction;
public class GFG
{
static int mod1 = (int) (1e9 + 7);
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream di... |
Petya collects beautiful matrix.
A matrix of size n × n is beautiful if:
* All elements of the matrix are integers between 1 and n;
* For every row of the matrix, all elements of this row are different;
* For every pair of vertically adjacent elements, these elements are different.
Today Petya bought a b... | #include <bits/stdc++.h>
using namespace std;
struct BIT {
int bit[2005];
void init() { memset(bit, 0, sizeof(bit)); }
void add(int k, int x) {
k++;
while (k < 2005) {
bit[k] += x;
k += k & -k;
}
}
int get(int k) {
k++;
int ret = 0;
while (k > 0) {
ret += bit[k];
... |
Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself.
Let's describe this problem in a mathematical way. Consider a timeline from time 1 to n. The i-th red envelope will be available from time s_i ... |
import java.io.*;
import java.util.*;
public class A{
static long [][]memo;
static int []max,to;
static int n;
static long dp(int idx,int rem) {
if(idx==n)
return 0;
if(memo[rem][idx]!=-1)
return memo[rem][idx];
long ans=dp(to[idx],rem)+max[idx];
if(rem>0)
ans=Math.min(ans, dp(idx+1,rem-1));
... |
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degre... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class G {
public static void main(String[] args... |
Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
* on Mondays, Thursdays and Sundays he eats fish food;
* on Tuesdays and Saturdays he eats rabbit stew;
* on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already pa... | import copy
nums = [0, 1, 2, 0, 2, 1, 0]
asdf = [3, 2, 2]
things = list(map(int, input().split(' ')))
max_idx = 0
for i in range(7):
stuff = copy.deepcopy(things)
idx = i
while stuff[0] >= 0 and stuff[1] >= 0 and stuff[2] >= 0 and idx < 7:
stuff[nums[idx % 7]] -= 1
idx += 1
num_weeks = m... |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | for _ in range(input()) :
num = input()
count = 0
while num % 3 == 0 :
num = num / 3
count += 2
while num % 5 == 0 :
num = num / 5
count += 3
while num % 2 == 0 :
num = num / 2
count += 1
if num == 1 :
print count
else :
... |
Let's call a fraction x/y good if there exists at least one another fraction (x')/(y') such that x/y = (x')/(y'), 1 ≤ x', y' ≤ 9, the digit denoting x' is contained in the decimal representation of x, and the digit denoting y' is contained in the decimal representation of y. For example, 26/13 is a good fraction, becau... | #include <bits/stdc++.h>
using namespace std;
const int N = 111, mod = 998244353;
char s[N];
int dig[N], n;
int gcd(int x, int y) { return x ? gcd(y % x, x) : y; }
map<pair<int, int>, int> dp[2][2][10][10];
void add(int& var, int val) {
var += val;
if (var >= mod) var -= mod;
}
int to1[10], to2[10];
long long solve... |
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | #include <bits/stdc++.h>
using namespace std;
int n, k, a[200005];
set<int> ada;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
id;
vector<int> ans;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin... |
You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n.
In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≤ l ≤ r ≤ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r.
For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ... | T=int(input())
s=[]
for t in range(T):
dif=0;h=0
n=int(input())
a=[int(k) for k in input().split()]
b =[int(k) for k in input().split()]
for i in range (n):
if(a[i]==b[i]):
continue
else:
dif=b[i]-a[i]
h=i
break
if(dif<0):
a... |
Consider a string s of n lowercase English letters. Let t_i be the string obtained by replacing the i-th character of s with an asterisk character *. For example, when s = abc, we have t_1 = \tt{*bc}, t_2 = \tt{a*c}, and t_3 = \tt{ab*}.
Given a string s, count the number of distinct strings of lowercase English letter... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100;
int n, m;
char ch[N];
struct SA {
int sa[N], rk[N], h[N], x[N], y[N], c[N];
void build_SA() {
m = 128;
for (int i = 0; i <= m; ++i) c[i] = 0;
for (int i = 1; i <= n; ++i) c[x[i] = ch[i]]++;
for (int i = 1; i <= m; ++i) c[i] += c[... |
There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.
You have a map of that network, so for each railway section you know which stations it connects.
Each of the n-1 sections has some integer... | #include <bits/stdc++.h>
using namespace std;
vector<int> c(5001, 0);
const int MAX_V = 5001;
vector<vector<int> > G = vector<vector<int> >(MAX_V, vector<int>(0, 0));
int root;
int parent[30][MAX_V];
vector<int> depth(MAX_V);
void dfs(int v, int p, int d) {
parent[0][v] = p, depth[v] = d;
for (int i = 0; i < G[v].s... |
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n.
Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som... | n = int(input())
a = input().split()
a = [int(x) for x in a]
a = [a[i]-i for i in range(n)]
d = {}
for i in range(n):
if (a[i] not in d):
d[a[i]] = 0
d[a[i]] += a[i]+i
m = 0
for k in d:
m = max(m,d[k])
print(m) |
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const long long MOD = 998244353;
const long long N = 1e5 + 9;
const long long M = 1e6 + 9;
long long n, l, m, cnt, root;
vector<long long> G[N];
bool ll[N];
void dfs(long long u, long long f, long long dep) {
bool ok = 0;
for (a... |
Consider all binary strings of length m (1 ≤ m ≤ 60). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly 2^m such strings in total.
The string s is lexicographically smaller than the string t (both have the sam... | #include <bits/stdc++.h>
using namespace std;
long long a[105];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
long long tmp = 0;
for (int j = 0; j < m; ++j) {
... |
This is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
public class Round658A2 {
public static void solve() {
int t = s.nextInt();
while(t-- > 0) {
int n = s.nextInt();
cha... |
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements i... | def checkKey(dict, key):
if key in dict:
return True
return False
# def helper(s):
# l=len(s)
# if (l==1):
# l=[]
# l.append(s)
# return l
# ch=s[0]
# recresult=helper(s[1:])
# myresult=[]
# myresult.append(ch)
# for st in recresult:
# myresult.append(st)
# ts=ch+st
# myresult.append(ts)
# ret... |
The Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:
Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
long long x;
void answer() {
cin >> x;
cout << ((x / 4 + 1) % mod * ((x / 2 - x / 4 + 1) % mod) % mod) << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
for (int i = 0; i < t; i++) answer();
return 0;
}... |
The new academic year has started, and Berland's university has n first-year students. They are divided into k academic groups, however, some of the groups might be empty. Among the students, there are m pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.
A... | #include <bits/stdc++.h>
using std::cerr;
using std::cin;
using std::max;
using std::min;
int n, m, K, a, b, ecnt, last[500005], A[500005], Bn, f[500005 << 1],
size[500005 << 1], mark[500005], sta[500005 << 1], top, tot;
long long ans;
struct node {
int x, y;
} B[500005];
struct road {
int to, nex;
} e[500005];... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has sequence a consisting of n integers.
The subsequence of the sequence a is such subseque... | #include <bits/stdc++.h>
using namespace std;
void init();
int C(int n, int k);
const int N = (int)1e5 + 7, M = (int)1e9 + 7;
int n, k, cnt = 0;
map<int, int> m1;
vector<int> m2;
vector<long long> dp[N];
bool isl(int A) {
for (; A; A /= 10)
if (A % 10 != 4 && A % 10 != 7) return false;
return true;
}
int main()... |
Kawashiro Nitori is a girl who loves competitive programming.
One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.
Given a string s and a parameter k, you need to check if there exist k+1 non-empty strings a_1,a_2...,a_{k+1}, such that $$$s=a_1+a_2+… +a_k+a_{k+1}... | from os import path
import sys,time
# mod = int(1e9 + 7)
# import re
from math import ceil, floor,gcd,log,log2 ,factorial,sqrt
from collections import defaultdict ,Counter , OrderedDict , deque
from itertools import combinations ,accumulate
# from string import ascii_lowercase ,ascii_uppercase
from bisect import *
from... |
You are given two integer arrays a and b of length n.
You can reverse at most one subarray (continuous subsegment) of the array a.
Your task is to reverse such a subarray that the sum ∑_{i=1}^n a_i ⋅ b_i is maximized.
Input
The first line contains one integer n (1 ≤ n ≤ 5000).
The second line contains n integers ... | #include<iostream>
#include<stdio.h>
#include<cmath>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<queue>
#include<vector>
#include<map>
#define oo 0x3f3f3f3f
#define OO 0x3f3f3f3f3f3f3f3f
#define LL long long
#define res register int
#define STP system("pause")
using namespace std;
const int N=5e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.