input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
You are given a permutation p_1, p_2, …, p_n of integers from 1 to n and an integer k, such that 1 ≤ k ≤ n. A permutation means that every number from 1 to n is contained in p exactly once.
Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_... | import sys
input = sys.stdin.readline
if __name__ == "__main__":
n, k = map(int, input().split())
p = list(map(int, input().split()))
max_val = sum(range(n, n - k, -1))
num_perm = 1
last_idx = -1
for i in range(n):
if p[i] > n - k:
if last_idx != -1:
num_pe... |
A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h-1 onto a base. A base consists of h pyramids of height 1, and h-1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
... | import os
import bisect
def get_sizes():
s = [0]
i = 1
while s[-1] <= int(1e9):
s.append(s[-1] + (i - 1) * 3 + 2)
i += 1
return s
SIZES = get_sizes()[1:]
def g(n, p = 0):
if n < 2:
return p
b = SIZES[bisect.bisect_right(SIZES, n) - 1]
return g(n - b, p + 1)
... |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | t=int(input())
for i in range (t):
a=input()
print(a[0::2]+a[-1])
|
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | # import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
t = 1
t = int(input())
while t:
t -= 1
n = int(input())
# s = input()
if n > 30:
if (n-30) in [6, 10, 14]:
if n > 31:
print('YES')
print(6,10,15,n-31)
... |
You are given a sequence a_1, a_2, …, a_n of non-negative integers.
You need to find the largest number m of triples (i_1, j_1, k_1), (i_2, j_2, k_2), ..., (i_m, j_m, k_m) such that:
* 1 ≤ i_p < j_p < k_p ≤ n for each p in 1, 2, …, m;
* a_{i_p} = a_{k_p} = 0, a_{j_p} ≠ 0;
* all a_{j_1}, a_{j_2}, …, a_{j_m} are ... | #include <bits/stdc++.h>
using namespace std;
int n, w[501000], LL[501000], RR[501000];
int OK[501000], ML[501000], MR[501000];
int TR[501000], TL[501000], SL[501000], SR[501000];
vector<int> G[501000], T, OO[501000];
struct AA {
int b, e;
} U[501000];
bool Pos(int K) {
int i, m = T.size();
for (i = 0; i < K; i++... |
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot h... | from math import *
m,n=map(int,raw_input().split())
if m>n:
t=n;n=m;m=t
if m==1:
print n
elif m==2:
print (n/4)*4+min((n%4),2)*2
else:
print int(ceil(n/2.0)*ceil(m/2.0)+(n/2)*(m/2))
|
You are given a multiset of powers of two. More precisely, for each i from 0 to n exclusive you have cnt_i elements equal to 2^i.
In one operation, you can choose any one element 2^l > 1 and divide it into two elements 2^{l - 1}.
You should perform q queries. Each query has one of two types:
* "1 pos val" — assig... | #include<iostream>
#include<cstdio>
#include<set>
#include<map>
#include<vector>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<iomanip>
#include<stack>
#include<cmath>
using namespace std;
#ifndef POJ
#define Cpp11
#endif
#ifdef Cpp11
#define _for(i,a... |
There are n + 1 cities, numbered from 0 to n. n roads connect these cities, the i-th road connects cities i - 1 and i (i ∈ [1, n]).
Each road has a direction. The directions are given by a string of n characters such that each character is either L or R. If the i-th character is L, it means that the i-th road initiall... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.IntStream;
public class A {
public static void main(String[] args) {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.ou... |
A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.
You are given a binary string s of length n. Construct two balanced bracket sequences ... | #include<bits/stdc++.h>
#define pb push_back
#define x first
#define y second
#define pdd pair<double,double>
#define pii pair<int,int>
#define pll pair<LL,LL>
#define mp make_pair
#define LL long long
#define ULL unsigned long long
#define sqr(x) ((x)*(x))
#define pi acosl(-1)
#define MEM(x) memset(x,0,sizeof(x))
#def... |
Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array.
More formally, given a suffix array of length n and having an alphabet size k, count the number of strings that produce such a suffix array.
Let s be a string of length n. Then the i-th suffix of s is the subst... | #include<bits/stdc++.h>
using namespace std;
//#include <atcoder/lazysegtree>
//using namespace atcoder;
//using mint = modint998244353;
//using mint = modint1000000007;
#pragma region template
using ll = long long;
using PII = pair<int, int>;
using PLL = pair<ll, ll>;
template <class T> using V = vector<T>;
template <... |
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n, cnt = 0, i;
cin >> n;
string ans[200000], s;
while (n--) {
cin >> s;
if (s == "pwd") {
cout << "/";
for (i = 0; i < cnt; i++) {
cout << ans[i] << "/";
}
... |
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of h cells numb... | import java.io.*;
import java.util.*;
public class C implements Runnable {
private MyScanner in;
private PrintWriter out;
List<int[]> trees;
List<Integer> treeSize;
boolean[] used;
int[] posInTree, treeNum;
Map<Integer, Integer> addedId, hashById;
long answer;
int mod(int a, int ... |
The capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into n rows, each row consists of m seats.
There are k people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office started sel... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
int n, m, aib[4002][4002], q;
bool pus[2002][2002];
void add(int L, int C) {
for (int i = L; i <= n + m - 1; i += (i & (-i)))
for (int j = C; j <= n + m - 1; j += (j & (-j))) aib[i][j]++;
}
int query(int L, int C) {
int ans = 0;
for (int... |
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:
1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that ... | #include <bits/stdc++.h>
using namespace std;
int n, K, size;
int v[2010];
long long C[2010];
long long sol[2010];
long long ModN(long long x) {
long long a = x % 1000000007;
if (a < 0) return (a + 1000000007);
return a;
}
void Euclid_extins(long long a, long long b, long long &x, long long &y) {
if (b == 0) {
... |
Piglet has got a birthday today. His friend Winnie the Pooh wants to make the best present for him — a honey pot. Of course Winnie realizes that he won't manage to get the full pot to Piglet. In fact, he is likely to eat all the honey from the pot. And as soon as Winnie planned a snack on is way, the pot should initial... | #include <bits/stdc++.h>
using namespace std;
int n, m, x, y, w, lo, hi, a[100005], C[15][15];
double p[100005][110], buf[110], A, B, t, pr, ret;
int main() {
for (int i = (0); i < (10); i++) {
C[i][0] = C[i][i] = 1;
for (int j = (1); j < (i); j++) C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
scanf("%d", &n... |
Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures.
A piece of squared paper of size n × m is represented by a table, consisting of n rows and m columns. All squares are white on blank squared paper. Dima defines a picture as ... | #include <bits/stdc++.h>
using namespace std;
int n, m;
long long ret, cnt, dp[155][155][155][2][2], S[2][2][155][155];
long long MOD = 1000000007;
inline void Mod(long long &a) {
while (a >= MOD) a -= MOD;
}
inline long long Sum(int a, int b, int l1, int h1, int l2, int h2) {
if (l2 > h2 || l1 > h1) return 0;
lo... |
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a... | #include <bits/stdc++.h>
using namespace std;
int main() {
char a[10000], b[10000];
int a1 = 0, b1 = 0;
cin >> a >> b;
for (int i = 0; i < strlen(a); i++)
if (a[i] == '1') a1++;
for (int i = 0; i < strlen(b); i++)
if (b[i] == '1') b1++;
a1 += a1 % 2;
if (a1 >= b1)
cout << "YES";
else
cou... |
Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parall... | #include <bits/stdc++.h>
using namespace std;
struct Node {
int x1, y1, x2, y2;
};
struct Node line[110], node[210];
int n, m, w, h;
int isgo[110];
int ans[110];
int judge(int u, int v) {
if (line[u].x1 == line[u].x2) {
int a = line[u].y1;
int b = line[u].y2;
if (a == node[v].y1 && b == node[v].y2 && li... |
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u... | import java.util.Scanner;
public class D {
public static void main(String[] args) {
D solver = new D();
solver.solve();
}
private void solve() {
Scanner sc = new Scanner(System.in);
// sc = new Scanner("-++-\n");
// sc = new Scanner("+-\n");
// sc = new Scanne... |
Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs ai rubles. Only one person can hang clothes on one hook.
Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to... | racks, fine = map(int, input().split())
cost = list(map(int, input().split()))
cost.sort()
guests = int(input())
if guests > racks:
print (sum(cost) - ((guests - racks) * fine))
else:
print (sum(cost[:guests]))
|
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.
A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at vo... | import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long a[]=new long[n];
long b[]=new long[n];
int i;
for(i=0;i<n;i++){
a[i]=sc.nextLong();
}
for(i=0;i<n;i++){
b[i]=sc.nextLong();
}
long sum=0;
for(... |
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of n characters, so the decorators hung a lar... | import java.util.Scanner;
public class Input {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int l = in.nextInt();
int p = in.nextInt();
String s = in.next();
if (l%2 == 0)... |
Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?
Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty part... | import java.io.*;
import java.util.*;
public class Main2 {
public static void main (String[] args) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] spl = in.readLine().split(" ");
int n = Integer.parseInt(spl[0]);
int k = Integer.parseInt(spl[1]);
i... |
Roland loves growing flowers. He has recently grown a beautiful rose at point (0, 0) of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it.
To protect the rose, Roland wants to build n watch towers. Let's assume that a tower is a point on the plan... | #include <bits/stdc++.h>
const int K = 210, N = 9;
int x[K], y[K], z[K], ax[N], ay[N], tx[N], ty[N], n, r, i, j, k, r1, r2, t, s;
void go(int t, int p) {
if (p == n) {
int u = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
u += (tx[i] - tx[j]) * (tx[i] - tx[j]) +
(ty... |
In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's sociability is the maxim... | #include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');
cerr.writ... |
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password ... |
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Main {
static ArrayList<Integer> graph[];
static ArrayList<Integer> res=new ArrayList<Integer>();
public static void main(String[] args) throws IOException {
... |
The biggest gold mine in Berland consists of n caves, connected by n - 1 transitions. The entrance to the mine leads to the cave number 1, it is possible to go from it to any remaining cave of the mine by moving along the transitions.
The mine is being developed by the InMine Inc., k miners work for it. Each day the ... | #include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int n, w[N], m;
vector<int> v[N], vv[N];
struct SegmentTree {
struct TNode {
int l, r, v;
} t[N << 2];
int lazy[N << 2];
inline int lc(int pos) { return pos << 1; }
inline int rc(int pos) { return pos << 1 | 1; }
inline void pushup(int ... |
Tomorrow Ann takes the hardest exam of programming where she should get an excellent mark.
On the last theoretical class the teacher introduced the notion of a half-palindrome.
String t is a half-palindrome, if for all the odd positions i (<image>) the following condition is held: ti = t|t| - i + 1, where |t| is th... | #include <bits/stdc++.h>
using namespace std;
const int N = 5050;
struct node {
node *c[2];
int t;
node() {
c[0] = c[1] = NULL;
t = 0;
}
} * root;
int n, k;
bool vis[N][N], dp[N][N];
string s, x;
bool can(int l, int r) {
if (r <= l) return 1;
if (vis[l][r]) return dp[l][r];
vis[l][r] = 1;
if (s[... |
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula
<image>
Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6,... | import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.TreeMap;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
impor... |
Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.
He has suggestions to wo... | #include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-12;
struct PT {
long double x, y;
PT() {}
PT(long double x, long double y) : x(x), y(y) {}
bool operator<(const PT &rhs) const {
return make_pair(y, x) < make_pair(rhs.y, rhs.x);
}
bool operator==(const PT &rhs) const {
return ... |
For his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.
Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to ... | import java.util.*;
import java.io.*;
public class PreorderTest
{
public static int[][] adj;
public static boolean[] removed;
public static boolean[] visited;
public static int[] dp;
public static int best;
public static void main(String[] args) throws Exception
{
FastScanner in = new FastScanner(System.in);... |
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a sec... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, b, T, ans = 0;
cin >> n >> a >> b >> T;
vector<int> d(n, 1);
for (int& p : d) {
char c;
cin >> c;
if (c == 'w') p += b;
}
vector<int> rtime(n), ltime(n);
rtime[0] = d[0], ltime[0] = d[0];
for (int i = 1; i < n; i++) {
r... |
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya h... | n, h, k = map(int, input().split())
pots = map(int, input().split())
comb = [0]
for pot in pots:
if (comb[-1] % k + pot <= h):
comb[-1] += pot
else:
comb.append(pot)
sec = lambda x : x // k + int(x % k > 0)
ans = sum(map(sec, comb))
print(ans) |
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all ... | n, m, c = input().split()
n, m = int(n), int(m)
lst = []
for i in range(n):
lst.append(input())
N = set()
for i in range(n):
for j in range(m):
if lst[i][j] == c:
if j != 0 and lst[i][j-1] != c and lst[i][j-1] != ".":
N.add(lst[i][j-1])
if i != 0 and lst[i-1][j] != c and lst[i-1][j] != ".":
N.add(lst... |
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of ... | import java.io.*;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class D {
void solve() throws IOException {
FastScanner scanner = new FastScanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
int n = scanner.nextInt();
... |
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq... |
import java.awt.List;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Locale;
public... |
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have ... | #include <bits/stdc++.h>
using namespace std;
map<string, int> mp;
int rar[101000], e[101000], r[101000], xr[101000];
bool vis[101000];
vector<pair<int, int> > v[101000];
vector<pair<pair<int, int>, pair<int, int> > > ss;
int root(int x) {
while (rar[x] != x) {
rar[x] = rar[rar[x]];
x = rar[x];
}
return x... |
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Eac... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int n = r.nextInt();
int m = r.nextInt();
int k = r.nextInt();
if(n % 2 == 0){
System.out.println("Marsel");
}els... |
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.
Form... | #include <bits/stdc++.h>
using namespace std;
constexpr int64_t MOD = (int64_t)1e9 + 7LL;
struct quad {
int64_t x1, y1;
int64_t x2, y2;
bool contains(const quad& other) {
return (x1 <= other.x1 && other.x2 <= x2) ||
(y1 <= other.y1 && other.y2 <= y2);
}
bool intersects(const quad& other) {
... |
The flag of Berland is such rectangular field n × m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
... |
import java.util.Scanner;
/**
*
* 作者:张宇翔
* 创建日期:2017年8月3日 下午10:54:33
* 描述:永远的ACM
*/
public class Main {
private static final int Max=(int) (1e3+10);
private static int n,m;
private static String s[];
public static void main(String[] args) {
InitData();
GetAns();
}
private static void InitData() {
S... |
Masha is fond of cacti. When she was a little girl, she decided to plant a tree. Now Masha wants to make a nice cactus out of her tree.
Recall that tree is a connected undirected graph that has no cycles. Cactus is a connected undirected graph such that each vertex belongs to at most one cycle.
Masha has some additio... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
const ll MOD = 998244353;
const ll root = 3;
ll binpow(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1) res = (res * a) % MOD;
a = (a * a) % MOD;
b >>= 1;
}
return res;
}
ll modInv(ll a) { return binpow(a, MO... |
Game field is represented by a line of n square cells. In some cells there are packmen, in some cells there are asterisks and the rest of the cells are empty. Packmen eat asterisks.
Before the game starts you can choose a movement direction, left or right, for each packman. Once the game begins all the packmen simulta... | #include <bits/stdc++.h>
const int N = 1000000;
int n;
char str[N + 10];
int cdog = 0, fdog = 0, ldog = 0, cbone = 0, fbone = 0, lbone = 0;
int cntd[N + 10], cntb[N + 10];
int nxtd[N + 10], nxtb[N + 10];
int lstd[N + 10], lstb[N + 10];
int tp1[N + 10], tp2[N + 10][2];
bool dp[N + 10];
bool chk(int x) {
memset(dp, 0, ... |
Priests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from k - 1 rocks, possesses power p and we want to... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
const int INF = 0x3f3f3f3f;
int N, M, Q;
int w[MAXN];
vector<int> f;
set<int> ones;
int lft[MAXN][10];
void load() {
scanf("%d%d", &N, &M);
for (int i = 1; i <= N; i++) scanf("%d", w + i);
}
inline int mul(int x, int y, int mod) { return (long ... |
A sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. Th... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
long long p, m;
scanf("%d%lld%lld", &n, &p, &m);
long long curd = 1;
long long curb = 0;
long long sum = 0;
for (int i = 0; i < n; ++i) {
long long d, v;
scanf("%lld%lld", &d, &v);
long long tpos = 0;
if (curb > 0) tpos = cu... |
Jenya has recently acquired quite a useful tool — k-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length k from an arbitrary string s (its length should be at least 2·k in order to perform this operation) and concatenating them afterwards (preserving the initia... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
int z[600000 + 10 + 600000 + 10], form[600000 + 10][2], n, m, k;
string s, t;
void z_function(string S) {
int len = S.length();
S = '$' + S;
int l, r;
memset(z, 0, sizeof(z));
for (int i = 2; i <= len; ++i)
if (S[i] != S[i - 1])
... |
It's marriage season in Ringland!
Ringland has a form of a circle's boundary of length L. There are n bridegrooms and n brides, and bridegrooms decided to marry brides.
Of course, each bridegroom should choose exactly one bride, and each bride should be chosen by exactly one bridegroom.
All objects in Ringland are l... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:512000000")
using namespace std;
void solve(__attribute__((unused)) bool);
void precalc();
clock_t start;
int main() {
start = clock();
int t = 1;
cout.sync_with_stdio(0);
cin.tie(0);
precalc();
cout.precision(10);
cout << fixed;
int testNum = 1;
... |
Alice decides to challenge Bob to a problem. She gives him a number.
Bob can rearrange the digits of this number by applying pair-wise swaps between any 2 digits in the number as many times as he wants. Now Alice asks him to write down all the distinct numbers that he can form and sort them. Of these she wants him to... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
from collections import Counter
cases = int(raw_input())
for case in xrange(0,cases):
st = raw_input()
lis = sorted(list(st))[ : :-1]
sc = Counter(st)
lenlis = len(lis)
if ... |
Big P has become a Physical Education teacher at Hack International School.
Today, the students of class XII have been very undisciplined and he decides to punish them all.
He makes all of the N student (numbered 1 to N ) to stand in a line and asks them to sit down on their knees.
Students know that Big P is a very... | def color_it(friendship_map,student_list,i,visitlist):
if len(friendship_map[i])>0 :
for j in friendship_map[i] :
if not visitlist[j]:
student_list[j-1]=True
visitlist[j]=True
color_it(friendship_map,student_list,j,visitlist)
def solve(friendship_... |
Harry is playing a game with is friend. He is given a notebook which has names of their friends written in various lowercase letter from 'a' to 'z'. His task is to find a 'special-letters'. A letter is a 'special-letters' if it occurs at least once in each of their friends name.
Given the list of N names, display the ... | from sys import stdin
ans = set()
t=int(stdin.readline())
a = stdin.readlines()
b = a[0].strip()
for i in b:
valid = 1
for j in a:
if i not in j:
valid = 0
break
if valid:
ans.add(i)
print len(ans) |
Alice has just learnt multiplying two integers. He wants to multiply two integers X and Y to form a number Z. To make the problem interesting he will choose X in the range [1,M] and Y in the range [1,N]. Help him to find the number of ways in which he can do this.
Input
First line of the input is the number of test ca... | tc = int(raw_input())
for test in xrange(tc):
res =0
z,m,n = [ int(x) for x in raw_input().split() ]
for elem1 in xrange(1,int(z**0.5)+1):
#print "elem 1 --->",elem1
if z%elem1 == 0:
if elem1 == z/elem1 and ((1<= elem1 <= m and 1<= z/elem1 <= n) or ( 1<= elem1 <= n and 1<= z/elem1 <= m)):
#print "Same"
... |
This problem of Oz is very straight forward. You are given N distinct prime integers i.e p1, p2,..., pN and an interval [L,R]. Calculate number of integers in this interval that are divisible by at least one of the given primes.
Input :
First line of input contain an integer T — the number of test cases. T tests foll... | T=int(raw_input())
for i in xrange(T):
N,L,R=map(int, raw_input().split())
arrP=map(int, raw_input().split())
bits=[[] for _ in xrange(N+1)]
for i in xrange(1,pow(2,N)):
bits[bin(i).count("1")].append(i)
# calc for L-1, R inclusive from 1:
numL=0
numR=0
muls=[1]
sign=1
for i in xrange(N):
fo... |
You will be given a set of distinct numbers. Your task is to find that even length subset which will give you a maximum value of P % (10^9 + 7). This value of P for a subset of length N is defined as below :
P = (product of N/2 maximum values) / (product of N/2 minimum values)
Now suppose we have a subset S... | t = input()
while t>0:
t-=1
n = input()
a = map(int, raw_input().split())
l = []
mval = 0
subs = pow(2, n)
for i in range(subs):
ls = []
for j in range(n):
if (i & (1 << j) > 0):
ls.append(a[j])
if len(ls) > 0 and len(ls)%2 == 0:
ls.sort()
mp = 1
minp = 1
for k in range(0,len(ls)/2):
... |
Campus Ambassador has organized a Coding Contest in his college. Contest has multiple rounds, in each round a participant may gain or lose few points. At the end, there is only one participant with the maximum points. In the course of the contest, the number of points is written in the line as
"name points", where nam... | n=int(raw_input())
a={}
for i in range(n):
x,y=raw_input().split()
y=int(y)
if not a.has_key(x):
a[x]=[y,i]
else:
a[x][0]+=y
a[x][1]=i
b=a.items()
b.sort(key=lambda x:(-x[1][0],x[1][1]))
print b[0][0] |
Do you remember the game of Snakes and Ladders ? We have removed all the snakes from the board. However to compensate for the loss of trouble, we have enlarged the board from a maximum limit (Target Square) of 100 to a maximum limit (Target Square) of N ≥ 100, N being a perfect square.
Rani has a match with Nandu on t... | nooftest=input()
for i in range(nooftest):
size,l=map(int,raw_input().split())
dist=[]
ladderdestination=[]
ladderend=[]
for j in range(size+13):
ladderdestination.append(0)
dist.append(-1)
ladderend.append(-1)
for j in range(l):
temp=map(int,raw_input().split())
... |
Given a number X between 0 to 1000000006 find smallest positive integer Y such that the products of digits of Y modulo 1000000007 is X.
Input Format
A single integer - X
Output Format
A single integer - Y
Input Constraint
0 ≤ X ≤ 1000000006
Problem Setter: Practo Tech Team
SAMPLE INPUT
16
SAMPLE OUTPUT
28
Exp... | import sys
def get_min_length_single_digit_factors(x):
original_x = x
factor_counts = [0]*10
for i in xrange(8):
if x < 2:
break
factor = 9-i
while x % factor == 0:
x = x/factor
factor_counts[factor] += 1
if not x==1:
return get_min_length_single_digit_factors(original_x+1000000007)
return facto... |
Now that you have won Code Monk and been hired by HackerEarth as a software engineer, you have been assigned to work on their wildly popular programming contest website.
HackerEarth is expecting a lot of participants (P) in Code Monk next year, and they want to make sure that the site can support that many people at t... | t = int(raw_input())
for cs in xrange(1,t+1):
l,p,c = [int(i) for i in raw_input().split()]
a=0
temp = l
while(temp<p):
temp*=c
a+=1
ans =0
while((1<<ans)<a):
ans+=1
print "Case #"+str(cs)+": "+str(ans) |
Given is an integer S. Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S. The answer can be very large, so output it modulo 10^9 + 7.
Constraints
* 1 \leq S \leq 2000
* All values in input are integers.
Input
Input is given from Standard Input in ... | import java.util.*;
import java.io.*;
class Main {
Scanner in;
InputStream is;
PrintWriter out;
String INPUT = "";
//----------------------------------------------------------------------------------------------------//
int INF = Integer.MAX_VALUE;
int m = (int) (1e9) + 7;
long power(long x... |
A bracket sequence is a string that is one of the following:
1. An empty string;
2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ;
3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B /
Given are N strings S_i. Can a bracket sequence be forme... | #include <bits/stdc++.h>
using namespace std;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int N; cin >> N;
vector<int> sum(N,0),Min(N,0);
int Sum=0;
for (int i=0;i<N;++i){
string S; cin >> S;
for (int j=0;j<S.size();++j){
sum[i]+=(S[j]=='('?1:-1);
... |
For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows:
* Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations.
* Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \time... | #include "bits/stdc++.h"
using namespace std;
long long MOD = 1000 * 1000 * 1000 + 7;
long long p(long long a, long long b) {
if (b == 0) return 1;
if (b == 1) return a;
long long ha = p(a, b/2);
if (b % 2 == 0) return (ha * ha) % MOD;
return (((ha * ha) % MOD) * a) % MOD;
}
int main() {
long long n;
cin >>... |
We have two bottles for holding water.
Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.
Bottle 2 contains C milliliters of water.
We will transfer water from Bottle 2 to Bottle 1 as much as possible.
How much amount of water will remain in Bottle 2?
Constraints
* All val... | A, B, C = list(map(int,input().split()))
print(max((B+C-A),0)) |
You are given a string S of length N consisting of `A`, `C`, `G` and `T`. Answer the following Q queries:
* Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many t... | import sys
input=sys.stdin.readline
n,q=map(int,input().split())
s=input();a=[0]*2
for i in range(2,n+1):
a+=[a[i-1]+s[i-2:i].count("AC")]
for _ in range(q):
l,r=map(int,input().split())
print(a[r]-a[l]) |
There are N blocks arranged in a row, numbered 1 to N from left to right. Each block has a weight, and the weight of Block i is A_i. Snuke will perform the following operation on these blocks N times:
* Choose one block that is still not removed, and remove it. The cost of this operation is the sum of the weights of t... | MOD = 10**9+7
def main():
N = int(input())
A = list(map(int, input().split()))
prodasc = [1] * (N+1)
prodesc = [1] * (N+1)
for i in range(N):
prodasc[i+1] = (prodasc[i] * (i+1)) % MOD
prodesc[i+1] = (prodesc[i] * (N-i)) % MOD
inv = [1] * (N+1)
for i in range(1, N+1):
... |
There is an H \times W grid (H vertical, W horizontal), where each square contains a lowercase English letter. Specifically, the letter in the square at the i-th row and j-th column is equal to the j-th character in the string S_i.
Snuke can apply the following operation to this grid any number of times:
* Choose two... | #include <cstdio>
#include <map>
using namespace std;
typedef unsigned long long ULL;
const int N=15;
const ULL B=133333;
int n,m;
char str[N][N];
inline int abs(int x){
return x>=0?x:-x;
}
void readData(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%s",str[i]+1);
}
bool use[N];
int match[N];
bool check(){
... |
In programming, hexadecimal notation is often used.
In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters `A`, `B`, `C`, `D`, `E` and `F` are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.
In this problem, you are given two letters X and Y. Each X and Y is `A`, `B`, `C`,... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] inputArr = sc.nextLine().split(" ");
sc.close();
char input1 = inputArr[0].charAt(0);
char input2 = inputArr[1].charAt(0);
if(input1 < input2) {
System.out.pri... |
You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K.
a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K?
Constraints
* All input values are integers.
* 1 ≤ N ≤ 2 ... | def examC():
N = I()
S = [I() for _ in range(N)]
S1 = []
for s in S:
if s%10==0:
continue
S1.append(s)
if S1==[]:
print(0)
return
S1.sort()
ans = sum(S)
if ans%10==0:
ans -= S1[0]
print(ans)
return
def examD():
N, A, B = LI... |
There are N pinholes on the xy-plane. The i-th pinhole is located at (x_i,y_i).
We will denote the Manhattan distance between the i-th and j-th pinholes as d(i,j)(=|x_i-x_j|+|y_i-y_j|).
You have a peculiar pair of compasses, called Manhattan Compass. This instrument always points at two of the pinholes. The two legs ... | #include<bits/stdc++.h>
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define rep(i,a,b) for (int i=(a); i<(b); i++)
#define per(i,a,b) for (int i=(b-1); i>=(a); i--)
#define debug(x) cout << #x << " => " << x << endl
using namespace std;
#define fi first
#define se second
#define mp make_pair
t... |
Snuke got an integer sequence from his mother, as a birthday present. The sequence has N elements, and the i-th of them is i. Snuke performs the following Q operations on this sequence. The i-th operation, described by a parameter q_i, is as follows:
* Take the first q_i elements from the sequence obtained by concaten... | #include <bits/stdc++.h>
using namespace std;
#define N 100000
#define ll long long
int n, m, q;
ll a[N + 5], ans[N + 5], coef[N + 5];
void f(ll l, ll v) {
if (!l) return ;
int p = upper_bound(a + 1, a + m + 1, l) - a - 1;
if (!p)
ans[1] += v, ans[l + 1] -= v;
else {
coef[p] += v * (l / a[p]);
f(l % a[p],... |
Jerry is a little mouse. He is trying to survive from the cat Tom. Jerry is carrying a parallelepiped-like piece of cheese of size A × B × C. It is necessary to trail this cheese to the Jerry's house. There are several entrances in the Jerry's house. Each entrance is a rounded hole having its own radius R. Could you he... | #include<stdio.h>
#include<math.h>
#define M(a,b) (a<b?a:b)
int main(){
for(int a,b,c,n,r;scanf("%d%d%d",&a,&b,&c),a|b|c;){
for(scanf("%d",&n);n--;){
scanf("%d",&r);
puts(
(2*r>M(M(sqrt(a*a+b*b),sqrt(b*b+c*c)),sqrt(c*c+a*a)))?
"OK":"NA"
);
}
}
} |
An extension of a complex number is called a quaternion. It is a convenient number that can be used to control the arm of a robot because it is convenient for expressing the rotation of an object. Quaternions are $ using four real numbers $ x $, $ y $, $ z $, $ w $ and special numbers (extended imaginary numbers) $ i $... | #include<iostream>
using namespace std;
#define rep(i, n) for (int i = 0; i < int(n); ++i)
int main() {
while (true) {
int n;
cin >> n;
if (n == 0) break;
while (n--) {
int x1, y1, z1, w1, x2, y2, z2, w2;
cin >> x1 >> y1 >> z1 >> w1 >> x2 >> y2 >> z2 >> w2;
cout << x1 * x2 - y1 * ... |
At Aiz Pharmaceutical, research on chemical substances is carried out every day. I am currently studying the code name "Alpha", a chemical substance that has a structure in which molecules from $ 1 $ to $ N $ are linearly arranged from the left end to the right end.
Using the technology developed by Aiz Pharmaceutical... | #include <iostream>
#include <vector>
#include <array>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <tuple>
#include <bitset>
#include <memory>
#include <cmath>
#include <algorithm>
#include ... |
Advanced Creative Mobile (ACM) has decided to develop a GUI application to be installed in a new portable computer.
As shown in the figure below, the GUI has a nested structure in which it has one main panel, several panels are arranged on it, and some panels are arranged on top of those panels. .. All panels are rect... | #include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
struct Panel{
string name;
int x1,y1,x2,y2;
Panel *parent;
vector<Panel> child;
void init(){name="";x1=y1=x2=y2=0;parent=NULL;child.clear();}
};
Panel list;
pair<string,int>ans;
int maxDepth;
void p... |
A decimal representation of an integer can be transformed to another integer by rearranging the order of digits. Let us make a sequence using this fact.
A non-negative integer a0 and the number of digits L are given first. Applying the following rules, we obtain ai+1 from ai.
1. Express the integer ai in decimal nota... | #include<iostream>
#include<algorithm>
using namespace std;
int a,l;
int vis[1000000];
int mi[10],ma[10];
int main(){
while(cin >> a >> l,l){
int lim = 1;
for(int i=0;i<l;i++)lim *= 10;
for(int i=0;i<lim;i++)vis[i] = -1;
vis[a] = 0;
for(int cnt=1;;cnt++){
for(int i=0;i<l;i++){
mi[i] = m... |
Dr. Jimbo, an applied mathematician, needs to calculate matrices all day for solving his own problems. In his laboratory, he uses an excellent application program for manipulating matrix expressions, however, he cannot use it outside his laboratory because the software consumes much of resources. He wants to manipulate... |
import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
public class Main {
int INF = 1 << 28;
//long INF = 1L << 62;
double EPS = 1e-10;
int MOD = 32768;
void run() {
Scanner sc = new Scanner(System.in);
for(;;) {
i... |
Problem
Aizu Magic School is a school where people who can use magic gather. Aizu Magic School has classrooms numbered from 1 to N and a corridor connecting the classrooms. You can go through the classrooms and corridors as many times as you like. In addition, Aizu Magic School has only one route that allows you to mo... | #define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#define rep(i,n) f... |
ICPC (Internet Contents Providing Company) is working on a killer game named Quiz Millionaire Attack. It is a quiz system played over the Internet. You are joining ICPC as an engineer, and you are responsible for designing a protocol between clients and the game server for this system. As bandwidth assigned for the ser... | #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 105
enum Type{
START,
SERVER_CHECK,
FINISH,
SUBMIT,
};
struct Info{
Info(){
type ... |
The sales department of Japanese Ancient Giant Corp. is visiting a hot spring resort for their recreational trip. For deepening their friendships, they are staying in one large room of a Japanese-style hotel called a ryokan.
In the ryokan, people sleep in Japanese-style beds called futons. They all have put their futo... | #include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <string>
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
#define pb push_back
#define fs first
#define sc seco... |
A Boolean expression is given. In the expression, each variable appears exactly once. Calculate the number of variable assignments that make the expression evaluate to true.
Input
A data set consists of only one line. The Boolean expression is given by a string which consists of digits, x, (, ), |, &, and ~. Other ... | #include <bits/stdc++.h>
using namespace std;
typedef long long lli;
const lli mod = 1000000007LL;
string s;
int p;
pair<lli,lli> exp();
pair<lli,lli> term();
pair<lli,lli> fact();
pair<lli,lli> exp() {
pair<lli,lli> x = term();
lli all = (x.first + x.second) % mod;
lli f = x.second;
while(s[p] == '|'... |
Princess Tetra of the Kingdom of Palace is known as an unrivaled puzzle lover, and has recently been enthusiastic about her own "Tetra puzzle". This is a puzzle that uses a board with equilateral triangle squares and a regular tetrapod block consisting of four equilateral triangle panels called a tetrapod. The purpose ... | #include <bits/stdc++.h>
using namespace std;
#define for_(i,a,b) for(int i=(a);i<(b);++i)
#define allof(a) (a).begin(),(a).end()
typedef pair< int, int > pii;
class BipartiteMatching {
private:
int V;
vector< vector< int > > adj;
vector< int > match;
vector< bool > used;
vector< bool > visible;
bool dfs(int ... |
F: Disordered Data Detection / Anomaly detection
story
Akane Miyamori is an engineer working for Musashino Software. Today, I'm worried about the bug report I received from the customer. "Weird story, the behavior of the software you made last time is plump, can you check it there? Isn't it your job to maintain it?" ... | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define all(v) begin(v), end(v)
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define reps(i, s, n) for(int i = (int)(s); i < (int)(n); i++)
template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;}
template<class T1, class T2> void ch... |
problem
AOR Ika is at the $ S $ th bus stop at time $ 0 $ and wants to go from there to the $ G $ th bus stop. The number of bus stops $ N $ and $ M $ routes (*) connecting different bus stops are given. The bus stops are numbered $ 1, \ dots, and N $, respectively. Each route consists of $ 4 $ values: origin $ u $, d... | #include <bits/stdc++.h>
using namespace std;
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define mp(a,b) make_pair((a),(b))
#define pb(a) push_back((a))
#define all(x) (x).begin(),(x).end()
#define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x))
#define fi first
#define se... |
K is a polygonal Kay
"Do I have to be No. 1? Is it not No. K?"
This is Mr. Kay's inscription. Recently, Mr. Kay seems to be exclusively interested in polygons, seeing N points placed on a vast two-dimensional plane spreading in front of him, and thinking about how to form polygons from them. There is. Apparently, Kay... | #include <algorithm>
#include <set>
#include <vector>
#include <iostream>
#include <complex>
#include <cstdio>
#include <utility>
#include <queue>
using namespace std;
using W = double;
using P = complex<W>;
using L = pair<P,P>;
using Poly = vector<P>;
#define X real()
#define Y imag()
constexpr W EPS = 1e-8;
namesp... |
K Average Ranges
Given the sequence a_1, a_2, .., a_N.
How many intervals in this sequence have an average value of K or more and a length of 1 or more?
input
N K
a_1 a_2 ... a_N
output
Output the answer.
Constraint
* 1 \ leq N \ leq 10 ^ 5
* 1 \ leq K \ leq 10 ^ 9
* 1 \ leq a_i \ leq 10 ^ 9
Input example
... | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdlib>
#include <map>
#include <iomanip>
#include <set>
#include <stdio.h>
#include <ctype.h>
using namespace std;
#define pie 3.141592653589793238462643383279
#... |
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(i, x): add x to ai.
* getSum(s, t): print the sum of as, as+1,...,at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* If comi is 0, then 1 ≤ xi... | from array import array
import bisect
import collections
import heapq
import itertools
import operator
import sys
class BIT:
def __init__(self, n):
self.n = n
self.arr = array("l", [0] * (n + 1))
def __str__(self):
return str(self.arr.tolist())
def add(self, i, x):
while ... |
One day, Chef found a cube which has each of its sides painted in some color out of black, blue, red, green, yellow and orange.
Now he asks you to check if he can choose three sides such that they are pairwise adjacent and painted in the same color.
Input
The first line of the input contains an integer T denoting the... | T = input()
for _ in xrange(T):
ans = "NO"
f = raw_input().split()
f1 = f[0:2]
f2 = f[2:4]
f3 = f[4:]
for side in f1:
if side in f2 and side in f3:
ans = "YES"
break
print ans |
Devu is a class teacher of a class of n students. One day, in the morning prayer of the school, all the students of his class were standing in a line. You are given information of their arrangement by a string s. The string s consists of only letters 'B' and 'G', where 'B' represents a boy and 'G' represents a girl.
De... | def func(typ,k,bg):
count=0
if typ==0:
for i in range(len(k)):
if k[i]!=bg[i]:
count+=1
return count/2
if typ==1 or typ==2:
b=[]
g=[]
for i in range(len(k)):
if k[i]!=bg[i]:
if k[i]=='B':
b.ap... |
You are given e even and o odd numbers. In a single operation, you change an even to odd number or vice versa. Find out min number of operations needed to
do such that ratio of even to odd numbers becomes 2 : 3. If it is impossible to do so, output -1.
Input
The first line of the input contains an integer T denoting... | #Anwesh Mohanty
t=input()
while t>0:
a,b=map(int,raw_input().split())
if((a+b)%5==0):
r=int(2*(a+b)/5)
print abs(r-a)
else:
print -1
t-=1 |
Nikhil has designed the following game. The game is played in a
set of rooms in a dungeon, arranged in an M × N
rectangular grid. In one of the rooms, the evil wazir has imprisoned
the princess. The noble prince is on his way to rescue the
princess.
The prince starts in the room at the top left corner of the grid,
whic... | #!/usr/bin/python
# Richard Lee
# CodeChef
# Nikhils Dungeon
#
import os
import sys
inp = sys.stdin.readline
INF=-1
# what does the board look lke?
l = inp()
p = l.split()
m = int(p[0])
n = int(p[1])
l = ""
for i in xrange(m):
l += inp()
board = [int(i) for i in l.split()]
# where's the princess and how much time... |
Problem description.
Most campuses have a lot of named buildings, and as the names tend to be rather long, the class schedules
have abbreviations. At IITD, it seems that the abbreviations have become used so widely that most people
don’t even remember the full name of the building, such as SAC. To a newcomer, this can... | import copy
cases = int(raw_input())
i = 1
while cases:
cases -= 1
times = int(raw_input())
lis = []
while times:
times -= 1
lis.append(raw_input())
abb = raw_input().lower()
print "Data Set "+ str(i) + ":"
i += 1
j = 0
l1 = len(abb)
for s in lis:
tmp = c... |
Problem Description:
If you know what is XOR and Binary Representation of number you can skip to problem statement.
What is a binary representation of a number ?
All computer calculations are done in binary system that is system containing only 0’s and 1’s. Number, character, images and everything is represented and s... | cases=input()
for i in range(cases):
T=input()
if T%4==0:
print T
elif T%4==1:
print 1
elif T%4==2:
print T+1
else:
print 0 |
This is an interactive problem.
Bob lives in a square grid of size n × n, with rows numbered 1 through n from top to bottom, and columns numbered 1 through n from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer n.
Bob can move... | #include <bits/stdc++.h>
using namespace std;
int n, route[1010];
char cans[10];
int ans[1010];
bool getans() {
cin >> cans;
if (cans[0] == 'Y') return 1;
return 0;
}
int main() {
cin >> n;
int x = n, y = n;
for (int i = 1; i < n; i++) {
cout << "? 1 1 " << x - 1 << ' ' << y << endl;
cout.flush();
... |
Let T be a tree on n vertices. Consider a graph G_0, initially equal to T. You are given a sequence of q updates, where the i-th update is given as a pair of two distinct integers u_i and v_i.
For every i from 1 to q, we define the graph G_i as follows:
* If G_{i-1} contains an edge \\{u_i, v_i\}, then remove thi... | #include <bits/stdc++.h>
using namespace std;
const int N = 300005;
set<int> s[N];
int n, q, i, j, k, x, y, z, head[N], adj[N * 2], nxt[N * 2], size[N], id[N],
dep[N], p[N][25], mark[N * 5], num[N * 5];
void update(int o, int l, int r, int x, int y) {
if (l == x && r == y) {
mark[o] += z;
if (mark[o])
... |
Let's define rank of undirected graph as rank of its adjacency matrix in R^{n × n}.
Given a tree. Each edge of this tree will be deleted with probability 1/2, all these deletions are independent. Let E be the expected rank of resulting forest. Find E ⋅ 2^{n-1} modulo 998244353 (it is easy to show that E ⋅ 2^{n-1} is a... | #include <bits/stdc++.h>
using i64 = long long;
constexpr int maxn = 500000;
constexpr int p = 998244353;
template <class x_tp, class y_tp>
inline void inc(x_tp &x, const y_tp y) {
x += y;
(p <= x) && (x -= p);
}
template <class _Tp>
inline _Tp div2(const _Tp &v) {
return ((v & 1) ? v + p : v) >> 1;
}
template <c... |
The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).
For each house, the... | class Node:
def __init__(self,index):
self.index = index
self.inputs = []
self.outputs = []
self.d = 10000000
self.do = 0
self.d2 = 10000000
self.di = 0
def find(nodes,n):
s = n.index
e = 0
m = n.d
o = n.do
while( o != 0 ):
if nodes[o-1].d < m:
m = nodes[o-1].d
e = nodes[o-1].index
o = nod... |
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in t... | import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
public static final int MOD = 998_244_353;
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter... |
In the country N, there are n cities connected by m one-way roads. Although this country seems unremarkable, there are two interesting facts about it. At first, a week lasts d days here. At second, there is exactly one museum in each city of the country N.
Travel agency "Open museums" is developing a new program for t... | #include <bits/stdc++.h>
using namespace std;
ostream& operator<<(ostream& cerr, vector<long long> aux) {
cerr << "[";
for (auto e : aux) cerr << e << ' ';
cerr << "]";
return cerr;
}
struct state {
int x, y;
int where;
};
const int maxN = 100011;
const int maxD = 54;
const int init = 1000000000;
int n, m, ... |
Let's analyze a program written on some strange programming language. The variables in this language have names consisting of 1 to 4 characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.
There are four types ... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1009;
string a[MAXN][4];
long long n;
bool u[MAXN];
string name[10 * MAXN];
long long pt;
string gen(map<string, vector<pair<long long, long long> > >& pos) {
while (pos.find(name[pt]) != pos.end()) {
pt++;
if (pt >= 10 * MAXN) pt = 0;
}
... |
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A >... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import ja... |
You are given a sorted array a_1, a_2, ..., a_n (for each index i > 1 condition a_i ≥ a_{i-1} holds) and an integer k.
You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let max(i) be equal to the maximum in the i-th subar... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Random;
/*
Solution Created: 01:57:06 09/06/2019
Custom Competitive programming helper.
*/... |
All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.
Treasure Island may be represented as a rectangular table n × m which is surrounded by the ocean. Let us number rows of the field with consecutive integers from 1 to n from top to bottom and columns with consecutive integers from... | #include <bits/stdc++.h>
using namespace std;
const int MOD = (int)1e9 + 7;
const int MAX = 1e6;
int ans = 0;
int dfs(int x, int y, string s[], int R, int C) {
if (x == R || y == C) return 0;
if (x == R - 1 && y == C - 1) {
return 1;
}
if (s[x][y] == '.') {
s[x][y] = '#';
int val = dfs(x, y + 1, s, ... |
Consider a square grid with h rows and w columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.
Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered b... | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
int mult(int a, int b) { return (1LL * a * b) % mod; }
int sum(int a, int b) {
int s = a + b;
if (s >= mod) s -= mod;
return s;
}
int sub(int a, int b) {
int s = a - b;
if (s < 0) s += mod;
return s;
}
int pw(int a, int b) {
if (b ==... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.