input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Vasya owns three strings s , a and b, each of them consists only of first k Latin letters.
Let a template be such a string of length k that each of the first k Latin letters appears in it exactly once (thus there are k! distinct templates). Application of template p to the string s is the replacement of each character... | #include <bits/stdc++.h>
using namespace std;
string a, b, ds, s, temp;
bool used[26];
bool fore, back, filled;
void fill_temp(char c, int b, int e) {
if (temp[c - 'a'] != '$') return;
for (int i = b; i <= e; ++i) {
if (!used[i]) {
temp[c - 'a'] = i + 'a';
used[i] = true;
return;
}
}
}
i... |
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.
There are n positive integers a_1, a_2, …, a_n on Bob's homework paper, where n is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 2 numbers. Suppose the n... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
long long a[n];
long long sum = 0;
for (int i = 0; i < (n); i++) {
cin >> a[i];
}
sort(a, a + n);
for (int i = 0; i < (n / 2); i++) {
sum += (a[i] ... |
You are given two arrays a and b, each contains n integers.
You want to create a new array c as follows: choose some real (i.e. not necessarily integer) number d, and then for every i ∈ [1, n] let c_i := d ⋅ a_i + b_i.
Your goal is to maximize the number of zeroes in array c. What is the largest possible answer, if y... | import sys, math
from sys import stdin, stdout
rem = 10 ** 9 + 7
inf = 10 ** 18
sys.setrecursionlimit(10 ** 6 + 7)
#from resource import *; setrlimit(RLIMIT_STACK, (RLIM_INFINITY, RLIM_INFINITY))
take = lambda: map(int, stdin.readline().split())
from heapq import heappush, heappop, heapify
from collections import dequ... |
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | x,y,z,w = (int(i) for i in input().split())
s = (x+y+z+w)//3
for i in x,y,z,w:
temp = s - i
if s - i > 0:
print(s-i, end=' ') |
You have an array a_1, a_2, ..., a_n.
Let's call some subarray a_l, a_{l + 1}, ... , a_r of this array a subpermutation if it contains all integers from 1 to r-l+1 exactly once. For example, array a = [2, 2, 1, 3, 2, 3, 1] contains 6 subarrays which are subpermutations: [a_2 ... a_3], [a_2 ... a_4], [a_3 ... a_3], [a... | #include <bits/stdc++.h>
using namespace std;
int a[300010], pre[300010], pos[300010];
int n;
int max_[1200010];
int f(int x, int y) {
if (a[x] > a[y]) return x;
return y;
}
void pushup(int rt) { max_[rt] = f(max_[rt << 1], max_[rt << 1 | 1]); }
void build(int l, int r, int rt) {
if (l == r) {
max_[rt] = l;
... |
There are n segments drawn on a plane; the i-th segment connects two points (x_{i, 1}, y_{i, 1}) and (x_{i, 2}, y_{i, 2}). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every i ∈ [1, n] either x_{i, 1} = x_{i, 2} or y_{i, 1} = y_{i, 2} (but only one of these conditions holds). Onl... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
long long n, m, a, b, c, k, x, y;
const int MAXN = 1e5 + 11, mod = 1e9 + 7;
long long max(long long a, long long b) { return ((a > b) ? a : b); }
long long min(long l... |
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.
You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.
... | import math
for _ in range(int(input())):
k=int(input())
l=list(map(int,input().split()))
k=sum(l)/k
print(math.ceil(k)) |
Vasya has a tree with n vertices numbered from 1 to n, and n - 1 edges numbered from 1 to n - 1. Initially each vertex contains a token with the number of the vertex written on it.
Vasya plays a game. He considers all edges of the tree by increasing of their indices. For every edge he acts as follows:
* If both end... | #include <bits/stdc++.h>
using namespace std;
int n, i, j, k, x, y;
vector<int> e[200005];
long long f[200005][4], pre[200005], nex[200005];
void DFS(int x, int p) {
int fi = 0, y, k;
for (int i = 0; i < e[x].size(); i++)
if (e[x][i] == p) {
fi = i;
break;
}
for (int i = 0; i < e[x].size(); i+... |
This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters one of the two ... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 205;
int n, ans[MAX];
char a[MAX];
int main() {
scanf("%d", &n);
scanf("%s", a + 1);
for (int i = 1; i <= n; i++) {
if (!ans[i]) ans[i] = 2;
for (int j = i + 1; j <= n; j++) {
if (a[i] > a[j]) {
if (ans[i] == ans[j]) {
p... |
A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.
There are m queens on a square n × n chessboard. You ... | import java.io.*;
import java.util.*;
public class E {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextIn... |
You have array of n numbers a_{1}, a_{2}, …, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | #include <bits/stdc++.h>
using namespace std;
void fast() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
bool isPrime(long long int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (long long int i = 5; i * i <= n; i = i + 6)
... |
You are given n strings a_1, a_2, …, a_n: all of them have the same length m. The strings consist of lowercase English letters.
Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that... | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
//class Declaration
static class pair implements Comparable<pair>{
int x;
int y;
... |
You are creating a level for a video game. The level consists of n rooms placed in a circle. The rooms are numbered 1 through n. Each room contains exactly one exit: completing the j-th room allows you to go the (j+1)-th room (and completing the n-th room allows you to go the 1-st room).
You are given the description ... | #include <bits/stdc++.h>
using namespace std;
const long long M = 998244353, N = 300005;
long long n, a[N];
long long ksm(long long x, long long y) {
long long ans = 1;
for (; y; y /= 2, x = x * x % M)
if (y & 1) (ans *= x) %= M;
return ans;
}
signed main() {
scanf("%lld", &n);
for (long long i = 1; i <= ... |
Polycarp plays a (yet another!) strategic computer game. In this game, he leads an army of mercenaries.
Polycarp wants to gather his army for a quest. There are n mercenaries for hire, and the army should consist of some subset of them.
The i-th mercenary can be chosen if the resulting number of chosen mercenaries is... | #include <bits/stdc++.h>
using namespace std;
const int Inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3fll;
const int jt = 998244353;
int n, m;
int jc[1 << 19], fjc[1 << 19];
int l[1 << 19], r[1 << 19];
int a[44], b[44];
int xf[1 << 19], cs[1 << 19][44];
int lgl[1 << 19];
int ksmii(int a, int b) {
if (!b) r... |
During one of the space missions, humans have found an evidence of previous life at one of the planets. They were lucky enough to find a book with birth and death years of each individual that had been living at this planet. What's interesting is that these years are in the range (1, 10^9)! Therefore, the planet was na... | #include <bits/stdc++.h>
using namespace std;
const int Mn = 1e5 + 5;
struct A {
long long a;
bool x;
} p[Mn << 1];
int cnt = 0;
bool cmp(A a, A b) {
if (a.a != b.a) return a.a < b.a;
return a.x < b.x;
}
int main() {
int n;
scanf("%d", &n);
long long x, y;
for (int i = 1; i <= n; i++) {
scanf("%lld%... |
Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.
To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that:
* p_i is divisible by x_i;
* x_i is not divisible by q_i.
... | """
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Pety... | import java.util.Scanner;
public class C_104C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
int count=0;
int sa4=0,sa7=0,sb7=0, sb4=0;
for (int i = 0; i < a.length(); i++) {
if(... |
Qingshan and Daniel are going to play a card game. But it will be so boring if only two persons play this. So they will make n robots in total to play this game automatically. Robots made by Qingshan belong to the team 1, and robots made by Daniel belong to the team 2. Robot i belongs to team t_i. Before the game start... | #include <bits/stdc++.h>
using namespace std;typedef long long ll;const int N=5000005;const int M=1000000007;int seed, base, t[N], a[N], b[N];ll s[2];
int rnd() {int ret = seed; seed = (1ll * seed * base + 233) % 1000000007;return ret;}
int main() {int n, m; scanf("%d%d", &n, &m);for (int i=1, p0=1, p, k; i<=m; i++) {s... |
There is a n × m grid. You are standing at cell (1, 1) and your goal is to finish at cell (n, m).
You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell (x, y). You can:
* move right to the cell (x, y + 1) — it costs x burles;
* move down to the cell (x + 1,... | import java.util.*;
public class TheCakeIsALie_B {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
int cost = (m-1) + (m*(n-1... |
AquaMoon had n strings of length m each. n is an odd number.
When AquaMoon was gone, Cirno tried to pair these n strings together. After making (n-1)/(2) pairs, she found out that there was exactly one string without the pair!
In her rage, she disrupted each pair of strings. For each pair, she selected some positions... | #include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <stack>
#include <list>
#include <cstring>
#include <map>
#include <cstdio>
#include <set>
#include <utility>
using namespace std;
#define ll long long
#define mem(f, z) memset(f, z, sizeof(f))
#define foi(i, x, y) for... |
Let's consider a k × k square, divided into unit squares. Please note that k ≥ 3 and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of t... | #include <bits/stdc++.h>
using namespace std;
const long long INF = (long long)1e18;
int n, m;
long long A[505][505];
long long cnt[505][505];
long long dp[2][505][505];
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) cin >> A[i][j];
for (int i = 0; i < n; i++)
for (int... |
Nick has some permutation consisting of p integers from 1 to n. A segment [l, r] (l ≤ r) is a set of elements pi satisfying l ≤ i ≤ r.
Nick calls a pair of segments [a0, a1] and [b0, b1] (1 ≤ a0 ≤ a1 < b0 ≤ b1 ≤ n) good if all their (a1 - a0 + b1 - b0 + 2) elements, when sorted in ascending order, form an arithmetic p... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
const int maxn = 300005;
const int mn = maxn << 2;
int getint() {
int r = 0, k = 1;
char c = getchar();
for (; '0' > c || c > '9'; c = getchar())
if (c == '-') k = -1;
for (; '0' <= c && c <= '9'; c = getchar()) r = r * 10 - '0' + c;
r... |
Byteland is trying to send a space mission onto the Bit-X planet. Their task is complicated by the fact that the orbit of the planet is regularly patrolled by Captain Bitonix, the leader of the space forces of Bit-X.
There are n stations around Bit-X numbered clockwise from 1 to n. The stations are evenly placed on a ... | #include <bits/stdc++.h>
using namespace std;
void Get(int &T) {
char C;
bool F = 0;
for (; C = getchar(), C < '0' || C > '9';)
if (C == '-') F = 1;
for (T = C - '0'; C = getchar(), C >= '0' && C <= '9'; T = T * 10 + C - '0')
;
F && (T = -T);
}
int N, M;
int Cnt[125];
void Init() {
Get(N);
Get(M);... |
Mirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters ... | #include <bits/stdc++.h>
int t[100005], f[100005], v[105];
int hl, hr, n;
bool used[105];
double first, last, unit, upd;
int trytry(int init) {
int x, up = init, pt = 0;
double loc = first;
memset(used, false, sizeof used);
while (loc < 100000) {
x = loc;
if (up) {
if (t[x] && !used[t[x]]) {
... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... |
n, t = map(int, input().split())
a = list(input())
for i in range(t):
j = 0
while j < n:
while j < n and a[j] == 'G':
j += 1
while j < n and a[j] == 'B':
j += 1
if j < n:
a[j - 1], a[j] = 'G', 'B'
j += 1
for i in a:
print(i, ... |
One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where ... | #include <bits/stdc++.h>
using namespace std;
int g[102];
int a[102];
int find(int i) {
if (i != g[i]) g[i] = find(g[i]);
return g[i];
}
int main() {
int n;
cin >> n;
for (int i = 0; i <= n; i++) g[i] = i;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) {
int d;
cin >> d;
... |
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi.... | import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
#sys.setrecursionlimit(10**7)
# OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
mod=10**9 + 7
"""
x_move=[-1,0,1,0,-1,1... |
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... | #include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 3;
int n, m, d, p[N], mx[N][2], us[N];
vector<vector<int> > v;
void up(int ind, int ch) {
if (mx[ind][0] <= ch) {
mx[ind][1] = mx[ind][0];
mx[ind][0] = ch;
} else if (mx[ind][1] < ch) {
mx[ind][1] = ch;
}
}
void dfs(int x) {
us[x] ... |
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j ... | #include <bits/stdc++.h>
using namespace std;
int q[10000][5];
int t[10000];
int m;
int main() {
int n;
cin >> n >> m;
for (int i = 0; i < m; i++) cin >> q[i][0] >> q[i][1] >> q[i][2] >> q[i][3];
for (int i = 1; i <= n; i++) {
t[i] = 1000000000;
int tot = 0;
for (int j = 0; j < m; j++) {
if (q... |
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 ≤ i ≤ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode f... | #include <bits/stdc++.h>
using namespace std;
const int oo = 0x3f3f3f3f;
const long long OO = 1LL << 61;
const int MOD = 1000000007;
long long dp[1005][20005];
int a[1005];
int main() {
int n;
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
memset(dp, 0, sizeof dp);
for... |
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera count... | from sys import exit
n, k = map(int, input().split())
nodes = [[] for _ in range(n+1)]
edges = []
for node, dist in enumerate(map(int, input().split())):
nodes[dist].append(node)
if len(nodes[0]) != 1 or len(nodes[1]) > k:
print(-1)
else:
for i in range(1, n):
if len(nodes[i])*(k-1) < len(nodes[... |
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the t... | import java.util.*;
import java.io.*;
public class D {
static int [] bits ;
static long [][][] memo ; // less , k , pos
static long dp(int less , int rem , int pos)
{
if(rem == 0)
return 1 ;
if(pos == bits.length)
return 0 ;
if(memo[less][rem][pos] != -1)
return memo[less][rem][pos] ; ... |
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | #include <bits/stdc++.h>
using namespace std;
long long int INF = 1e18 + 5;
long long int power(long long int a, long long int n) {
long long int res = 1;
if (n & 1) {
n--;
res *= a;
} else {
n /= 2;
a = a * a;
}
return res;
}
long long int gcd(long long int a, long long int b) {
if (b == 0)... |
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 main() {
long long n;
cin >> n;
long long k;
cin >> k;
long long ans = k * (6 * n - 1);
cout << ans << endl;
long long tmp = 0;
for (int i = 0; i < n; i++) {
cout << k * (tmp + 1) << " " << k * (tmp + 2) << " " << k * (tmp + 3) << " "
<< k *... |
The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const double PI = acos((long double)-1.0);
const int INF = 1 << 30;
const long long LINF = 1ll << 61;
const int BUFFER_SZ = 1 << 20;
const int MOD = 1000 * 1000 * 1000 + 7;
char BUFFER[BUFFER_SZ];
int gi() {
int x;
scanf("%d", &x);
return x;
}... |
Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the bo... | #include <bits/stdc++.h>
using namespace std;
class ST {
private:
int st[400013];
int size;
int left(int w) { return w << 1; }
int right(int w) { return (w << 1) + 1; }
int queryI(int w, int L, int R, int a, int b) {
if (a > R || b < L) return 2147483647;
if (L >= a && R <= b) return st[w];
int l... |
One winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of «TopShop», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention.
Actually, a vacuum cleaner was advertised ... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-8;
const double pi = acos(-1.0);
inline int sgn(double x) { return (x > eps) - (x < -eps); }
inline double sqr(double x) { return x * x; }
struct point {
double x, y;
point(double _x = 0, double _y = 0) { x = _x, y = _y; }
point operator-(const p... |
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
T... | import sys
n, x = map(int, sys.stdin.readline().split())
s = 0
for i in range(1, n + 1):
if (x % i == 0 and x / i <= n):
s += 1
print(s)
|
Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two a... | n,i,t,r=int(input()),0,0,[]
while 1:
i+=1
n-=i*i
if n<0:break
t+=i
m=n//t
r+=[(m+i,i),(i,m+i)][m==0:]*(m*t==n)
print(len(r))
for p in sorted(r):print("%d %d"%p) |
There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.
Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.
Split the row of the pearls to the maximal number of ... | import java.util.*;
import java.io.*;
public class cf{
public static void main(String args[])throws Exception{
Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n=sc.nextInt();
ArrayList<String> ans=new ArrayList<>();
HashMap<Long,Integer> indices=new HashMap<>();
for(int i=... |
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size n × m. There a... | #include <bits/stdc++.h>
using namespace std;
pair<int, int> mat[103][103];
int org[103][103];
int main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
int n, m, q;
cin >> n >> m >> q;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
mat[i][j] = make_pair(i, j);
}
}
for (int i = 1; ... |
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... | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main extends PrintWriter {
final Random rand = new Random(31);
final int inf = (int) 1e9;
final long linf = (long) 1e18;
final static String IO = "_std";
class Treap {
int x, y, sz;
Treap l, r;
... |
Zombies seem to have become much more intelligent lately – a few have somehow wandered into the base through the automatic gate. Heidi has had to beef up security, and a new gate has been installed. Unfortunately, now the questions being asked are more complicated, and even humans have trouble answering them. Can you s... | #include <bits/stdc++.h>
int main() {
printf(
"2 1\n2 3 1\n4 3 2 1\n1 3 4 2 5\n1 6 11 3 10 9 15 12 7 13 2 5 4 14 8\n5 "
"1 3 11 10 7 6 9 13 15 12 4 14 2 8\n9 7 2 5 1 10 8 3 4 6\n2 1 4 3\n4 12 "
"8 2 9 14 5 7 1 6 10 13 15 3 11\n11 5 6 8 10 12 7 2 1 4 9 3 13 14 15\n11 "
"7 8 4 5 15 13 14 3 9 12 ... |
ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edg... | #include <bits/stdc++.h>
using namespace std;
const int nmax = 1e3 + 10;
const int mmax = 1e4 + 10;
int n, m, length, node1, node2, inf;
pair<int, int> edge[mmax];
int weight[mmax];
vector<int> m_edges, r_edges;
vector<pair<int, int> > g[nmax];
priority_queue<pair<long long, int>, vector<pair<long long, 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... | #include <bits/stdc++.h>
using namespace std;
bool check_prime(int n) {
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
int check_ps(long long n) {
for (int i = n; i >= 2; i--) {
bool d = check_prime(i);
if (d) return i;
}
}
int check_div(long long n) {
int ans = 0;
... |
Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.
This problem is similar to a standard problem but it has a different format and constraints.
In the stand... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class BigMaximumSum {
public static int n, m;
public static class Node {
long ml, mr, m;
boolean rightAll;
long all;
public Node(long ml,long mr,long m,... |
Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.
The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 * 4 + 100;
vector<int> vec[maxn];
queue<int> q;
int n, c[maxn], fa[maxn], maxe;
bool check[maxn];
void bfs() {
check[1] = 1;
q.push(1);
while (!q.empty()) {
int cur = q.front();
q.pop();
int cnt = 0;
for (auto nei : vec[cur])
... |
You are given an array a consisting of positive integers and q queries to this array. There are two types of queries:
* 1 l r x — for each index i such that l ≤ i ≤ r set ai = x.
* 2 l r — find the minimum among such ai that l ≤ i ≤ r.
We decided that this problem is too easy. So the array a is given in a co... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.Collection;
import java.util.Random;
import java.io.Writer;
import java.io.Out... |
Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string s initially.
Evolution of the species is described as a sequence of changes i... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
int bit[4][12][12][N], n, m, id[307];
string a;
void add(int flag, int start, int gap, int pos, int val) {
while (pos <= n) bit[flag][start][gap][pos] += val, pos += pos & -pos;
}
int sum(int flag, int start, int gap, int pos) {
int res = 0;
whi... |
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.
We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class C {
static PrintWriter out = new PrintWriter(System.out);
static BufferedReader reader = new BufferedReader(new InputStreamR... |
Ivan is playing a strange game.
He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
1. Initially Ivan's scor... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
long double PI = 4 * atan(1);
int k, n, m, a[101][101], dp[101][101], ans[101], rom[101];
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> m >> k;
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < m + 1; j++) {
ci... |
Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.
... | a1 = '31 28 31 30 31 30 31 31 30 31 30 31 '
a2 = '31 29 31 30 31 30 31 31 30 31 30 31 '
s = a1 + a1 + a1 + a2 + a1 + a1
n = input()
ss = input().strip()
print(["NO",'YES'][ss in s]) |
A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.
In the constructing process m bidirectional ski r... | #include <bits/stdc++.h>
int nextInt() {
int x;
scanf("%d", &x);
return x;
}
double nextDouble() {
double x;
scanf("%lf", &x);
return x;
}
long long nextLong() {
long long x;
scanf("%I64d", &x);
return x;
}
char nextChar() {
char x;
scanf("%c", &x);
return x;
}
void newLine() { printf("\n"); }
l... |
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.
The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog... | R,C=map(int, input().split())
m=[[str(j) for j in input()] for i in range(R)]
row=0
for i in range(R):
if row == 1:
break
for j in range(C):
if m[i][j] == ".":
m[i][j] = "D"
elif m[i][j] == "S":
if j > 0 and m[i][j-1] == "W":
row=1
... |
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string s.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" <image>... | n=int(input())
a=input()
count1=0
for item in a:
if(item=='1'):
count1=count1+1
if(count1>=1):
print(1,end="")
for i in range(0,len(a)-count1):
print(0,end="") |
Allen is playing Number Clicker on his phone.
He starts with an integer u on the screen. Every second, he can press one of 3 buttons.
1. Turn u → u+1 \pmod{p}.
2. Turn u → u+p-1 \pmod{p}.
3. Turn u → u^{p-2} \pmod{p}.
Allen wants to press at most 200 buttons and end up with v on the screen. Help him!
Inp... | #include <bits/stdc++.h>
using namespace std;
using nagai = long long;
int u, v, p;
int mult(int a, int b) { return 1LL * a * b % p; }
int pw(int a, int b) {
int ans = 1;
while (b) {
if (b & 1) ans = mult(ans, a);
a = mult(a, a);
b >>= 1;
}
return ans;
}
int inv(int a) { return pw(a, p - 2); }
struc... |
Cat Noku recently picked up construction working as a hobby. He's currently working with a row of buildings and would like to make it beautiful.
There are n buildings in a row. The height of the i-th building is xi.
Cat Noku can modify the buildings by adding or removing floors to change the heights.
It costs him P d... | n,S,M,P=map(int, raw_input().split())
his=map(int, raw_input().split())
maxhi=max(his)
minhi=min(his)
earned={}
act=n-1
for i in xrange(minhi,maxhi+1):
earned[i]=(i-his[act])*M if his[act]>i else (his[act]-i)*P # all neg!
while act>0:
nextearn=earned
maxnext=max(nextearn.values())
earned={}
act-=1
for i in... |
There are 26 letters in the English alphabet and 6 of them are vowels: a,e,i,o,u,y.
Other 20 letters are called consonants.
Limak is a little polar bear.
He found a string s consisting of lowercase English letters.
He is going to read and pronounce s but it may be hard for him.
Some letters are harder to pronounce, so... | def hardness(s):
consective_consonants = 0
consective_condition = False
consonants, vowels = 0, 0
for c in s:
if c not in ['a', 'e', 'i', 'o', 'u', 'y']:
consonants += 1
consective_consonants += 1
if consective_consonants == 3:
consective_condi... |
Chinna and Chinnu has recently started developing a website for their startup from scratch. But they found it difficult to validate an Email field for their login forum. Help them build one.
An Email Address is of the form <username>@<hostname>
<username> consists of 1 - 16 characters inclusive and contains only sma... | t=input()
while t:
t-=1
e = raw_input()
yes = True
try:
u,h = e.split('@')
except:
print("NO")
continue
else:
if len(u) >16 or len(u) < 1:
yes = False
for x in u:
if not ((x >= 'a' and x <= 'z') or (x >= 'A' and x <= 'Z') or (x >= '0' and x <= '9') or x =='_'):
yes = False
h_a... |
"She loves me", "She loves me not", "She loves me", "She loves me not", OH WAIT, I'm LALA,
"They love me", "They love me not", "They love me", "They love me not". Lala was indeed overwhelmed by the
'runner's high' and the turbulence inside him. Heart-broken by one of his many lalis, he decided to code out his frustrati... | def f(x):
while x%2==0:
x /= 2
return x%4 == 3
for i in range(int(raw_input())):
if f(int(raw_input())):
print(1)
else:
print(0) |
Lucky numbers are those numbers which are greater than all numbers to its right side.You task is to count all lucky numbers in a given array.
RightMost Element is always lucky Number
INPUT First line contain number of test case T. Each test case contain number of elements N.Next line contains elements of array.
OUTPUT ... | import sys
for __ in range(input()) :
n = input()
lists = list(map(int,sys.stdin.readline().split()))
lucky = lists[-1]
ans = 1
for i in range(n-2,-1,-1) :
if lucky < lists[i] :
lucky = lists[i]
ans += 1
print ans |
Subly is a very naughty kid. His father gave a set of numbers to him. In the set no number is repeated and the set has N elements. He wanted Subly to keep that set safe. When his Father was busy watching a new season of his favourite TV series, Subly became bored. He started playing with the set of numbers that his fa... | test=input()
arr=[]
c=0
arr=raw_input().split()
if len(arr)==test:
print len(arr)-len(set(arr)) |
There are 'n' coins kept on the table, numbered from 0 to 'n-1'. Initially, each coin is kept tails up. You have to perform two types of operations :
1) Flip all coins numbered between A and B inclusive. This is represented by the command:
0
A
B
2) Answer how many coins numbered between A and B inclusive are heads up. ... | lst=[0]*input()
for i in range(input()):
a=int(raw_input())
b=int(raw_input())
c=int(raw_input())
c=c+1
if a==0:
for i in range(b,c):
if lst[i]==0:
lst[i]=1
else:
lst[i]=0
else:
count=0
for i in range(b,c):
if lst[i]==1:
count=count+1
print count |
WizKid went on a trip to Wonderland with his classmates. Now, as you know, going on trips incurs costs including hotel costs, fooding, shopping, etc. And when many people go together, usually one person pays and it is expected that the others will pay back their share. But, after a few days people lost track of who owe... | t=input('')
cnt=0
while int(t)>int(cnt):
d={}
n_person,q_transaction=raw_input('').split(' ')
tourist_name=[]
for i in range(int(n_person)):
tourist_name.append(str(raw_input('')))
d[tourist_name[i]]=[0,0]#expense,paid
for j in range(int(q_transaction)):
payee_name=str(raw_input(''))#who paid for transact... |
This is 1526 A.D. Third Battle of Panipat between Babur and Ibrahim Lodi, the current ruler of India is going on.
Realising that Lodi has much larger army, Babur planned to attack the cities of India to bring the moral of the soldiers of Lodi down.
Now, Lodi had been ordered by his ancestors that, if he is to rule I... | n=int(raw_input())
r=[True]*(n)
G=[[] for i in xrange(n)]
A=[-1]*(n)
B=[-1]*(n)
m=(10**9+7)
for i in xrange(n-1):
u,v=map(int,raw_input().split())
G[u].append(v)
r[v]=False
for i in xrange(0,n):
if r[i]==True:
root=i
def f(x):
#print x
p=1
t=0
if len(G[x])==0:
A[x]=1
... |
Today, teacher taught Xenny the chapter 'Prime numbers and Composite numbers'. Xenny liked it and being a studious boy, wanted some homework. So teacher gave him a simple task. The task is to find the smallest composite number greater than given no. Xenny was happy to get the simple task. But Xenny didn't get the time ... | def isprime(n):
for x in xrange(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
t=input()
while(t):
n=input()
flag=1
i=n+1
while(flag):
if not isprime(i):
print i
flag=0
... |
When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.
Constra... | import sys
s = input()
print(s[:3]) |
We have N integers A_1, A_2, ..., A_N.
There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?
Constraints
* All values in input are integers.
* 2 \leq N \leq 2 \times 1... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1LL<<61;
int main(){
ll n, k; cin >> n >> k;
vector<ll> A(n);
for(int i = 0; i < n; i++) cin >> A[i];
sort(A.begin(), A.end());
ll left = -INF, right = INF;
while(right - left > 1){
ll x = (right+left)/2;
ll s = 0, t... |
The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...
Given is a string S representing the weather in the town today. Predict the weather tomorrow.
Constraints
* S is `Sunny`, `Cloudy`, or `Rainy`.
Input
Input is given from Standard Input in the... | #include <iostream>
using namespace std;
int main()
{
string s, a="Sunny", b="Cloudy", c="Rainy";
cin>>s;
if(s==a)s=b;
else if(s==b)s=c;
else if(s==c)s=a;
cout<<s<<endl;
return 0;
} |
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices p... | #include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int>>> G;
vector<int> V;
vector<int> ans;
void dfs(int v, int dist) {
ans.at(v) = dist % 2;
for (auto g : G.at(v)) {
if (V.at(g.first)) continue;
V.at(v) = 1;
dfs(g.first, dist + g.second);
V.at(v) = 0;
}
}
int main() {
int... |
Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.
Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death. As he wants to live, he cannot eat one in su... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
int C = sc.nextInt();
if (A + B >= C - 1) {
System.out.println(B + C);
} else {
System.out.println(B + A + B + 1);
}
sc.clos... |
Takahashi and Aoki will play a game with a number line and some segments. Takahashi is standing on the number line and he is initially at coordinate 0. Aoki has N segments. The i-th segment is [L_i,R_i], that is, a segment consisting of points with coordinates between L_i and R_i (inclusive).
The game has N steps. The... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
int main()
{
int n;
cin >> n;
vector<int> x(n+1);
vector<int> y(n+1);
for(int i = 0; i < n; i++)
{
cin >> x[i] >> y[i];
}
sort(x.rbegin(), x.rend());
sort(y.begin(), y.end());
ll... |
There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of ... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 5003;
const ll MOD = 1e9+7;
ll fac[5010], fnv[5010];
ll D[5010][5010];
int ni[5010], sz[5010];
int n;
vector<int> lis[5010];
int idfs(int here, int p) {
sz[here] = 1;
for (int &there : lis[here]) {
if (there==p) con... |
There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i.
Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the ... | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MX = 100500;
int sz[MX];
vector<pair<int,int>> e[MX];
void dfs(int u, int pr){
sz[u] = 1;
for(int i = 0; i < e[u].size(); i++){
int v = e[u][i].first;
if(v == pr) continue;
dfs(v, u);
sz[u] += sz[v];
}
}
long long ans... |
There are N integers written on a blackboard. The i-th integer is A_i, and the greatest common divisor of these integers is 1.
Takahashi and Aoki will play a game using these integers. In this game, starting from Takahashi the two player alternately perform the following operation:
* Select one integer on the blackbo... | #include <bits/stdc++.h>
using namespace std;
int T,n,m,k,q,a[100010];
int gcd(int x,int y){
return y?gcd(y,x%y):x;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
int cur=0,o_cnt,e_cnt,pos;
bool flag;
while(true){
o_cnt=e_cnt=flag=0,pos=-1;
for(int i=1;i<=n;i++){
if(a[i]%2==0) o_cnt... |
There is a long blackboard with 2 rows and N columns in a classroom of Kyoto University. This blackboard is so long that it is impossible to tell which cells are already used and which unused.
Recently, a blackboard retrieval device was installed at the classroom. To use this device, you type a search query that forms... | #include<iostream>
#include<vector>
#include<iomanip>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
using ulong = unsigned long;
using ll = long long;
const int M = 1e9 + 7;
#pragma unused(M)
int main(){
int n;
cin >> n;
string s1, s2;
char q... |
There is a plan view consisting of 12 vertical and 12 horizontal squares showing the terrain. Each square is painted white or black. White represents the sea and black represents the land. When two black squares touch each other vertically or horizontally, they are said to be continuous. In this plan view, the area cre... | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
void dfs(vector<string>& m,int i,int j){
int di[]={1,0,-1,0};
int dj[]={0,1,0,-1};
for(int k=0;k<4;++k){
int ni=i+di[k];
int nj=j+dj[k];
if(ni<0||ni>=12||nj<0||nj>=12)continue;
if(m[ni][nj]=='1'){
... |
The neutral city of Eyes City, in the heart of the four countries, is home to the transcontinental train Bandai. The platform has a row of chairs for passengers waiting for the Bandai, and people who enter the platform can use the chairs freely.
The Bandai is cheap, fast and comfortable, so there are a constant number... | #include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
char s[200], a[2];
int main() {
bool b;
int n, m;
while (scanf("%d%d", &n, &m), n) {
memset(s, 0, sizeof(s)); rep(i, n)s[i] = '#';
rep(i, m) {
scanf("%s", a);
switch (a[0]) {
case 'A':
rep(i, n) { if (s[i] == '#') { s... |
You are now in a bookshop with your friend Alice to buy a book, "The Winning Strategy for the Programming Koshien Contest,” just released today. As you definitely want to buy it, you are planning to borrow some money from Alice in case the amount you have falls short of the price. If the amount you receive from Alice s... | m,a,b=map(int,input().split())
if m>=b:
print(0)
elif m+a<b:
print("NA")
else:
print(b-m)
|
The JOI Railways is the only railway company in the Kingdom of JOI. There are $N$ stations numbered from $1$ to $N$ along a railway. Currently, two kinds of trains are operated; one is express and the other one is local.
A local train stops at every station. For each $i$ ($1 \leq i < N$), by a local train, it takes $A... | #include <bits/stdc++.h>
using namespace std;
typedef long long int64;
int main()
{
int64 N, M, K, A, B, C, T, S[3001];
cin >> N >> M >> K;
cin >> A >> B >> C;
cin >> T;
for(int i = 0; i < M; i++) cin >> S[i];
S[M] = N + 1;
K -= M;
int64 ret = -1;
priority_queue< int64, vector< int64 >, greater<... |
You are given N points in the xy-plane. You have a circle of radius one and move it on the xy-plane, so as to enclose as many of the points as possible. Find how many points can be simultaneously enclosed at the maximum. A point is considered enclosed by a circle when it is inside or on the circle.
<image>
Fig 1. Cir... | #include<bits/stdc++.h>
using namespace std;
#define reps(i,f,n) for(int i=f;i<int(n);i++)
#define rep(i,n) reps(i,0,n)
typedef complex<double> P;
vector<P> point;
const double EPS = 0.0000000001;
void init(){
point.clear();
}
bool input(){
int n;
cin>>n;
if(n==0)return false;
rep(i,n){
double ... |
Isaac is tired of his daily trip to his ofice, using the same shortest route everyday. Although this saves his time, he must see the same scenery again and again. He cannot stand such a boring commutation any more.
One day, he decided to improve the situation. He would change his route everyday at least slightly. His ... | import java.util.Arrays;
import java.util.BitSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class Main {
Scanner sc;
Main() {
sc = new Scanner(System.in);
}
int n, m, k, a, b,
c[][] = new int[50][50];
void run() {
for (;;) {
n = sc.nextInt();
m ... |
Halting Problem
A unique law is enforced in the Republic of Finite Loop. Under the law, programs that never halt are regarded as viruses. Releasing such a program is a cybercrime. So, you want to make sure that your software products always halt under their normal use.
It is widely known that there exists no algorith... | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair < int , int > pii;
typedef pair < LL , int > pli;
typedef pair < int , LL > pil;
typedef pair < LL , LL > pll;
#define mpr make_pair
#define FS first
#define SC second
#define PB push_back
template < typename T > T MAX(T a,T b){return (a>b... |
For Programming Excellence
A countless number of skills are required to be an excellent programmer. Different skills have different importance degrees, and the total programming competence is measured by the sum of products of levels and importance degrees of his/her skills.
In this summer season, you are planning to... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef int _loop_int;
#define REP(i,n) for(_loop_int i=0;i<(_loop_int)(n);++i)
#define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i)
#define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1;i>=(_loop_int)(a);--i)
#define CHMIN(a,b) a... |
Andrew R. Klein resides in the city of Yanwoe, and goes to his working place in this city every weekday. He has been totally annoyed with the road traffic of this city. All the roads in this city are one-way, so he has to drive a longer way than he thinks he need.
One day, the following thought has come up to Andrew’s... | #include<bits/stdc++.h>
#define MAX 1005
#define INF 123456789
using namespace std;
struct edge{int to;int cost;};
typedef pair<int,int> P;
int V;
vector<edge> G[MAX];
int d[MAX];
void dkstr(int s){
priority_queue<P,vector<P>,greater<P> >que;
fill(d,d+V,INF);
d[s]=0;
que.push(P(0,s));
while(!que.empty()){
... |
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to develop physical strength and judgment by running on a straight road. The rabbit is now standing at the starting line and looking out over a long, long road.
There... | #include<bits/stdc++.h>
#define range(i,a,b) for(int i = (a); i < (b); i++)
#define rep(i,b) for(int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define show(x) cerr << #x << " = " << (x) << endl;
using namespace std;
const double EPS = 1e-9;
int main(){
int n;
double k, t, u, v, l;
cin >>... |
In the year 20XX, mankind is hit by an unprecedented crisis. The power balance between the sun and the moon was broken by the total eclipse of the sun, and the end is looming! To save the world, the secret society called "Sun and Moon" decided to perform the ritual to balance the power of the sun and the moon called "R... | #include<map>
#include<cmath>
#include<cstdio>
#include<vector>
#include<algorithm>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){ return b?gcd(b,a%b):a; }
ll fast_modmul(ll a,ll b,ll m){
return (((a*(b>>20)%m)<<20)+a*(b&((1<<20)-1)))%m;
}
ll fast_modpow(ll ... |
Nathan O. Davis has been running an electronic bulletin board system named JAG-channel. He is now having hard time to add a new feature there --- threaded view.
Like many other bulletin board systems, JAG-channel is thread-based. Here a thread (also called a topic) refers to a single conversation with a collection of ... | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <utility>
#define REP(i,a,b) for(int i=int(a);i<int(b);i++)
using namespace std;
typedef long long int lli;
typedef pair<string, int> psi;
void print(vector<vector<psi>> &sl, int fst = 0, int depth = 0) {
REP (i, 0, sl[fst].si... |
Problem statement
Cards with ranks of $ 2 $ and $ 8 $ are powerful in card game millionaires. Therefore, we call an integer consisting of only the numbers $ 2 $ and $ 8 $ in $ 10 $ decimal notation a good integer. The best integers are listed from the smallest to $ 2, 8, 22, 28, 82, 88, \ cdots $.
Let $ n $ be a posi... | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const ll INF = 1LL << 28;
ll N;
vector<ll> num;
map<ll,ll> memo;
queue<ll> q;
function<ll(ll)> seki;
int main() {
cin >> N;
q.push(2LL); q.push(8LL);
while (q.size()) {
ll n = q.front(); q.pop();
num.push_back(n);
... |
Santa is going to pack gifts into a bag for a family. There are $N$ kinds of gifts. The size and the price of the $i$-th gift ($1 \leq i \leq N$) are $s_i$ and $p_i$, respectively. The size of the bag is $C$, thus Santa can pack gifts so that the total size of the gifts does not exceed $C$. Children are unhappy if they... | #include<bits/stdc++.h>
using namespace std;
#define INF (1<<28)
#define DEKAI 1000000007
#define FDST int hogehoge;cin>>hogehoge;
int main(){
int c,n,m;
int gv[10000],gs[10000];
int a[10001];
int ans[10001];
cin>>c>>n>>m;
for(int i=0;i<n;i++){
cin>>gs[i]>>gv[i];
}
for(int i=0;i<c+1;i++){
a[... |
Problem
If you bring an empty bottle of $ a $ milk, you can exchange it for a new bottle of $ b $ milk.
How many bottles of milk can Mr. Kawabayashi, who initially has a bottle of $ x $ milk, drink? Output the remainder after dividing by $ 1000000007 $.
Constraints
The input satisfies the following conditions.
* $ ... | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<math.h>
#include<string>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<stdlib.h>
#include<iomanip>
using namespace std;
#define ll long long
#d... |
For given three points p1, p2, p, find the reflection point x of p onto p1p2.
<image>
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xi, yi ≤ 10000
* p1 and p2 are not identical.
Input
xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq−1 ypq−1
In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv... | #include <iostream>
#include <complex>
#include <cstdio>
using namespace std;
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
#define FOR(i,a,b) for(int i = (a); i < (int)(b); ++i)
#define ALL(c) (c).begin(), (c).end()
#define SIZE(v) ((int)v.size())
typedef complex<double> P;
// ??????
double dot(const P& a, co... |
For $n$ lists $L_i$ $(i = 0, 1, ..., n-1)$, perform a sequence of the following operations.
* insert($t$, $x$): Insert an integer $x$ at the end of $L_t$.
* dump($t$): Print all elements in $L_t$.
* splice($s$, $t$): Transfer elements of $L_s$ to the end of $L_t$. $L_s$ becomes empty.
In the initial state, $L_i$ $(... | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
list<int>st[1000];
list<int>::iterator it;
int n,tc,q,t,s;
ll x;
cin>>n>>tc;
while(tc--)
{
cin>>q;
if(q==0)
{
cin>>t>>x;
st[t].push_back(x);
}
else if(q==1)
{
cin>>t;
for(it=s... |
N Soldiers are lined up for a memory test. They are numbered from 0 to N-1 from left to right.
In the test, there are M rounds. In each round, Captain selects one position. Soldier at that position will be numbered 0. All the soldiers to the right of selected position will be numbered one greater than the soldier to ... | T = input()
for _ in range(T):
n,m = map(int,raw_input().split())
arr = map(int,raw_input().split())
s = min(arr)
l = max(arr)
for i in range(n):
if abs(i-s)>abs(i-l):
print abs(i-s),
else:
print abs(i-l), |
Once upon a time chef decided to learn encodings. And, obviously, he started with the easiest one (well, actually the easiest after Caesar cypher) – substitution cypher.
But very soon Chef got bored with encoding/decoding, so he started thinking how to hack this cypher.
He already knows some algorithm, which is not alw... | def cmp(tup):
return (tup[1], tup[0])
def get_decoder(text,freqseq):
mymap = {}
for ch in text:
if ch.isalpha():
if ch.lower() in mymap:
mymap[ch.lower()] += 1
else:
mymap[ch.lower()] = 1
v = []
for k in mymap:
v.append((k,mymap[k]))
v = sorted(v,key=cmp)
length = len(v)
lastcut = freqse... |
Did you know that Chwee kueh, a cuisine of Singapore, means water rice cake ? Its a variety of the most popular South Indian savory cake, only that we call it here idli :). The tastiest idlis are made in Chennai, by none other than our famous chef, Dexter Murugan. Being very popular, he is flown from Marina to Miami, t... | # your code goes here
# your code goes here
import math
A=[]
t=int(raw_input())
for u in range(0,t):
size=int(raw_input())
A=map(int,raw_input().split())
idli=[0]*(size+1)
count=0
for k in A:
idli[k]+=1
count =count+k
if(count%size!=0):
print("-1")
else:
i=0
j=size
count=0
while i<j:
while idli[... |
Clash of clans is a very popular game. Each player in the game is allocated a base with certain hit points the player can train a limited number of troops on the base. There are three types of troops: Barbarian, Archers and Giants. The Cost of training a Barbarian is 100, an Archer is 500, and a Giant is 1500. When att... | # cook your code here
def hitpoint(a,n,t):
i=0
h=0
while(i<n):
if(a[i]==1):
h+=t*1
elif(a[i]==2):
h+=t*2
else:
h+=t*3
i+=1
return h
#input size of army
n=int(raw_input())
#input the time in mins
t=int(raw_input())
#convertion to sec
t=... |
You are given a weighted graph with N nodes and M edges. Some of the nodes are marked as special nodes. Your task is to find the shortest pairwise distance between any two different special nodes.
Input
The first line of the input contains three space-separated integers N, M and K denoting the number of nodes, the n... | INFINITY = 10**9+7
from heapq import *
def dijkstra(s):
global mini
q, seen = [(0, s)], set()
while q:
cost, v1 = heappop(q)
if v1 not in seen:
seen.add(v1)
if cost > mini:
break
if specials[v1] == 1:
if v1 != s:
mini = cost
break
for c, v2 in g[v1]:
if v2 not in seen:
heap... |
Problem description:
There are students in a class fighting for a girl. As she came to know she decided that the boy will win who will help her find out specific characters present in a given string is present either "even" or "odd" number of times as asked by her. So help the boys win.
Input
Input description.
Fir... | testcase = input()
for i in range(0, testcase):
n, q = map(int, raw_input().split())
s = raw_input()
for j in range(0, q):
c, t = raw_input().split()
if(t == "even"):
if(s.count(c)%2 == 0):
print "yes"
else:
print "no"
else:
if(s.count(c)%2 == 1):
print "yes"
else:
print "no" |
In this problem you will have to help Berland army with organizing their command delivery system.
There are n officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer a is the direct superior of officer... | #include <bits/stdc++.h>
using namespace std;
int ans = 1;
vector<int> son[200010];
int start[200010];
int eend[200010];
int place[200010];
void dfs(int num) {
place[ans] = num;
start[num] = ans++;
for (int i = 0; i < son[num].size(); i++) {
dfs(son[num][i]);
}
eend[num] = ans;
}
int main() {
int num_so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.