input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
One day Vasya was lying in bed watching his electronic clock to fall asleep quicker.
Vasya lives in a strange country, where days have h hours, and every hour has m minutes. Clock shows time in decimal number system, in format H:M, where the string H always has a fixed length equal to the number of digits in the decim... | #include <bits/stdc++.h>
using namespace std;
const int INF = 0x3fffffff;
const int SINF = 0x7fffffff;
const long long LINF = 0x3fffffffffffffff;
const long long SLINF = 0x7fffffffffffffff;
const int DIG = 11;
struct tT {
int h, m;
} beg, en;
int h, m, k;
void init();
void input();
void work();
long long getans(int h... |
Vasya has n different points A_1, A_2, … A_n on the plane. No three of them lie on the same line He wants to place them in some order A_{p_1}, A_{p_2}, …, A_{p_n}, where p_1, p_2, …, p_n — some permutation of integers from 1 to n.
After doing so, he will draw oriented polygonal line on these points, drawing oriented s... | #include <bits/stdc++.h>
using namespace std;
inline char gc() {
static char buf[100000], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2)
? EOF
: *p1++;
}
inline long long read() {
long long x = 0;
char ch = getchar();
bool positive... |
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A >... | #include <bits/stdc++.h>
const long long int INF = (long long int)1e9;
const double EPS = 0.000000000001;
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
long long int n, q;
cin >> n >> q;
deque<long long int> deq;
long long int max_n = -1;
for (long long int i = 0; i <... |
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers.
If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} ... | import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class q5 {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=Reader.nextInt();
int I= Reader.nex... |
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he wi... | n = map(int, input().split())
A = list(map(int, input().split()))
la = []
ind = 1
for a in A:
la.append((a, ind))
ind += 1
la.sort(key=lambda x: x[0], reverse=True)
# print(la)
x = 0
sm = 0
li = []
for tp in la:
a = tp[0]
sm += (a * x + 1)
x += 1
li.append(tp[1])
print(sm)
print(" ".join(str(i) for i in li)... |
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... | #include <bits/stdc++.h>
using namespace std;
struct FenwickTree {
FenwickTree() { this->n = 0; }
void init(int n) {
this->n = n;
a.clear();
a.insert(a.begin(), n + 3, 0);
}
FenwickTree(int n) { init(n); }
int query(int i) {
if (i == 0) {
return 0;
}
int res = 0;
while (i > 0... |
A team of three programmers is going to play a contest. The contest consists of n problems, numbered from 1 to n. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of... | #include <bits/stdc++.h>
using namespace std;
const int imax = 1e9 + 7;
const long long lmax = 1e18;
vector<int> v1, v2, v3, v, f;
int calc() {
int i, j, k1, k2, k3, ans = 0, start = 0, n;
v.clear();
cin >> k1 >> k2 >> k3;
n = k1 + k2 + k3;
v1.resize(k1);
v2.resize(k2);
v3.resize(k3);
for (i = 0; i < ((... |
You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a 2 × (2k + 1) rectangular grid. The alien has 4k + 1 distinct organs, numbered 1 to 4k + 1.
In healthy such aliens, the organs are arranged in a particular way. For exam... | #include <bits/stdc++.h>
using namespace std;
const int inf = (int)1.01e9;
const long long infll = (long long)1.01e18;
const long double eps = 1e-9;
const long double pi = acos((long double)-1);
mt19937 mrand(chrono::steady_clock::now().time_since_epoch().count());
int rnd(int x) { return mrand() % x; }
void precalc() ... |
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right.
You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1},... | def main():
from sys import stdin,stdout
ans = []
stdin.readline()
for ai in map(int, map(int, stdin.readline().split())):
cnt=1
while ans and ai*ans[-1][0]<=ans[-1][1]*cnt:
c, r = ans.pop()
ai+=r
cnt+=c
ans.append((cnt, ai))
for i, res in... |
You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black).
You have to solve the following problem for each vertex v: what is the maximum difference betwee... | //package codeforces.round627div3;
import java.io.*;
import java.util.*;
public class MaximumWhiteSubtree {
private static List<Integer>[] tree;
private static Integer[] color;
private static int[] subTreeMaxDiff;
private static int[] res;
public static void main(String[] args) {
// try {
/... |
You are given an undirected unweighted graph consisting of n vertices and m edges (which represents the map of Bertown) and the array of prices p of length m. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) a to the vertex (district) b... | import collections
tests = int(input())
def bfs(start, edges):
q = collections.deque([start])
dist = [-1]*(n+1)
dist[start] = 0
while(len(q) > 0):
curr_node = q.popleft()
for idx, neighbour in enumerate(edges[curr_node]):
if dist[neighbour] == -1:
q.append(n... |
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.
Each test case consists of an integer n and two arrays a and b, of size n. If after some (possibly zero) operations described below, array a can be transformed into array b, the ... | import java.io.*;
import java.util.*;
import java.math.*;
public class F {
public void realMain() throws Exception {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000);
String in = fin.readLine();
String[] ar = in.split(" ");
int T = Integer.parseInt(ar[0]);
for(int t = 0... |
You are given a tree (connected graph without cycles) consisting of n vertices. The tree is unrooted — it is just a connected undirected graph without cycles.
In one move, you can choose exactly k leaves (leaf is such a vertex that is connected to only one another vertex) connected to the same vertex and remove them w... | import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wr... |
There are n beautiful skyscrapers in New York, the height of the i-th one is h_i. Today some villains have set on fire first n - 1 of them, and now the only safety building is n-th skyscraper.
Let's call a jump from i-th skyscraper to j-th (i < j) discrete, if all skyscrapers between are strictly lower or higher than ... | #include <bits/stdc++.h>
using namespace std;
bool ispow(long long n) { return (n & (n - 1)) == 0; }
const int mod = 1e9 + 7;
int a[300005];
int dp[300005];
int s1[300005], s2[300005];
int cnt1 = 0, cnt2 = 0;
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n;... |
In the snake exhibition, there are n rooms (numbered 0 to n - 1) arranged in a circle, with a snake in each room. The rooms are connected by n conveyor belts, and the i-th conveyor belt connects the rooms i and (i+1) mod n. In the other words, rooms 0 and 1, 1 and 2, …, n-2 and n-1, n-1 and 0 are connected with conveyo... | import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class A {
void solve() {
int n = in.nextInt();
String s = in.nextLine();
boolean right = true;
boolean left = ... |
Hr0d1y has q queries on a binary string s of length n. A binary string is a string containing only characters '0' and '1'.
A query is described by a pair of integers l_i, r_i (1 ≤ l_i < r_i ≤ n).
For each query, he has to determine whether there exists a good subsequence in s that is equal to the substring s[l_i… r_... | # Problem: B. Non-Substring Subsequence
# Contest: Codeforces - Codeforces Round #685 (Div. 2)
# URL: https://codeforces.com/contest/1451/problem/B
# Memory Limit: 256 MB
# Time Limit: 1000 ms
#
# KAPOOR'S
from sys import stdin, stdout
def INI():
return int(stdin.readline())
def INL():
return [int(_) for _ in s... |
Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021.
For example, if:
* n=4041, then the number n can be represented as the s... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
public void solve(IO io) throws IOException {
long a = io.nextLong();
if (a % 2020L <= a / 2020L) {
io.println("YES");
} else {
io.pri... |
Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first ve... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-6;
const int MAXN = 2005;
const int MAXM = 5005;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const double FINF = 1e18;
long long dp[25][25][25][11][11];
int main() {
int n, t;
scanf("%d%d", &n,... |
You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once).
You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation canno... | k = int(input())
a = []
import math
def nhap():
r = input()
r = r.split()
r =[int(i) for i in r]
return r
def kq(a):
minn = min(a)
maxx = max(a)
b = sorted(a)
if(b == a): return 0
if(a[0]== maxx and a[-1]== minn): return 3
if(a[0]== minn or a[-1]== maxx): return 1
return 2
for i in range(k):
num = int(input... |
As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7, inf = 0x3f3f3f3f;
vector<int> g[maxn];
int vis[maxn], n, m, mod, cnt;
void dfs(int u, int fa) {
cnt++;
vis[u] = 1;
for (auto &v : g[u]) {
if (v == fa || vis[v]) continue;
dfs(v, u);
}
}
long long quick(long long x, long long n) {
... |
Fibonacci strings are defined as follows:
* f1 = «a»
* f2 = «b»
* fn = fn - 1 fn - 2, n > 2
Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba".
You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as... | #include <bits/stdc++.h>
#pragma GCC diagnostic ignored "-Wunused-const-variable"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wsign-compare"
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-7;
const int dx[4] = {1, -... |
Qwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen.
Y... | #include <bits/stdc++.h>
double xp, yp, vp, x, y, v, r, xpr, xpa;
int ok(double tim) {
double jd = tim * vp / xpr;
double xpnow = cos(xpa + jd) * xpr;
double ypnow = sin(xpa + jd) * xpr;
double dis1 = sqrt(x * x + y * y);
double hd1 = acos(r / dis1);
double dis2 = sqrt(xpnow * xpnow + ypnow * ypnow);
doub... |
A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([... | #include <bits/stdc++.h>
using namespace std;
bool visit[2010][2010] = {};
vector<long long> vec[100001];
long long a[100001] = {};
int main() {
ios::sync_with_stdio(false);
string s;
cin >> s;
stack<char> st;
stack<int> sst;
vector<long long> v[3];
long long n = s.size();
for (int i = 0; i < n; i++) {
... |
You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.
Let's consider all vertices of the graph, that are painted some color k. Let's denote a se... | #include <bits/stdc++.h>
using namespace std;
class graph {
int v;
list<int>* adj;
public:
graph(int x) {
this->v = x;
adj = new list<int>[v];
}
void add_edge(int a, int b) {
adj[a].push_back(b);
adj[b].push_back(a);
}
void count_colors(int a, int& n, int color[], int color_ar[]);
};
voi... |
There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top an... | #include <bits/stdc++.h>
using namespace std;
int n, m, t[100010], d[100010], tot, tmp;
long long ans;
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
void calc(int x) {
int i;
for (i = 1; i * i < x; i++)
if (x % i == 0) d[++tot] = i, d[++tot] = x / i;
if (i * i == x) d[++tot] = i;
}
int main() {
sc... |
Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game:
* The game consists of n steps.
* On the i-th step Greg removes vertex number xi from the grap... | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static StreamTokenizer in = new StreamTokenizer(System.in);
public static int ni() throws Exception {in.nextToken(); return (int)in.nval;}
public static void main(String[] args) throws Exception {
int n1 = ni();
... |
A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tub... | #include <bits/stdc++.h>
const int maxn = 301, maxe = 100001;
int n, lim, m, a[maxn], b[maxn], g[maxn], tot, len, path[maxn], cnt,
ans[maxn * maxn * 2][3];
bool vis[maxn];
struct Edge {
int nxt, v;
} e[maxe];
int min(int x, int y) { return x < y ? x : y; }
void dfs(int u) {
vis[u] = 1;
path[len++] = u;
if (... |
Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes v and u is the number of edges in the shortest path between v and u... | #include <bits/stdc++.h>
using namespace std;
vector<int> ADJ[1000000];
vector<int> adj[1000000];
int VIS[1000000];
int lvl[1000000];
int VISS[1000000];
int dis[100000];
bool DEL[1000000];
int P[1000000];
int dp[1000000][20];
int cur[1000000];
int n, m;
int tim = 1;
int sz[1000000];
int cnt = 0;
void DFFS(int v) {
VI... |
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int arr[100001], sum[100001] = {0}, z = 1;
for (int i = 0; i < n; i++) {
cin >> arr[i];
sum[i % k] += arr[i];
if (z < i % k) z = i % k;
}
int mx = 2e8;
int index;
for (int i = 0; i < k; i++) {
if (mx > su... |
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.
One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.
Vasya ha... | #!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
d = readln()
a, b = readln()
print(sum(d[a - 1:b - 1]))
|
Golorps are mysterious creatures who feed on variables. Golorp's name is a program in some programming language. Some scientists believe that this language is Befunge; golorps are tantalizingly silent.
Variables consumed by golorps can take values from 0 to 9, inclusive. For each golorp its daily diet is defined by it... | #include <bits/stdc++.h>
using namespace std;
inline string GetString() {
char GS[1000005];
scanf("%s", GS);
string ret = GS;
return ret;
}
inline char getc() {
char c = ' ';
while (c == ' ' || c == '\t' || c == '\r' || c == '\n') c = getchar();
return c;
}
string s;
vector<int> adj[10005];
vector<int> da... |
Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int a[100005], num[100005];
int family[100005];
double ans = 0;
struct node {
int le, ri;
int quan;
} edge[100005];
bool comp(node xx, node yy) { return xx.quan > yy.quan; }
int Find(int x) { return family[x] == x ? x : family[x] = Find(family[x]); }
int main(... |
Once Vasya needed to transport m goats and m wolves from riverbank to the other as quickly as possible. The boat can hold n animals and Vasya, in addition, he is permitted to put less than n animals in the boat. If in one place (on one of the banks or in the boat) the wolves happen to strictly outnumber the goats, then... | #include <bits/stdc++.h>
using namespace std;
struct S {
int a, b, c;
S(int a, int b, int c) : a(a), b(b), c(c) {}
S() {}
};
int m, n, cur;
int d[2][3][100035];
set<int> se[2][3];
queue<S> q;
bool aCunningPlan() { return m - cur + 1 <= n; }
int updVal;
void upd(int a, int b, int c) {
if (d[a][b][c] == -1) {
... |
You have a root tree containing n vertexes. Let's number the tree vertexes with integers from 1 to n. The tree root is in the vertex 1.
Each vertex (except fot the tree root) v has a direct ancestor pv. Also each vertex v has its integer value sv.
Your task is to perform following queries:
* P v u (u ≠ v). If u i... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &x) {
x = 0;
char c = getchar();
bool flag = false;
while (!isdigit(c)) {
if (c == '-') flag = true;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + (c ^ 48);
c = getchar();
}
if (flag)... |
Mr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" a... | #include <bits/stdc++.h>
using namespace std;
int main() {
string s, ss, cc;
cin >> s;
for (int i = 0; i <= s.length(); i++) {
for (char ch = 'a'; ch <= 'z'; ch++) {
ss = s;
cc = ch;
ss.insert(i, cc);
if (ss == string(ss.rbegin(), ss.rend())) {
cout << ss << endl;
retur... |
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | n = int(input())
s = input()
x = s.count('0')
y = s.count('1')
print(abs(x-y)) |
Motorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.
Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is... | #include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
long long ln, lk, lm;
int e, s;
vector<int> v[3];
long long dp[3][200105];
long long cal(int id, int f) {
int pos = lower_bound(v[id].begin(), v[id].end(), f) - v[id].begin();
return dp[id][p... |
Kevin Sun is ruminating on the origin of cows while standing at the origin of the Cartesian plane. He notices n lines <image> on the plane, each representable by an equation of the form ax + by = c. He also observes that no two lines are parallel and that no three lines pass through the same point.
For each triple (i,... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.BufferedInputStream;
import java.util.concurrent.Callable;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.... |
Catherine has a deck of n cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:
* take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color;
* take any two (not necessarily adj... | #include <bits/stdc++.h>
using namespace std;
enum { BC = 1, GC = 2, RC = 4 };
char dp[201][201][201];
static int f(int B, int G, int R) {
if (dp[B][G][R] != -1) return dp[B][G][R];
if (B == 1 && G == 0 && R == 0) return (dp[B][G][R] = BC);
if (B == 0 && G == 1 && R == 0) return (dp[B][G][R] = GC);
if (B == 0 &... |
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning V... | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
final long MOD = 1000L * 1000L * 1000L + 7;
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
void solve() throws IOException {
... |
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is cons... |
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
UF uf = new UF(n);
int root =-1;
int[] a = new int[n];
int ans =0;... |
The closing ceremony of Squanch Code Cup is held in the big hall with n × m seats, arranged in n rows, m seats in a row. Each seat has two coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m).
There are two queues of people waiting to enter the hall: k people are standing at (0, 0) and n·m - k people are standing at (0, m + 1).... | #include <bits/stdc++.h>
using namespace std;
inline int rd() {
int ans = 0, flag = 1;
char ch = getchar();
while ((ch > '9' || ch < '0') && ch != '-') ch = getchar();
if (ch == '-') flag = -1;
while (ch >= '0' && ch <= '9')
ans = (ans << 3) + (ans << 1) + ch - 48, ch = getchar();
return ans * flag;
}
c... |
Note that girls in Arpa’s land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs wer... | n=int(raw_input())
g=[[]for i in range(n+n)]
c=[-1 for i in range(n+n)]
e=[]
for i in range(n):
u,v=map(int,raw_input().split())
u-=1
v-=1
e.append([u,v])
g[u].append(v)
g[v].append(u)
for i in range(n):
g[2*i].append(2*i+1)
g[2*i+1].append(2*i)
q=[-1 for i in range(2*n)]
for i in range(... |
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and rep... | #include <bits/stdc++.h>
using namespace std;
bool letter[512] = {0};
char str[512];
int main() {
gets(str);
char temp = 'a';
int i;
for (i = 0; str[i] != 0; i++) {
if (str[i] == temp)
temp++;
else if (str[i] > temp)
break;
}
if (str[i] == 0 && temp <= 'z' + 1)
puts("YES");
else
... |
After some programming contest Roma decided to try himself in tourism. His home country Uzhlyandia is a Cartesian plane. He wants to walk along each of the Main Straight Lines in Uzhlyandia. It is known that each of these lines is a straight line parallel to one of the axes (i.e. it is described with the equation x = a... | #include <bits/stdc++.h>
using namespace std;
const int MX = 1e8;
int ask(int x, int y) {
cout << "0 " << x << " " << y << endl;
int resp;
cin >> resp;
return resp;
}
vector<int> ansX, ansY, ans;
int not0;
void dnc(int cl, int cr) {
if (cl > cr) return;
if (abs(cl) > MX || abs(cr) > MX) return;
int md = (... |
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | from math import ceil, sqrt
def array(arr, struc):
return (list(map(struc, arr.split())))
def isPrime(x):
for i in range(2, ceil(sqrt(x))+1):
if x % i == 0:
return False
return True
arr = array(input(), int)
prime1 = arr[0]
prime2 = arr[1]
counter = 0
tmp = prime1 + 1
while tmp ... |
<image>
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.
Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable t... | #include <bits/stdc++.h>
using namespace std;
const int mxN = 35001;
int A[mxN], dp[mxN][51], cnt[mxN];
int L = 1, R = 1, now = 1;
int Cost(int l, int r) {
while (R < r) {
now += !cnt[A[++R]];
++cnt[A[R]];
}
while (L < l) {
--cnt[A[L]];
now -= !cnt[A[L++]];
}
while (L > l) {
now += !cnt[A[... |
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he... | import java.util.*;
import java.io.*;
import java.math.*;
import java.util.regex.*;
public class C17b {
static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
static Reader fastInput = new Reader();
public static void main(String[] args) throws IOException {
int... |
Recently a tournament in k kinds of sports has begun in Berland. Vasya wants to make money on the bets.
The scheme of the tournament is very mysterious and not fully disclosed. Competitions are held back to back, each of them involves two sportsmen who have not left the tournament yet. Each match can be held in any of... | #include <bits/stdc++.h>
using namespace std;
int N, K;
struct Node {
int mx[10], mn[10];
int sz;
bool operator<(const Node &b) const {
for (int i = 0; i < K; i++) {
if (mn[i] < b.mx[i]) {
return true;
}
}
return false;
}
bool operator>(const Node &b) const {
for (int i = 0... |
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has... | class Character:
def __init__(self, hPoints, attPoints, healPoints):
self.hPoints = hPoints
self.attPoints = attPoints
self.healPoints = healPoints
def attack(self, boss):
boss.setHP(boss.getHP() - self.attPoints)
def recAttack(self, boss):
self.hPoints -= boss.getAP(... |
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence a_1, …, a_n. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence b_1, …, b_n using the following rules:
... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("no-stack-protector")
#pragma GCC target("sse,sse2,ssse3,sse3,sse4,popcnt,avx,mmx,abm,tune=native")
using namespace std;
namespace output {
void __(short x) { cout << x; }
void __(unsigned x) { cout << x; }
voi... |
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible num... | #include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const long long MOD = 1000000007LL, INF = 1e9, LINF = 1e18;
const long double PI = 3.141592653589793116, EPS = 1e-9,
... |
Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.
Their algorithm will be tested on an array of integers, where the i-th integer represents the color of the i-th pixel in the image. The image is in black and white, therefore ... | #include <bits/stdc++.h>
using namespace std;
int n, k;
int arr[100000];
int taken[256] = {-1};
int picked, cur;
signed main() {
cin >> n >> k;
for (int i = 0; i < 256; i++) taken[i] = -1;
for (int i = 0; i < n; i++) {
cin >> cur;
picked = cur;
for (int j = cur; j >= max(0, cur - k + 1); j--) {
... |
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this w... | #include <bits/stdc++.h>
long long mod = 1e9 + 7;
const int MAX = 1e5 + 5;
using namespace std;
long long get_binary(int n) {
long long binary = 0;
int remainder, i = 1, step = 1;
while (n != 0) {
remainder = n % 2;
n /= 2;
binary += remainder * i;
i *= 10;
}
return binary;
}
int main() {
io... |
Sheldon Cooper, Leonard Hofstadter and Penny decide to go for drinks at Cheese cake factory. Sheldon proposes to make a game out of this. Sheldon proposes as follows,
To decide the amount of beverage they plan to consume, say X.
Then order for a random number of different drinks, say {A, B, C, D, E, F} of quantities ... | import itertools
x=input()
y=raw_input().split(" ")
y=map(int,y)
z=input()
c=[]
for i in range(1,len(y)):
c.extend(itertools.combinations(y,i))
c=list(set(c))
con=0
for i in range(0,len(c)):
s=0
for j in range(0,len(c[i])):
s+=c[i][j]
if s==z:
print "True"
con=1
break
if con==0:
print "False" |
In Ninja World, World War is going on..
The Raikage Army and Zetsu Army are fighting each other. The war has become so fierce that, no one knows who will win. The ninjas of Leaf Village want to know who will survive finally. But leaf village ninjas are afraid of going to the battlefield.
So, they made a plan. They col... | from collections import defaultdict
class Graph():
def __init__(self, connections=[], directed=False):
self.status_dict = defaultdict(lambda : 1)
self.graph_dict = defaultdict(list)
self.is_directed = directed
def add_edge(self,node1, node2):
sel... |
You have been given an array A of size N consisting of positive integers. You need to find and print the product of all the number in this array Modulo 10^9+7.
Input Format:
The first line contains a single integer N denoting the size of the array. The next line contains N space separated integers denoting the eleme... | x=input()
s=raw_input()
i=0
d=1
cities=s.split()
for city in cities:
d=(d*int(city))%((10**9)+7)
i=i+1
if i==x:
break
print d |
We always knew they were coming back.
Species on Earth always had faced the problems came from outer space. We call them Alien , but for them they are travellers, who want to expand their territory.
When we had defeated them years back and sent them back to their World , still with a hope and with new advanced weapon... | t=int(raw_input().strip())
for i in range(0,t):
no=int(raw_input().strip())
points=[]
for j in range(0,no):
points.append(map(float,raw_input().strip().split(" ")))
x=[l[0] for l in points]
y=[k[1] for k in points]
x=sum(x)/len(points)
y=sum(y)/len(points)
print "(%.2f , %.2f)"%(round(x,2),round(y,2)) |
You are given a square matrix of size n. Rows are indexed 1 to n from top to
bottom and columns are indexed 1 to n
form left to right. Matrix consists of only '*' and '.'.
You need to check whether matrix is symmetric or not. if it is, check
it is symmetric about vertical axis or horizontal axis or both.
A matrix is ... | t = raw_input()
t = int(t)
for i in range(t):
n = raw_input()
n = int(n)
horizontal = []
vertical = []
for j in range(n):
s = raw_input()
horizontal.append(s)
vertical = map(lambda *row: ''.join(list(row)), *horizontal)
h = 1
v = 1
l=len(horizontal)
for i in range(l/2):
if(h==0 and v==0):
break
if(... |
Oliver and Bob are best friends. They have spent their entire childhood in the beautiful city of Byteland. The people of Byteland live happily along with the King.
The city has a unique architecture with total N houses. The King's Mansion is a very big and beautiful bungalow having address = 1. Rest of the houses in By... | # https://www.hackerearth.com/problem/algorithm/oliver-and-the-game-3/
import sys
n = int(sys.stdin.readline())
neighbors = [ [] for _ in range(n)]
for _ in range(n - 1):
u, v = [int(x) - 1 for x in sys.stdin.readline().split()]
neighbors[u].append(v)
neighbors[v].append(u)
vert = [[0, 0, 0] for _ in ra... |
Raju is the Class Representative of his class. His teacher assigned him a task to enroll the students' entries in the class register. He is given two information about each student: name and age. Now the teacher asked him to enroll entries according to the students' age (youngest being first) and then the students will... | import sys
t=int(raw_input())
while(t>0):
s=int(raw_input())
fd={}
while(s>0):
sd=sys.stdin.readline().strip('\n').split()
if(len(sd)!=0):
fd[int(sd[0])]=sd[1]
s=s-1
x = sorted(fd)
r=int(raw_input())
ss=x[r-1]
print fd[ss]
t=t-1 |
Find the number of ways of distributing N objects into R groups such that each group gets 1 or more objects.
Input:
The one and only line of input contains two numbers separated by a single space, which are N and R respectively.
Output:
The corresponding answer modulo 10000007 in a single line and if no answer exist... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
import math
n,m=map(int,raw_input().split())
if(n>=m):
n=n-1
m=m-1
a=math.factorial(n)
b=math.factorial(m)
c=math.factorial(n-m)
ans=a/(b*c)
print ans%10000007
else:
print -1 |
Once upon a time there was a girl who loved to garden. This girl liked to work in the garden to plant peas, weed watermelon, and grown all sorts of tasty and interesting fruits and vegetables. In fact, not only did this girl have a green thumb, her whole hand was green!
On the first day of fall, the girl went into her ... | fibs = {0: 0, 1: 1}
def fib(n):
if n in fibs: return fibs[n]
if n % 2 == 0:
fibs[n] = (((2 * fib((n / 2) - 1)) + fib(n / 2)) * fib(n / 2))%1000000007
return fibs[n]
else:
fibs[n] = ((fib((n - 1) / 2) ** 2) + (fib((n+1) / 2) ** 2))%1000000007
return fibs[n]
for _ in xrange(in... |
In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.
In Taknese, the plural form of a noun is spelled based on the following rules:
* If a noun's singular form does not end with `s`, append `s` to the end of the singular form.
* If a noun's singular form ends with `s`... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 入力
String s = sc.next();
int l=s.length();
if(s.charAt(l-1)=='s'){
System.out.println(s+"es");
}else{
System.out.p... |
Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.
An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to ... | #include <bits/stdc++.h>
using namespace std;
int main(){
int A,B,H,M;
cin >> A >> B >> H >> M;
double C=acos(-1)*(60*H+M)/360-acos(-1)*M/30;
double ans=sqrt(A*A+B*B-2*A*B*cos(C));
cout << fixed << setprecision(15) << ans << endl;
}
|
Given are N points (x_i, y_i) in a two-dimensional plane.
Find the minimum radius of a circle such that all the points are inside or on it.
Constraints
* 2 \leq N \leq 50
* 0 \leq x_i \leq 1000
* 0 \leq y_i \leq 1000
* The given N points are all different.
* The values in input are all integers.
Input
Input is giv... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
impo... |
There are N positive integers arranged in a circle.
Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:
* Choose an integer i such that 1 \leq i \leq N.
* Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStrea... |
The Patisserie AtCoder sells cakes with number-shaped candles. There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively. Each cake has an integer value called deliciousness, as follows:
* The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.
* The deliciousn... | from heapq import nlargest
x,y,z,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=list(map(int,input().split()))
ab=nlargest(k,(x+y for x in a for y in b))
abc=nlargest(k,(xy+z for xy in ab for z in c))
for i in abc:
print(i) |
In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.
City i is established in year Y_i and belongs to Prefecture P_i.
You can assume that there are no multiple cities that are established in the same year.
It is decided to allocate a 12-digit ID number to each ci... | import java.util.*;
import java.io.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.next());
int M = Integer.parseInt(sc.next());
int[][] p = new int[M][3];
for (int i = 0; i < M; i++) {
p[i][0] = i;
... |
In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).
A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is ... | s = input().count('o')
print(700 + s*100) |
2^N players competed in a tournament. Each player has a unique ID number from 1 through 2^N. When two players play a match, the player with the smaller ID always wins.
This tournament was a little special, in which losers are not eliminated to fully rank all the players.
We will call such a tournament that involves 2... | #include<bits/stdc++.h>
using namespace std;
int N, p[(1 << 18) + 10], aux[(1 << 18) + 10], l[(1 << 18) + 10], r[(1 << 18) + 10];
vector < int > prv[(1 << 18) + 10], nxt[(1 << 18) + 10], ev[(1 << 18) + 10];
void fail ()
{
printf ("NO\n");
exit (0);
}
void solve (int pos, int length)
{
if (length == 1)
... |
There is a directed graph G with N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i is directed from x_i to y_i. Here, x_i < y_i holds. Also, there are no multiple edges in G.
Consider selecting a subset of the set of the M edges in G, and removing these edges... | #include<bits/stdc++.h>
using namespace std;
int N, M, msk[15], dp[1 << 15], nrb[1 << 15];
bool ok[1 << 15];
const int mod = 1e9 + 7;
const int long long mod2 = 1LL * mod * mod;
void mul (int &x, int y) {x = (1LL * x * y) % mod;}
void adto (int &x, int y) {x += y; if (x >= mod) x -= mod;}
int main ()
{
//freopen ("i... |
Joisino is about to compete in the final round of a certain programming competition. In this contest, there are N problems, numbered 1 through N. Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).
Also, there are M kinds of drinks offered to the contestants, numbered 1 through M. If Joisino takes d... | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m,b=0;
cin>>n;
int t[n];
for(int i=0;i<n;i++) {cin>>t[i]; b+=t[i];}
cin>>m;
int p[m],x[m];
for(int i=0;i<m;i++) {cin>>p[i]>>x[i]; cout<<b-t[p[i]-1]+x[i]<<endl;}
return 0;
}
|
Let w be a string consisting of lowercase letters. We will call w beautiful if the following condition is satisfied:
* Each lowercase letter of the English alphabet occurs even number of times in w.
You are given the string w. Determine if w is beautiful.
Constraints
* 1 \leq |w| \leq 100
* w consists of lowercas... | #include <bits/stdc++.h>
using namespace std;
int main() {
string w; cin >> w;
int r = 0;
for (char c : w) r ^= c;
cout << (r ? "No" : "Yes") << endl;
}
|
Matrix of given integers
a1,1 a1,2 ... a1, n
a2,1 a2,2 ... a2, n
::
an, 1 an, 2 ... an, n
Then, create a program that outputs the maximum value of the sum of one or more consecutive terms (submatrix) in the vertical and horizontal directions and ends.
Input
The input data is given in the following format.
n
a... | n = int(input())
s = [[0 for i in range(n + 1)] for j in range(n + 1)]
for r in range(n):
inp = list(map(int, input().split()))
for c in range(n):
s[r + 1][c + 1] = inp[c] + s[r][c + 1]
ans = -10001
for r_end in range(1, n + 1):
for r_start in range(r_end):
dp = [-10001]
for c in ... |
Ninja Atsushi guards the town from the roof of the Ninja Building from early morning to late night every day. This Ninja Building is two adjacent buildings of the same floor, and Atsushi's daily routine is to jump between buildings and head to the rooftop for security.
Because these two buildings are cleaned frequentl... | #include<iostream>
#include<queue>
#include<map>
#include<cstring>
using namespace std;
typedef pair<int,int> P;
typedef pair<int,P> PP;
int bfs();
int n;
int bill[2][222];
bool flag[2][222];
int main(){
while(1){
memset(bill,0,sizeof(bill));
cin >> n;
if(n == 0) break;
for(int i=0;i<n;i++){
... |
You are now examining a unique method to sort a sequence of numbers in increasing order. The method only allows swapping of two numbers that have a common prime factor. For example, a sequence [6, 4, 2, 3, 7] can be sorted using the following steps.
Step 0: 6 4 2 3 7 (given sequence)
Step 1: 2 4 6 3 7 (elements 6 and 2... | #include <iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<math.h>
using namespace std;
typedef long long ll;
#define int long long
typedef vector<int> VI;
typedef pair<int, int> pii;
#define fore(i,a) for(auto &i:a)
#define REP(i,n) fo... |
In the Indian Puzzle, one is intended to fill out blanks with numbers and operators in a n by n grid in order to make equalities in the grid true (See Figure 1).
<image>
Figure 1
A blank cell should be filled out with a number (from 0 to 9 inclusive) or an operator (+, -, ×, ÷, =), and black cells split equaliti... | #include <bits/stdc++.h>
using namespace std;
#define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl
#define repi(i,a,b) for(int i=int(a);i<int(b);i++)
#define peri(i,a,b) for(int i=int(b);i-->int(a);)
#define rep(i,n) repi(i,0,n)
#define per(i,n) peri(i,0,n)
#define all(c) begin(c),end(c)
#define mp mak... |
We have a flat panel with two holes. Pins are nailed on its surface. From the back of the panel, a string comes out through one of the holes to the surface. The string is then laid on the surface in a form of a polygonal chain, and goes out to the panel's back through the other hole. Initially, the string does not touc... | #include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>... |
Peter is a senior manager of Agile Change Management (ACM) Inc., where each employee is a member of one or more task groups. Since ACM is agile, task groups are often reorganized and their members frequently change, so membership management is his constant headache.
Peter updates the membership information whenever an... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < int(n); ++i)
int solve(map<int, set<int>>& group, unsigned m) {
vector<char> vis(m, 0);
function<int(int)> dfs = [&](int k) {
if (vis[k]) return 0;
vis[k] = 1;
if (!group.count(k)) return 1;
int ... |
Problem
A mysterious dungeon is a dungeon that involves structural changes. There are various mysterious dungeons, from deep to shallow, where evil monsters live and treasures sleep. Jay is a researcher studying a mysterious dungeon. One day, when I was digging a new dungeon, it led to a very large and deep dungeon. J... | #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
int N,M;
vector<int> G[20002];
vector<int> rG[20002];
bool used[20002];
int cmp[20002];
vector<int> vs;
void init(int size){
vs.clear();
for(int i=0;i<size;i++) {
G[i].clear();
rG[i].clear();
cmp[i] = -1;
used[i] = 0;
}
}
voi... |
Princess, a Strategist
Princess is a strategist
English text is not available in this practice contest.
A brave princess in a poor country is on an adventure to escape the castle and obtain ancient treasures. However, the area around the ancient treasure is protected by multiple guardians and cannot be reached in th... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#define CLOCKWISE -1
#define ONLINE_BACK 2
#define ONLINE_FRONT -2
#define ON_SEGMENT 0
using namespace std;
class Point{
public:
do... |
A young boy John is playing with eight triangular panels. These panels are all regular triangles of the same size, each painted in a single color; John is forming various octahedra with them.
While he enjoys his playing, his father is wondering how many octahedra can be made of these panels since he is a pseudo-mathem... | #include<map>
#include<set>
#include<string>
#include<vector>
#include<iostream>
#include<algorithm>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef vector<int> vi;
void rotx(vi &v){
vi t=v;
v[0]=t[3]; v[1]=t[2]; v[2]=t[6]; v[3]=t[7];
v[4]=t[0]; v[5]=t[1]; v[6]=t[5]; v[7]=t[4];
}
void roty(vi... |
There is a directed graph consisting of N points. There is no cycle in this graph. Several stones are placed at each point. Two players play a game using this graph. Each turn comes alternately. In their turn, each player chooses vertex v and removes one or more stones placed on it. You can then freely change the numbe... | #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#includ... |
Magic Circle
Problem Statement
~ How to draw a magic circle ~
1. Prepare a sufficiently large and white floor.
2. Draw a circle with radii 1, 2, ..., R centered on the point at the floor coordinates (0,0).
3. Paint blue between the circle with radius 1 and the circle with radius 2, between the circle with radius 3 a... | #include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
#define Y imag()
typedef complex<d... |
Problem statement
2D, who is good at cooking, is trying to make lunch. Cooking requires all N ingredients a_ {0}, a_ {1},…, a_ {N−1}.
Now, 2D's refrigerator doesn't contain any ingredients, so I have to go to the supermarket to buy it. At the supermarket, you can buy the material a_ {i} for the price x_ {i} yen.
2D ... | inf = 10**9
par = [0]*5001
rank = [0]*5001
def init_union_find(V):
for i in xrange(V):
par[i] = i
rank[i] = 0
def find(x):
if par[x] == x: return x
else:
par[x] = find(par[x])
return par[x]
def unite(x,y):
x = find(x)
y = find(y)
if (x == y): return
... |
E: Without the Devil Old Maid --Unbalanced Old Maid -
story
Mr. Kosaka, Mr. Sonoda, and Mr. Minami have been good friends since childhood. The three went on a school trip to Okinawa, but a typhoon came and they couldn't play in the sea, so they decided to maid out.
Mr. Sonoda is strong in the game, but he is not goo... | #include <bits/stdc++.h>
using namespace std;
// #define int long long // <-----!!!!!!!!!!!!!!!!!!!
#define rep(i,n) for (int i=0;i<(n);i++)
#define rep2(i,a,b) for (int i=(a);i<(b);i++)
#define rrep(i,n) for (int i=(n)-1;i>=0;i--)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define ... |
problem
Prepare the Othello board. The upper left is $ (1,1) $ and the lower right is $ (8,8) $. The board to be prepared here is $ (5,4) as follows. ) There is no $ black stone.
........
........
........
... ox ...
.... o ...
........
........
........
Kuroishi: x Shiraishi: o
8x8 board
From this state, Black st... | #include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <algorithm>
#include <functional>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <complex>
#include <iomanip>
#include <bitse... |
B: Tetris
problem
Consider a board consisting of a rectangle with 4 squares x 10 squares. A square of 1 square x 1 square is called a block.
Tetromino is a combination of four blocks, and there are the following seven types (and those that have been rotated 90 degrees arbitrarily).
<image>
Now, consider the situat... | #include <algorithm>
#include <iostream>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); i++)
using namespace std;
struct Tetro {
int h, w;
vector<vector<char>> b;
Tetro(int h, int w, vector<vector<char>> &b) : h(h), w(w), b(b) {}
};
bool is_empty(char ch) { return ch == '.'; }
bool is_filled(char... |
For given $N$ points in the 2D Euclidean plane, find the distance of the shortest tour that meets the following criteria:
* Visit the points according to the following steps:
1. It starts from the leftmost point (starting point), goes strictly from left to right, and then visits the rightmost point (turn-around point)... | #include <bits/stdc++.h>
using namespace std;
int n;
double x[1111],y[1111],dp[1111][1111];
double calc(int a,int b){
return sqrt(pow((x[a]-x[b]),2)+pow((y[a]-y[b]),2));
}
double dfs(int l,int r,int i){
if(i==n)return max(calc(l,n-1),calc(r,n-1));
if(dp[l][r])return dp[l][r];
return dp[l][r]=min(dfs(i,r,i+1)... |
For given integer n, count the totatives of n, that is, the positive integers less than or equal to n that are relatively prime to n.
Input
n
An integer n (1 ≤ n ≤ 1000000000).
Output
The number of totatives in a line.
Examples
Input
6
Output
2
Input
1000000
Output
400000 | #include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>
#include <map>
#include <utility>
using namespace std;
int gcd(int a, int b){
if(a < b) swap(a,b);
if(a == 0 || b == 0) return max(a,b);
else return gcd(b, a % b);
}
int eulerPhi(int n){
if(n == 0) ret... |
Somewhere out there, there are N islands numbered from 1 to N with no network connectivity. Communication is such a pain for the islands' dwellers. So the Kings of the islands go to nearby islands and decide to connect the islands with underwater cables for bidirectional communication.
Initially no islands are connecte... | n,q=map(int,raw_input().split())
sz=[]
idi=range(n+1)#array containing the objects idi[i]=i
for i in range(n+1):
sz.append(1)
''' unite to trees by pointing one root of one to the other'''
def union(x,y):
rootx=root(long(x))
rooty=root(long(y))
if(rootx==rooty):
return
if(sz[rootx]< sz[rooty... |
Chefs from all over the globe gather each year for an international convention. Each chef represents some country. Please, note that more than one chef can represent a country.
Each of them presents their best dish to the audience. The audience then sends emails to a secret and secure mail server, with the subject bein... | from sys import stdin
b = stdin.readline().split()
no_chef=int(b[0])
no_mails=int(b[1])
d={}
chef={}
country={}
for i in range(0,no_chef):
b = stdin.readline().split()
d[b[0]]=b[1]
chef[b[0]]=0
country[b[1]]=0
chf=""
cntry=""
for i in range(0,no_mails):
s = stdin.readline().split()
#print ch... |
Pankaj likes to eat Ice cream when he is working late into the night. Today has been yet another long day for Pankaj. So, he wants to eat ice cream now. He opens the fridge and sees that he has 2 types of containers holding the ice cream.
The first container is a cone with radius r1 and height h1. There is also a hemis... | # your code goes here
from sys import stdin, stdout
from math import pi
t = int(stdin.readline())
while t:
t -= 1
r1, h1, r2, h2 = map(float, stdin.readline().strip().split(' '))
v2 = pi*r2*r2*h2
v1 = pi*r1*r1 *h1 /3
v1 += 2*pi*r1*r1*r1 /3
stdout.write("%.18f" % v1 + ' '+"%.18f"%v2 +'\n') |
You are given three integers A,B and C.
We choose two real numbers x and y such that 0 ≤ x ≤ A and 0 ≤ y ≤ B.
What is the probability that x+y≤C ?
Input
The first line of input contains T denoting the number of test cases.
Each of the following T lines contains three space separated Integers A,B and C
Output
For e... | t = int(input())
for i in range(t):
a,b,c = map(float, raw_input().split())
ans = 0.0
if(a==0 and b ==0):
ans = 1
elif (a==0 and b!=0):
if (c>=b):
ans = 1.0
else:
ans = c/b
elif (a!=0 and b==0):
if(c>=a):
ans = 1.0
else:... |
Recently Chef bought a bunch of robot-waiters. And now he needs to know how much to pay for the electricity that robots use for their work. All waiters serve food from the kitchen (which is in the point (0, 0)) and carry it to some table (which is in some point (x, y)) in a shortest way. But this is a beta version of r... | # Recently Chef bought a bunch of robot-waiters. And now he needs to know how much to pay for the electricity that robots use for their work. All waiters serve food from the kitchen (which is in the point (0, 0)) and carry it to some table (which is in some point (x, y)) in a shortest way. But this is a beta version of... |
Chef Jessie has a lot of recipes with her (N). She often remembered the starting few characters of the recipe and forgot the rest. As all the great chefs do, Jessie also numbered the recipes depending on the priority. So, given the list of recipes along with their priorities answer Jessie’s queries.
Jessie’s queries ar... | def twstr():
n=int(raw_input())
s=[]
v=[]
for i in range(n):
x=raw_input().split()
s.append(x[0])
v.append(int(x[1]))
qn=int(raw_input())
for i in range(qn):
q=raw_input().strip()
maxs='NO'
maxv=min(v)-1
for j in range(n):
if q==s[j][:len(q)] and v[j]>maxv:
maxv=v[j]
maxs=s[j]
print(max... |
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.
Elections are coming. You know the number of voters and the number of parties — n and m respectively. For each vote... | #include <bits/stdc++.h>
using namespace std;
const int N = 3333;
int n, m, p[N], c[N], r[N];
vector<int> v[N];
multiset<int> S;
int main() {
int i, j, k, x;
long long ans = 1e18, s;
cin >> n >> m;
for (i = 1; i <= n; i = i + 1)
cin >> p[i] >> c[i], r[p[i]]++, v[p[i]].push_back(c[i]);
for (i = 1; i <= m; ... |
You are given a tube which is reflective inside represented as two non-coinciding, but parallel to Ox lines. Each line has some special integer points — positions of sensors on sides of the tube.
You are going to emit a laser ray in the tube. To do so, you have to choose two integer points A and B on the first and the... | #include <bits/stdc++.h>
using namespace std;
int aa[100005], bb[100005];
int main() {
int n, y1;
scanf("%d %d", &n, &y1);
for (int i = 1; i <= n; i++) scanf("%d", aa + i);
int m, y2;
scanf("%d %d", &m, &y2);
for (int i = 1; i <= m; i++) scanf("%d", bb + i);
int ans = 2;
for (int k = 1; k < 30; k++) {
... |
This is an interactive problem.
In good old times dwarves tried to develop extrasensory abilities:
* Exactly n dwarves entered completely dark cave.
* Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves.
* Dwarves went out ... | #include <bits/stdc++.h>
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::string s1;
std::string s2, curs;
int n;
std::cin >> n;
if (n == 1) {
std::cout << "0 0" << std::endl;
std::cin >> s1;
std::cout << "0 1 1 1" << std::endl;
return 0;
}
int curx = 0, cury =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.