input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ... | #include <bits/stdc++.h>
using std::abs;
using std::array;
using std::cerr;
using std::cin;
using std::cout;
using std::generate;
using std::get;
using std::make_pair;
using std::make_tuple;
using std::map;
using std::max;
using std::max_element;
using std::min;
using std::min_element;
using std::pair;
using std::queue... |
Let a and b be two arrays of lengths n and m, respectively, with no elements in common. We can define a new array merge(a,b) of length n+m recursively as follows:
* If one of the arrays is empty, the result is the other array. That is, merge(∅,b)=b and merge(a,∅)=a. In particular, merge(∅,∅)=∅.
* If both arrays a... | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fcking inter... |
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 100;
int t, n, a[N], b[N];
bool solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
b[i] = a[i];
}
sort(b + 1, b + n + 1);
int mn = b[1];
for (int i = 1; i <= n; i++) {
if (a[i] == b[i]) continue;
if (a[i] % mn) {
... |
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (b == 0LL) return a;
return gcd(b, a % b);
}
long long bigmod(long long a, long long b, long long mod) {
if (b == 0LL) return 1LL;
long long sq = bigmod(a, b / 2LL, mod);
sq = (sq * sq) % mod;
if (b & 1LL) return (sq ... |
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i.
You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W.
Output the list... | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception
{
FastReader fr=new FastReader();
int t=fr.nextInt();
while(t-->0) {
int n=fr.nextInt();
long wt=fr.nextLong();
int w[]=new int[n];
HashMap<Integer... |
Petya organized a strange birthday party. He invited n friends and assigned an integer k_i to the i-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are m unique presents available, the j-th present costs c_j dollars (1 ≤ c_1 ≤ c_2 ≤ … ≤ c_m). It's not allowed to buy a single... | import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import List
sys.setrecursionlimit(99999)
t, = map(int, sys.stdin.readline().split())
for _ in range(t):
n, m = map(int, sys.stdin.readline... |
You are given a multiset S initially consisting of n distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.
You will perform the following operation k times:
* Add the element ⌈(a+b)/(2)⌉ (rounded up) into S, where a = \operatorname{mex}(S) and b = max(S). If this numbe... | #include<bits/stdc++.h>
#define ll long long
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
using namespace std;
int main()
{
fio;
ll t=0;
cin>>t;
for(ll z=0; z<t; z++){
ll n,k,temp;
cin>>n>>k;
vector<ll> v;
for(int i = 0; i < n; i++){
cin>>tem... |
There are n points on an infinite plane. The i-th point has coordinates (x_i, y_i) such that x_i > 0 and y_i > 0. The coordinates are not necessarily integer.
In one move you perform the following operations:
* choose two points a and b (a ≠ b);
* move point a from (x_a, y_a) to either (x_a + 1, y_a) or (x_a, y... | #pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
// #include<ext/pb_ds/assoc_container.hpp>
// #include<ext/pb_ds/tree_policy.hpp>
// #include<ext/pb_ds/tag_and_trait.hpp>
// using namespace __gnu_pbds;
// #include<boost/multiprecision/cpp_int.hpp>
// nam... |
Cirno has prepared n arrays of length n each. Each array is a permutation of n integers from 1 to n. These arrays are special: for all 1 ≤ i ≤ n, if we take the i-th element of each array and form another array of length n with these elements, the resultant array is also a permutation of n integers from 1 to n. In the ... | #include <bits/stdc++.h>
#define FOR(i,a,b) for(long long i=a;i<=b;i++)
#define FORD(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
string s;
const int mn = 505;
const int md = 998244353;
int n, a[mn*2][mn], id[mn*2], removed[mn*2];
void solve()
{
long long way = 1;
vector<int> res;
int cur_size = ... |
A group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.
Polycarpus has already began the pro... | #include <bits/stdc++.h>
using namespace std;
double a[100];
int main() {
int n;
double b, sum, m = 0, one;
cin >> n >> b;
sum = b;
for (int i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
m = max(m, a[i]);
}
one = sum / n;
if (m > one) {
cout << -1;
return 0;
}
for (int i = 0; i ... |
There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downward... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
long long int n;
cin >> t;
for (int i = 0; i < t; ++i) {
cin >> n;
if (n % 2 == 0)
cout << 4 * n + 1;
else if (n % 4 == 1)
cout << 2 * n + 1;
else if (n % 4 == 3)
cout << n + 1;
else
;
cout << "\n";... |
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
* it is up to a passenger to choose a plane to fly on;
* if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs ... | n,m=list(map(int,input().split()))
L=list(map(int,input().split()))
P=list(map(int,L))
mi=0
ma=0
for i in range(n):
x=max(L)
ma+=x
L[L.index(x)]-=1
#print(P)
for i in range(n):
x=min(P)
if x==0:
P.remove(x)
x=min(P)
mi+=x
P[P.index(x)]-=1
print(ma,mi) |
The Old City is a rectangular city represented as an m × n grid of blocks. This city contains many buildings, straight two-way streets and junctions. Each junction and each building is exactly one block. All the streets have width of one block and are either vertical or horizontal. There is a junction on both sides of ... | #include <bits/stdc++.h>
using namespace std;
int n, m, k, pn;
char s[111][111];
int dxy[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
struct edge {
int v, w, next;
edge() {}
edge(int _v, int _w, int _next) {
v = _v;
w = _w;
next = _next;
}
} e[200011];
int head[100011], sz;
void init() {
memset(hea... |
You've got an array, consisting of n integers: a1, a2, ..., an. Your task is to quickly run the queries of two types:
1. Assign value x to all elements from l to r inclusive. After such query the values of the elements of array al, al + 1, ..., ar become equal to x.
2. Calculate and print sum <image>, where k does... | #include <bits/stdc++.h>
using namespace std;
int c[100005][6][6];
const int modo = 1000000007;
int sum[100005][6];
int val[1 << 18][6];
int a[100005];
int tag[1 << 18];
void updates(int num, int delta) {
register int i;
for (i = 0; i <= 5; i++) {
val[num][i] = val[num * 2 + 1][i];
int j;
for (j = 0; j ... |
How horrible! The empire of galactic chickens tries to conquer a beautiful city «Z», they have built a huge incubator that produces millions of chicken soldiers a day, and fenced it around. The huge incubator looks like a poligon on the the plane Oxy with n vertices. Naturally, DravDe can't keep still, he wants to dest... | #include <bits/stdc++.h>
using namespace std;
struct Point {
double x, y;
Point operator*(double cof) {
Point ret;
ret.x = x * cof;
ret.y = y * cof;
return ret;
}
Point operator+(Point other) {
Point ret;
ret.x = x + other.x;
ret.y = y + other.y;
return ret;
}
Point operator-... |
Sereja has a sequence that consists of n positive integers, a1, a2, ..., an.
First Sereja took a piece of squared paper and wrote all distinct non-empty non-decreasing subsequences of sequence a. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exce... | #include <bits/stdc++.h>
using namespace std;
int fen[100005];
int mod = 1000000007;
void upd(int n, int pos, int val) {
for (; pos <= n; pos |= (pos + 1)) {
fen[pos] += val;
if (fen[pos] >= mod) fen[pos] -= mod;
}
}
int fnd(int pos) {
int ret = 0;
for (; pos >= 0; pos = (pos & (pos + 1)) - 1) {
ret... |
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to r... | import java.util.ArrayList;
import java.util.Scanner;
public class SolutionB {
static int dfs1(int v, int p, int[] maxDistanceDown, boolean marked[], ArrayList<Integer> adj[])
{
maxDistanceDown[v] = marked[v] ? 0 : -1;
for(int i = 0; i < adj[v].size(); i++)
{
int u = adj[v]... |
Levko loves all sorts of sets very much.
Levko has two arrays of integers a1, a2, ... , an and b1, b2, ... , bm and a prime number p. Today he generates n sets. Let's describe the generation process for the i-th set:
1. First it has a single number 1.
2. Let's take any element c from this set. For all j (1 ≤ j ≤... | #include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m, p;
int a[N], b[N];
int dr[N], dn, r[N], f[N];
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
int fpm(int a, int b, int p) {
int w = 1;
for (; b; b >>= 1, a = 1LL * a * a % p)
if (b & 1) w = 1LL * w * a % p;
return w;
}
int ... |
Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.
Iahub can choose a pair of distinct indices i and j (1 ≤ i, j ≤ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, k, i, j;
cin >> n >> m >> k;
cout << m * (m - 1) / 2 << endl;
if (k) {
for (i = 1; i < m; i++)
for (j = i + 1; j <= m; j++) cout << j << " " << i << endl;
} else {
for (i = 1; i < m; i++)
for (j = i + 1; j <= m; j++) cout... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | cols = int(input(""))
inputs = input("")
inputList = inputs.split(' ')
inputList.sort(key=int)
for i in inputList:
print(i, end=" ")
|
Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).
In the tournament, each team plays exactly one home game and exactly one aw... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] home = new int[n];
int[] guest = new int[n];
int[] home_count = new int[100001];
int[] guest_coun... |
Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony.
<image>
A sequence of positive integers bi is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmo... | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Ar... |
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dream... | #include <bits/stdc++.h>
using namespace std;
int a[4] = {1, 2, 3, 5};
int main(void) {
int n, k;
scanf("%d%d", &n, &k);
printf("%d\n", (5 + 6 * (n - 1)) * k);
for (int i = 0; i < n; i++) {
printf("%d %d %d %d\n", (a[0] + 6 * i) * k, (a[1] + 6 * i) * k,
(a[2] + 6 * i) * k, (a[3] + 6 * i) * k);
... |
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.
... | names = {}
N = int(raw_input())
for n in range(N):
name = raw_input().strip()
try:
names[name] += 1
print name+str(names[name])
except:
names[name] = 0
print 'OK' |
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent ... | import java.io.*;
import java.util.*;
public class CF_530B {
public static void main(String[] args) throws IOException {
new CF_530B().solve();
}
void solve() throws IOException{
InputStream in = System.in;
PrintStream out = System.out;
// in = new FileInputStre... |
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-... | from itertools import combinations
def solve():
n="00"+input()
for s in (int(n[i]+n[j]+n[k]) for i,j,k in combinations(range(len(n)),3)):
if s%8==0:
print("YES\n{}".format(s))
exit(0)
print("NO")
solve()
|
A tree of size n is an undirected connected graph consisting of n vertices without cycles.
Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vert... | #include <bits/stdc++.h>
using namespace std;
void read_file(bool outToFile = true) {}
int n, m;
int p[100000 + 9];
vector<vector<int> > cycle;
bool vis[100000 + 9];
void DFS(int i) {
vis[i] = true;
cycle[m].push_back(i);
if (!vis[p[i]]) DFS(p[i]);
}
int main() {
read_file();
while (cin >> n) {
int chosen... |
Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces a... | //package CF;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A{
public static void main(String[] args) throws NumberFormatException, IOException{
Scanner bf = n... |
You are given an array with n integers ai and m queries. Each query is described by two integers (lj, rj).
Let's define the function <image>. The function is defined for only u ≤ v.
For each query print the maximal value of the function f(ax, ay) over all lj ≤ x, y ≤ rj, ax ≤ ay.
Input
The first line contains two i... | #include <bits/stdc++.h>
using namespace std;
const int tam = 100010;
const int MOD = 1000000007;
const int MOD1 = 998244353;
const double EPS = 1e-9;
const double PI = acos(-1);
const int sq = 225;
int ar[tam];
int res[tam];
bool comp(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) {
if (a.first.first / sq... |
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.
Artem wants to create a basic multiset of integers. He wants these structure to support operations of three typ... | #include <bits/stdc++.h>
using namespace std;
struct itree {
int L, R;
itree *l = 0, *r = 0;
int info = 0;
itree(int L, int R) : L(L), R(R) {}
itree() : L(0), R(INT_MAX) {}
void update(int i) {
info++;
if (R > L + 1) {
int M = (L + R) / 2;
if (l == 0) l = new itree(L, M);
if (r == ... |
Recently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested fo... | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static class Folder{
Folder father = null;
int foldercnt= 0;
int fCnt = 0;
String name;
ArrayList<Folder> foldersons = new ArrayList<Folder>();
ArrayList<String> sons = new ArrayList<Stri... |
To add insult to injury, the zombies have taken all but two drawings from Heidi! Please help her recover the Tree of Life from only these two drawings.
Input
The input format is the same as in the medium version, except that now the bound on n is 2 ≤ n ≤ 1000 and that k = 2.
Output
The same as in the medium version... | #include <bits/stdc++.h>
using namespace std;
const int MaxN = 1010, MaxM = 2010;
const unsigned long long base = 300007, mod = 100000000000007ll;
unsigned long long rand_val[MaxN];
class Graph {
public:
int en[MaxN], next[MaxM], to[MaxM], tot;
int lab[MaxN];
void add_edge(int x, int y) {
next[++tot] = en[x]... |
ZS the Coder is given two permutations p and q of {1, 2, ..., n}, but some of their elements are replaced with 0. The distance between two permutations p and q is defined as the minimum number of moves required to turn p into q. A move consists of swapping exactly 2 elements of p.
ZS the Coder wants to determine the n... | #include <bits/stdc++.h>
using namespace std;
int dg[2010], a[2010], b[2010], n, dp[2010][2010];
int va[2010], vb[2010], v[2010], vs[2010], f[2010], g[2010], h[2010];
int A, B, X, C, D, fac[2010], inv[2010];
int gmod(int x) { return x >= 998244353 ? x - 998244353 : x; }
void mul(int a[], int b[], int c[]) {
for (int ... |
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he ne... | import java.util.Scanner;
public class P736B
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if (prime(n))
System.out.println(1);
else if (n % 2 == 0 || prime(n - 2))
System.out.println(2);
else
System.out.println(3);
in.close();
}
public... |
n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if h... | #include <bits/stdc++.h>
using namespace std;
namespace ib {
char b[100];
}
inline void pi(int x) {
if (x == 0) {
putchar(48);
return;
}
if (x < 0) {
putchar('-');
x = -x;
}
char *s = ib::b;
while (x) *(++s) = x % 10, x /= 10;
while (s != ib::b) putchar((*(s--)) + 48);
}
inline void ri(int... |
A couple of friends, Axel and Marston are travelling across the country of Bitland. There are n towns in Bitland, with some pairs of towns connected by one-directional roads. Each road in Bitland is either a pedestrian road or a bike road. There can be multiple roads between any pair of towns, and may even be a road fr... | #include <bits/stdc++.h>
const int MAX_N = 500 + 10;
std::bitset<MAX_N> f[2][64][MAX_N], g, temp;
int n, m;
int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < m; ++i) {
int x, y, t;
scanf("%d %d %d", &x, &y, &t);
f[t][0][x][y] = 1;
}
for (int i = 1; i <= 60; ++i)
for (int j = 1; j <= n; ++... |
Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"
We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-t... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 500005;
int N, M, C, ban[MAXN], ans[MAXN], done[MAXN];
set<int> pset;
vector<int> color[MAXN], E[MAXN];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
;
cin >> N >> M;
C = 0;
int rt = 0;
for (int i = (1); i <= (N); i++) {
int K;
... |
Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.
One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible... | import java.io.*;
import java.util.*;
public class Sets {
public void run() {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
Scanner scanner = new Scanner(in);
int n = scanner.nextInt();
int[][] papers = new int[n * (n - 1) / 2][];
int[] id = new int[200 + 1];
boolean[][] ... |
Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex.
Yesterday Ivan learned Landau's criterion: there is tournament with scores d1 ≤ d2 ≤ ... ≤ dn ... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int UNDEF = -1;
const long long INF = 1e18;
template <typename T>
inline bool chkmax(T &aa, T bb) {
return aa < bb ? aa = bb, true : false;
}
template <typename T>
inline bool chkmin(T &aa, T bb) {
return aa > bb ? aa = bb, true : false... |
You are given a string s consisting of n lowercase Latin letters. Some indices in this string are marked as forbidden.
You want to find a string a such that the value of |a|·f(a) is maximum possible, where f(a) is the number of occurences of a in s such that these occurences end in non-forbidden indices. So, for examp... | //package Strings;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
public class forbiddenIndices {
static class pair implements Comparable<pair... |
Vasya has an array of integers of length n.
Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13, 13, 7, 7, 7, 2, 2, 2], then after one operat... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Solution{
... |
It is winter now, and Max decided it's about time he watered the garden.
The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned ... | t=int(input())
for _ in range(t):
n,k=list(map(int,input().split()))
x=list(map(int,input().split()))
b=[]
for i in range(1,n+1):
a=[]
for j in range(k):
a.append(abs(x[j]-i))
b.append(min(a))
print(max(b)+1) |
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the m... | #include <bits/stdc++.h>
using namespace std;
struct TrieNode {
int cnt;
TrieNode *arr[2];
};
TrieNode *newNode() {
TrieNode *temp = new TrieNode;
temp->cnt = 0;
temp->arr[0] = temp->arr[1] = NULL;
return temp;
}
void insert(TrieNode *root, int pre_xor) {
TrieNode *temp = root;
for (int i = 32 - 1; i >=... |
You are given a sequence of n positive integers d1, d2, ..., dn (d1 < d2 < ... < dn). Your task is to construct an undirected graph such that:
* there are exactly dn + 1 vertices;
* there are no self-loops;
* there are no multiple edges;
* there are no more than 106 edges;
* its degree set is equal to d.... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
int d[1010];
cin >> n;
for (int i = 0; i < n; i++) cin >> d[i];
vector<vector<int> > G(d[n - 1] + 1);
int l = 0, m = 0;
for (int i = 0, j = n - 1; i <= j; i++, j--) {
for (int k = 0; k < d[i]; k++)
for (int t = l; t <= l + d[j]; t... |
Allen wants to enter a fan zone that occupies a round square and has n entrances.
There already is a queue of a_i people in front of the i-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.
Allen uses the following strategy to enter the fan zone:
* Initially he stands... | import math
num_entrances = int(raw_input())
num_people = map(int, raw_input().split())
when_he_arrives = num_people
for i in range(len(num_people)):
when_he_arrives[i] = num_people[i] - i
# import pdb; pdb.set_trace()
min_en = (999999999999, 999999999999) #entrance number, num iter
for j in range(len(num_people)... |
A square pyramid of balls consists of square layers of balls stacked on top of each other. The i th (1-based indexing )layer from the top consists of exactly i^2 balls. Image
You have received one such beautiful square pyramid on your birthday, with each layer having a unique color. However, being the clumsy doofus yo... | n = input()
a = map(int, raw_input().split() )
a.sort()
layer, result = 1, 0
for u in a:
while layer * layer < u:
result += layer * layer
layer += 1
result += layer * layer - u
layer += 1
print result |
"Money money MONEY, I want money" thought Alex. "Now how do I get money? Well... I'll open up a camp!"
Well, unfortunately things didn't go so well for Alex's campers, and now there are N campers wandering around the city aimlessly. You have to handle Q queries; which consist of two groups finding each other and becom... | def union(parents, depths, i, j):
''' Union with under the deepest root '''
if depths[i] > depths[j]:
parents[j] = i
else:
parents[i] = j
depths[i] = max(depths[i], depths[j] + 1)
def find(parents, el):
''' Find an element and compress the sets '''
if parents[el] == el: retu... |
Shivani is interning at HackerEarth. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and may have distributed the chocolates unequally. One of the program managers gets to know this and orders Shivani to make sure everyone gets equal number of chocolates.
But to make ... | T = int(raw_input().strip())
inc_list= [1,2,5]
for t in range(T):
N = int(raw_input().strip())
nums = [int(i) for i in raw_input().strip().split()]
nums.sort()
step = 0
addition = 0
for i in range(1,len(nums)):
diff = nums[i]-nums[0]
while diff:
if diff>=5:
add_step = diff/5
sub = add_step*5
eli... |
Golu loves prime numbers . He wants to do something new with prime numbers. So Molu gives him a number and asks him to minmum number of prime numbers required such that their sum is equal to given number. This task is very diffcult for Golu so he asks you for your help.
Now your task is that you are given a number and... | import math
def check(n):
return all( n%i for i in range(2, int(math.sqrt(n) ) + 1 ))
for i in range(input()):
val = input()
print "1" if check(val) else "2" if check(val-2) or val % 2 == 0 else "3"
"""
import math
primes = []
def primeSieve(sieveSize):
sieve = [True] * sieveSize
sieve[0] = False
sie... |
Kuldeep's girlfriend Christie recently got her PhD in Maths. So to celebrate, they both decided to play games with mathematical sequences for their date nights.
The game they are playing today is "Jackpot Palindrome", the objective of the game is to find out length of the largest palindrome which only contains the dig... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
T = int(raw_input())
t = 0
while(t<T):
t = t+1
N = int(raw_input())
n = N
length = 1
while( (n - 2*length + 1) >= 0):
n = n - (2**length)*length
length = length + 1
leng... |
Navi is a famous shopkeeper in his locality. He gives discounts to his regular customers. Some new rules have been made due to which he is in trouble. According to the new rules, any shopkeeper can sale his items to only one customer in a day. But every customer has some issues like the total money they have or the tot... | import math
def solve(indx, sums, prev, curr):
global noOfItem, cnts, wtMax, price, weight
if indx == noOfItem or curr == cnts or sums == wtMax:
return prev
ans1 = solve(indx + 1, sums, prev, curr)
ans2 = 0
if (sums + weight[indx]) <= wtMax:
ans2 = solve(indx + 1, sums + weight[ind... |
Heading ##There are two integers A and B. You are required to compute the bitwise AND amongst all natural numbers lying between A and B, both inclusive.
Input Format
First line of the input contains T, the number of testcases to follow.
Each testcase in a newline contains A and B separated by a single space.
Constrai... | tc=input()
while tc:
a,b=map(int,raw_input().split())
if a<b:
print a
else:
print b
tc=tc-1 |
Richard is a travel freak. He is now out to travel to a distant place with his friends, so he took his car and went out with a certain amount of fuel. Thus he must stop at a fuel station before his fuel gets over. There are several fuel station with 1 km gap providing fixed amount of fuel.
At each fuel station his tan... | def distance(dis,alist):
i=0
next=0
mx =0
t=0
while i<dis-1 and next<dis-1:
mx=max(mx,i+int(alist[i]))
if i==next:
if mx == next:
return -1
next = mx
t+=1
i+=1
return t
test=int(raw_input())
while test>0:
dis=int(... |
Gudi, a fun loving girl from the city of Dun, travels to Azkahar - a strange land beyond the mountains. She arrives at the gates of Castle Grey, owned by Puchi,the lord of Azkahar to claim the treasure that it guards. However, destiny has other plans for her as she has to move through floors, crossing obstacles on her... | from operator import xor
tests = int(raw_input())
for test in range(tests):
number = int(raw_input())
count = 0
for i in range(1, number):
for j in range(i+1, number+1):
if xor(i, j) <= number:
count +=1
print count |
Xenny had N numbers and he loved equal triplets (An equal triplet is group of 3 numbers that are equal).
He defined a K-equal-triplet as a triplet in which all 3 integers were equal to K.
Given an integer K, he wanted to find out the probability of getting a K-equal triplet, from the N numbers.
Xenny is bad at underst... | def gcd(a,b):
if a == 0:
return b
if b == 0:
return a;
return gcd(b%a, a)
test = int(raw_input())
for i in range(test):
n,k = map(long, raw_input().split())
arr = map(long, raw_input().split())
cnt = 0
for j in range(0, n):
x = arr[j]
if x==k:
cnt... |
We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N. Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].
Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i. Now, process the following query Q times:
... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll f[520][100005],ans[100005];
int n,q,v[300005],w[300005];
typedef pair<int,int> pr;
vector<pr> qr[300005];
ll Query(int x,int va){
if(x<512)return f[x][va];
ll ret=Query(x/2,va);
if(va>=v[x])ret=max(ret,Query(x/2,va-v[x])+w[x]);
return ret;
}
void... |
We have A balls with the string S written on each of them and B balls with the string T written on each of them.
From these balls, Takahashi chooses one with the string U written on it and throws it away.
Find the number of balls with the string S and balls with the string T that we have now.
Constraints
* S, T, and ... | S,T=input().split()
a,b=map(int,input().split())
n=input()
if S==n:
print(a-1,b)
else:
print(a,b-1) |
Takahashi is going to buy N items one by one.
The price of the i-th item he buys is A_i yen (the currency of Japan).
He has M discount tickets, and he can use any number of them when buying an item.
If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nea... | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m,i;
long long sum = 0;
scanf("%d %d",&n,&m);
priority_queue<int> q;
for(i=0;i<n;i++)
{
int x;
scanf("%d",&x);
q.push(x);
}
while (m--)
{
int x = q.top();
q.pop();
q.push(x / 2);
}
while (!q.empty())
{
sum += q.top();
q.pop();... |
Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | R,G,B,N=map(int,input().split())
ans=0
for i in range(1+N//R):
r=R*i
for j in range(1+(N-r)//G):
g=G*j
if (N-r-g)%B==0:
ans+=1
print(ans) |
You are given an integer sequence of length N: A_1,A_2,...,A_N. Let us perform Q operations in order. The i-th operation is described by two integers X_i and Y_i. In this operation, we will choose one of the following two actions and perform it:
* Swap the values of A_{X_i} and A_{Y_i}
* Do nothing
There are 2^Q wa... | #include<cstdio>
const int mod=1000000007;
const int inv2=(mod+1)/2;
int n,m,a[5010],x,y,i,j;
long long p[5010][5010],t;
int main()
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;++i)scanf("%d",a+i);
for(i=1;i<=n;++i)for(j=1;j<=n;++j)p[i][j]=a[i]>a[j];
for (int k=0;k<m;k++) {
scanf("%d%d",&x,&y);
p[x][y]=p[y][x]=(p[x][y... |
Takahashi and Aoki love calculating things, so they will play with numbers now.
First, they came up with one positive integer each. Takahashi came up with X, and Aoki came up with Y. Then, they will enjoy themselves by repeating the following operation K times:
* Compute the bitwise AND of the number currently kept b... | using namespace std;
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 1000010
int n,m,k;
char str[N];
int s[N],t[N];
struct Node{
Node *pre,*suc;
int s,n;
} *fir,*lst;
Node *ins(Node *p,int s,int n=1){
Node *nw=new Node;
*nw={p,p->suc,s,n};
if (p->suc)
p->suc->pre=nw;
else
lst=nw;
p->suc=n... |
Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.
He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.
Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
Constraints
* 1 \leq K \leq N... | from collections import Counter
n, k = map(int, input().split())
xs = map(int, input().split())
ctr = Counter(xs)
cnts = sorted(ctr.values())
ans = n - sum(cnts[-k:])
print(ans)
|
Snuke is giving cookies to his three goats.
He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins).
Your task is to determine whether Snuke can give cookies to his three goats so that each of them ca... | from sys import stdin
a,b = map(int,stdin.readline().split())
ans = 'Impossible'
c = a+b
x = [a,b,c]
def ch(n):
if n==0:
return 0
if n%3:
return 0
return 1
for i in x:
if ch(i):
ans = 'Possible'
print ans |
Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.
You are given Smeke's current rating, x. Print `ABC` if Smeke will participate in ABC, and print `ARC` otherwise.
Constraints
* 1 ≦ x ≦ 3{,}000
* x i... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
String message = "";
if (a < 1200) {
message = "ABC";
} else {
message = "ARC";
}
System.out... |
Kyoto University decided to build a straight wall on the west side of the university to protect against gorillas that attack the university from the west every night. Since it is difficult to protect the university at some points along the wall where gorillas attack violently, reinforcement materials are also built at ... | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZER... |
Consider a sequence of n numbers using integers from 0 to 9 k1, k2, ..., kn. Read the positive integers n and s,
k1 + 2 x k2 + 3 x k3 + ... + n x kn = s
Create a program that outputs how many rows of n numbers such as. However, the same number does not appear more than once in one "n sequence of numbers".
Input
T... | #include <iostream>
#include <cstring>
using namespace std;
#define LIMIT 330
int cnt[11][LIMIT+1];
bool used[11];
void make(int k,int N,int sum){
if(sum > LIMIT) return;
if(N == 0){
cnt[k][sum]++;
return;
}
for(int i = 0 ; i <= 9 ; i++){
if(!used[i]){
used[i] = true;
make(k + 1 , ... |
Taro Aizu's company has a boss who hates being indivisible. When Taro goes out to eat with his boss, he pays by splitting the bill, but when the payment amount is not divisible by the number of participants, his boss always pays for it.
One day, Taro became the secretary of the dinner party. Mr. Taro, who has little m... | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <set>
using namespace std;
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define rep(i, n) FOR(i, 0, n)
const int N = 1000001;
bool isP[N], dp[N];
int main(){
FOR(i, 2, N) isP[i] = 1;
FOR(i, 2, N){
if(i... |
A plurality of trampolines are arranged in a line at 10 m intervals. Each trampoline has its own maximum horizontal distance within which the jumper can jump safely. Starting from the left-most trampoline, the jumper jumps to another trampoline within the allowed jumping range. The jumper wants to repeat jumping until ... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
#define pb push_back
#define rep(i, a, n) for(int i = (a); i < (n); i++)
#define dep(i, a, n) for(int i = (a); i >= (n); i--)
#define mod (ll)(1e9+7)
#define int ll
__attribute__((constructor))... |
JOI is a baby playing with a rope. The rope has length $N$, and it is placed as a straight line from left to right. The rope consists of $N$ cords. The cords are connected as a straight line. Each cord has length 1 and thickness 1. In total, $M$ colors are used for the rope. The color of the $i$-th cord from left is $C... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <cassert>
typedef long long ll;
using namespace std;
#define debug(x) c... |
The Ohgas are a prestigious family based on Hachioji. The head of the family, Mr. Nemochi Ohga, a famous wealthy man, wishes to increase his fortune by depositing his money to an operation company. You are asked to help Mr. Ohga maximize his profit by operating the given money during a specified period.
From a given l... | #include <cstdio>
#include <cstdlib>
int main(){
int m;
scanf( "%d", &m );
for( int i = 0; i < m; i++ ) {
int ini_fund;
int y, n;
int max_fund = 0;
scanf( "%d%d%d", &ini_fund, &y, &n );
for( int j = 0; j < n; j++ ) {
int type;
int a, b, cost;
int sum = 0;
double alpha;... |
Here is a very simple variation of the game backgammon, named “Minimal Backgammon”. The game is played by only one player, using only one of the dice and only one checker (the token used by the player).
The game board is a line of (N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker ... | #define _CRT_SECURE_NO_WARNINGS
#pragma comment (linker, "/STACK:526000000")
#include "bits/stdc++.h"
using namespace std;
typedef string::const_iterator State;
#define eps 1e-11L
#define MAX_MOD 1000000007LL
#define GYAKU 500000004LL
#define MOD 998244353LL
#define seg_size 262144*2LL
#define pb push_back
#define ... |
One-Way Conveyors
You are working at a factory manufacturing many different products. Products have to be processed on a number of different machine tools. Machine shops with these machines are connected with conveyor lines to exchange unfinished products. Each unfinished product is transferred from a machine shop to ... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using PII = pair<ll, ll>;
#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
template<typename T> void chmin(T &a, const T &b) { a = min(a, b); }
template<typename T> void chmax(T &a... |
<!--
Problem C
-->
Balance Scale
You, an experimental chemist, have a balance scale and a kit of weights for measuring weights of powder chemicals.
For work efficiency, a single use of the balance scale should be enough for measurement of each amount. You can use any number of weights at a time, placing them eithe... | def main():
n,m = map(int,input().split())
if n*m == 0: return False
a = list(map(int, input().split()))
w = list(map(int,input().split()))
d = {0:1}
for i in w:
new_d = dict(d)
for j in d.keys():
new_d[j+i] = 1
new_d[abs(j-i)] = 1
new_d[i] = 1
... |
There has been marketing warfare among beverage vendors, and they have been working hard for in- crease of their sales. The Kola-Coqua Company is one of the most successful vendors among those: their impressive advertisements toward the world has brought the overwhelming market share of their representative product cal... | #include<iostream>
using namespace std;
#define N 100001
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n) REP(i,0,n)
int table[10][N];
int dp(int n,int m,int *coin,int lim){
rep(i,m+1){
if ( i%coin[0]==0)table[0][i]=i/coin[0];
else table[0][i]=lim+1;
}
REP(i,1,n){
rep(j,coin[i]){
i... |
Miki is a high school student. She has a part time job, so she cannot take enough sleep on weekdays. She wants to take good sleep on holidays, but she doesn't know the best length of sleeping time for her. She is now trying to figure that out with the following algorithm:
1. Begin with the numbers K, R and L.
2. She t... | #include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <queue>
#include <set>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <bitset>
#include <climits>
#define REP(i,n) for (int i=0;i<(n);i++)
#define FOR(i,a,b) for (in... |
Mr. Knight is a chief architect of the project to build a new art museum. One day, he was struggling to determine the design of the building. He believed that a brilliant art museum must have an artistic building, so he started to search for a good motif of his building. The art museum has one big theme: "nature and hu... | #include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
using namespace std;
const double EPS = 1e-8;
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<do... |
Ayimok is a wizard.
His daily task is to arrange magical tiles in a line, and then cast a magic spell.
Magical tiles and their arrangement follow the rules below:
* Each magical tile has the shape of a trapezoid with a height of 1.
* Some magical tiles may overlap with other magical tiles.
* Magical tiles are arrang... | #include<stdio.h>
#include<algorithm>
using namespace std;
int l1[110000];
int r1[110000];
int l2[110000];
int r2[110000];
int segtree[524288];
int dp[110000];
int query(int a,int b,int c,int d,int e){
if(d<a||b<c)return 0;
if(c<=a&&b<=d)return segtree[e];
return max(query(a,(a+b)/2,c,d,e*2),query((a+b)/2+1,b,c,d,e*... |
B: Periodic Sequence-
problem
Dr. Period, a professor at H University, is studying a property called the cycle that is supposed to be hidden in all things. As a generally known basic cycle, a cycle hidden in a sequence may be considered. That is, if the sequence S = S_1, S_2, ..., S_N of length N satisfies the follow... | #include <bits/stdc++.h>
using namespace std;
int main()
{
int N, S[200000];
scanf("%d", &N);
for(int i = 0; i < N; i++) {
scanf("%d", &S[i]);
}
for(int i = 1; i <= N; i++) {
if(N % i == 0) {
bool match = true;
for(int j = i; j < N; j += i) {
for(int k = 0; k < i; k++) match &=... |
You are given an integer $N$ and a string consisting of '+' and digits. You are asked to transform the string into a valid formula whose calculation result is smaller than or equal to $N$ by modifying some characters. Here, you replace one character with another character any number of times, and the converted string s... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll inf = 2e9;
int main() {
int n; cin >> n;
string s; cin >> s;
const int m = s.size();
vector<vector<vector<ll>>> val(m, vector<vector<ll>>(10, vector<ll>(11, inf)));
for(int i = 0; i < m; ++i) {
for(int len =... |
Problem
Kotatsu turtle is a turtle with a kotatsu shell.
As soon as Kotatsu was pokita (getting up), he was trapped in a stage divided into grid-like sections. There is only one exit on this stage. The parcel is either a road, a fence or a bomb, and the kotatsu can move up, down, left and right to enter the parcel o... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 1000000000
#define mod 1000000007
#define fi first
#define sc second
#define rep(i,x) for(int... |
For given two segments s1 and s2, print "1" if they are intersect, "0" otherwise.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
Input
The entire input looks like:
q (the number of queries)
1st query
2n... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
3
0 0 3 0 1 1 2 -1
0 0 3 0 3 1 3 -1
0 0 3 0 3 -2 5 0
output:
1
1
0
"""
import sys
EPS = 1e-9
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def check_ccw(p0, p1, p2):
a, b = ... |
For a given sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$, perform the following operations.
* count($b, e, k$): print the number of the specific values $k$ in $a_b, a_{b+1}, ..., a_{e-1}$.
Constraints
* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i, k_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 ... | #include<bits/stdc++.h>
using namespace std;
signed main(){
int n;
cin>>n;
vector<int> a(n);
for(auto& ai:a)cin>>ai;
int q;
cin>>q;
while(q--){
int l,r,k;
cin>>l>>r>>k;
cout<< count(a.begin()+l,a.begin()+r,k) <<endl;
}
}
|
Given this sequence
..
1^(1!)+2^(2!)+3^(3!)+4^(4!)+
..N^(N!).
Your job is to write a program such that given N any time, you have to find out the unit place digit of the sum of the above sequence.
Input
Enter the number N to calculate the unit place digit of the sum of the above sequence 1 < N < 1000. ... | def factorial(k):
if k > 4: k = 4 # specific code
P = 1
for i in xrange(1,k+1):
P *= i
return P
def process(N):
S = 0
for i in xrange(1, N + 1):
S += ((i % 10) ** factorial(i)) % 10
return S
def main():
while True:
N = raw_input()
if N == '#': break
... |
Reversed number is a number written in arabic numerals but the order of digits is reversed.
The first digit becomes last and vice versa. For example, if the number is 1245,it will become
5421 .Note that all the leading zeros are omitted. That means if the number ends with a zero,
the zero is lost by reversing (e.g.... | import sys
t=input()
while(t>0):
sumu=0
n, m = map(int, sys.stdin.readline().split(' '))
n=str(n)[::-1]
n=int(n)
m=str(m)[::-1]
m=int(m)
sumu=n+m
sumu=str(sumu)[::-1]
sumu=int(sumu)
print sumu
t=t-1 |
In a company an emplopyee is paid as under:
If his basic salary is less than Rs. 1500, then HRA = 10% of base salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the Employee's salary is input, write a program to find his gross sa... | #!/usr/bin/python
for i in range(input()):
basic=input()
if basic<1500:
gross=(basic+basic*0.1+basic*0.9)
else:
gross=(basic+500+basic*0.98)
print "%g" %gross |
The Little Elephant from the Zoo of Lviv likes listening to music.
There are N songs, numbered from 1 to N, in his MP3-player. The song i is described by a pair of integers Bi and Li - the band (represented as integer) that performed that song and the length of that song in seconds. The Little Elephant is going to list... | import operator
t = input()
for i in range(t):
table = {}
remaining_table = []
swtns1 = 0
swtns2 = 0
swtns = 0
count = 1
n = input()
for j in range(n):
b,l = map(int, raw_input().split())
if b in table:
if l < table[b]:
remaining_table.append(table[b])
table[b] = l
else:
remaining_table.ap... |
Polo, the Penguin, likes the XOR operation. Please read NOTE if you are not familiar with XOR operation.
XOR-sum of a list of numbers is the result of XOR-ing all of them. XOR-sum of (A[1] XOR A[2] XOR ... XOR A[N]) is defined as A[1] XOR (A[2] XOR (A[3] XOR ( ... XOR A[N]))).
He has an array A consisting of N integer... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import random
def count_bits(n):
res = 0
while n:
res += 1
n >>= 1
return res
t = int(raw_input())
for _ in range(t):
n = int(raw_input())
lst = map(int, raw_input().split())
#lst = [random.randint(0, (1 << 16) - 1) for i in range(... |
Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
on each path the next ... | t=input()
for i in range(t):
n=input()
prev_row=[]
first_element=input()
prev_row.append(first_element)
for j in range(1,n):
row=[int(k) for k in raw_input().split()]
for l in range(1,len(row)-1):
row[l]+=max(prev_row[l],prev_row[l-1])
row[len(row)-1]+= p... |
Alice and Bob decided to play one ultimate game. They have n piles, the i-th pile initially contain v_i chips. Alice selects a positive integer a from interval [1, m], and Bob selects a number b the same way.
Then the game starts. In her turn, Alice can select any pile containing at least a chips, and remove exactly ... | #include <bits/stdc++.h>
using namespace std;
long long arr[100005], ans[2];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%lld", arr + i);
}
for (int sum = 1; sum <= m << 1; sum++) {
vector<int> vec = {0};
for (int i = 0; i < n; i++) {
vec.push_back(arr[... |
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal s towards a faraway galaxy. Recently they've received a response t which they believe to be a response from aliens! The scientists now want to check if the signal t is similar to s.
The original signal s was a se... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long base = 73;
const int maxn = 1e6 + 10;
long long p[maxn];
int main() {
string s, t;
cin >> s >> t;
int cnt[2] = {0, 0};
int pr[2][s.length() + 1];
pr[0][0] = pr[1][0] = 0;
vector<int> v[2];
for (int i = 0; i < s.le... |
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... | import java.io.*;
import java.lang.*;
import java.util.*;
public class ProgC {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
... |
Mitya and Vasya are playing an interesting game. They have a rooted tree with n vertices, and the vertices are indexed from 1 to n. The root has index 1. Every other vertex i ≥ 2 has its parent p_i, and vertex i is called a child of vertex p_i.
There are some cookies in every vertex of the tree: there are x_i cookies ... | #include <bits/stdc++.h>
using namespace std;
int cc[100002];
pair<int, int> in[100002];
vector<pair<int, int> > adj[100002];
int pos = 1;
int l[100002], r[100002], label[100002];
long long d[100002];
void dfs(int node, int par, long long depth = 0) {
l[node] = pos;
d[node] = depth;
int ch, w;
for (pair<int, in... |
Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells n × m in size (containing n rows, m columns). Petya marked two different cells of the rectangle and now he is solving the following task:
Let's define a simple path between those two cells as a sequence of distinct cells a1, a2... | #include <bits/stdc++.h>
using namespace std;
bool good(int h, int w, int first, int second) {
if (first < 0 || second < 0) return false;
if (h > w) {
swap(h, w);
swap(first, second);
}
if (h == 1) return second >= w - 2;
return first != 0 || second != 0;
}
void f(int h, int w, int first, int second, ... |
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned ... | from math import gcd
def primes():
yield 2; yield 3; yield 5; yield 7;
bps = (p for p in primes()) # separate supply of "base" primes (b.p.)
p = next(bps) and next(bps) # discard 2, then get 3
q = p * p # 9 - square of next base prime to keep track o... |
Toad Pimple has an array of integers a_1, a_2, …, a_n.
We say that y is reachable from x if x<y and there exists an integer array p such that x = p_1 < p_2 < … < p_k=y, and a_{p_i} \& a_{p_{i+1}} > 0 for all integers i such that 1 ≤ i < k.
Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bi... | #include <bits/stdc++.h>
const long long mod1 = (long long)1e9 + 7;
const long long mod2 = (long long)1e9 + 9;
const long long BASE = 15879;
const long long inf = (long long)1e18;
const long double e = 2.718281828459;
const long double pi = 3.141592653;
const long double EPS = 1e-9;
using namespace std;
template <class... |
Vus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex.
He needs to remain not more than ⌈ (n+m)/(2) ⌉ edges. Let f_i be the degree of the i-th vertex after removing. He needs to ... | import sys
range = xrange
input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
U = []
coupl = [[] for _ in range(n)]
for _ in range(m):
u = inp[ii] - 1; ii += 1
v = inp[ii] - 1; ii += 1
U.append(u)
U.append(v)
coupl[u].append(2*_)
... |
You are given integers n, k. Let's consider the alphabet consisting of k different elements.
Let beauty f(s) of the string s be the number of indexes i, 1≤ i<|s|, for which prefix of s of length i equals to suffix of s of length i. For example, beauty of the string abacaba equals 2, as for i = 1, 3 prefix and suffix o... | #include <bits/stdc++.h>
using namespace std;
long long cc[400005], ans;
int u[400005], c, D[400005], n, i, j, cnt, x, y, d, is[400005], p[400005];
inline long long cal(int mx, int f1, int f2) {
long long res = 0;
for (int i = 2; i <= mx + mx; ++i)
res += cc[max(f2, i * f1 - n)] * min(i - 1, mx + mx + 1 - i);
... |
You are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
... | for _ in range(int(input())):
s=input()
s1=input()
s=set(s)
s1=set(s1)
if s1&s:
print('YES')
else:
print('NO') |
There are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 ≤ i ≤ n) will decid... | import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.*;
public class TaskE {
private static final String QUICK_ANSWER = "NO";
private final Scanner in;
private final StringBuilder out;
private final int n;
private final int p;
private fina... |
Daisy is a senior software engineer at RainyDay, LLC. She has just implemented three new features in their product: the first feature makes their product work, the second one makes their product fast, and the third one makes their product correct. The company encourages at least some testing of new features, so Daisy a... | #include <bits/stdc++.h>
using namespace std;
const int M = 264;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> need(n), test(n);
for (int i = 0; i < n; ++i) {
int a, b, c;
cin >> a >> b >> c;
need[i] = a + 2 * b + 4 * c;
}
for (int i = 0; i < n; ++i)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.