input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
For given n points in metric space, find the distance of the closest points.
Constraints
* 2 ≤ n ≤ 100,000
* -100 ≤ x, y ≤ 100
Input
n
x0 y0
x1 y1
:
xn-1 yn-1
The first integer n is the number of points.
In the following n lines, the coordinate of the i-th point is given by two real numbers xi and yi. Each valu... |
#include <bits/stdc++.h>
#define PB push_back
#define PF push_front
#define MP make_pair
#define FI first
#define SE second
#define SIZE( A ) int( ( A ).size( ) )
#define ALL( A ) ( A ).begin( ), ( A ).end( )
#define ALLR( A ) ( A ).rbegin( ), ( A ).rend( )
using n... |
For given an integer $n$, print all permutations of $\\{1, 2, ..., n\\}$ in lexicographic order.
Constraints
* $1 \leq n \leq 9$
Input
An integer $n$ is given in a line.
Output
Print each permutation in a line in order. Separate adjacency elements by a space character.
Examples
Input
2
Output
1 2
2 1
Inpu... | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
int A[n];
for (int i = 0; i < n; i++) {
A[i] = i + 1;
}
do {
for (int i = 0; i < n; i++) {
if (i == 0) cout << A[i];
else cout << " " << A[i];
}
cout << endl;
} whil... |
Problem description
You will be given a zero-indexed array A. You need to rearrange its elements in such a way that the following conditions are satisfied:
A[i] ≤ A[i+1] if i is even.
A[i] ≥ A[i+1] if i is odd.
In other words the following inequality should hold: A[0] ≤ A[1] ≥ A[2] ≤ A[3] ≥ A[4], and so on. Operation... | import math
t=input()
while t>0:
n=input()
a=[]
for x in raw_input().split():
a.append(int(x))
a.sort()
n=int(math.ceil(n/2.0))
res=a[n:]
a=a[:n]
count=1
for x in res:
a.insert(count,x)
count+=2
for x in a:
print x,
print ''
t-=1 |
Chef plays with the sequence of N numbers. During a single move Chef is able to choose a non-decreasing subsequence of the sequence and to remove it from the sequence. Help him to remove all the numbers in the minimal number of moves.
Input
The first line of each test case contains a single N denoting the number of i... | def index(lis,l,r,k):
while(r-l>1):
m=l+(r-l)/2;
if(lis[m]>=k):
r=m
else:
l=m
return r
def count(lis,n):
t=[]
len1=1
t+=[lis[0]]
i=1
while i<n:
if(lis[i]<t[0]):
t[0]=lis[i]
elif(lis[i]>t[len1-1]):
... |
Least Distance
Mr. John has a habit of implementing new programming methods. This time he needs your help to solve a problem. He needs a method such that it accepts a series of numbers (all in single digits) and returns a typical answer. The answer must be the least distance between any two ADJACENT numbers.
For Exam... | import sys
L = map(int,sys.stdin.readline().split())
min = 10
for i in range(len(L)) :
if i == 0 :
continue
else :
dif = abs(L[i]-L[i-1])
if min > dif :
min = dif
print min |
There are N students living in the dormitory of Berland State University. Each of them sometimes wants to use the kitchen, so the head of the dormitory came up with a timetable for kitchen's usage in order to avoid the conflicts:
The first student starts to use the kitchen at the time 0 and should finish the cooking n... | import sys
n = int(raw_input().strip())
for i in xrange(n) :
len_a = int(raw_input().strip())
a = map(int,raw_input().strip().split(' '))
b = map(int,raw_input().strip().split(' '))
counter = 0
for i in range(0,len_a) :
if i == 0 :
if a[i] >= b[i] :
counter += 1
... |
Rohit loves to play poker. He has N piles of poker chips in a line. Number of chips in pile i is Ai. He wants to rearrange them such that Ai+1 = Ai + 1 for 1 ≤ i ≤ N-1 . The final piles can contain 0 chips as well.
To achieve this,he can take one coin from a pile and place it in another pile.Find the minimum number o... | for x in range(0,input()):
k,q = input(),map(int,raw_input().split())
n = (2*sum(q) -k*k -k)/(2.0*k)+1
if(n == int(n)): print sum(([abs(a - b) for a, b in zip(q, range( int(n), int(n)+k))]))/2
else: print - 1 |
As every other little boy, Mike has a favorite toy to play with. Mike's favorite toy is a set of N disks. The boy likes to compose his disks in stacks, but there's one very important rule: the disks in a single stack must be ordered by their radiuses in a strictly increasing order such that the top-most disk will have ... | def bs(k,start,end,search):
mid =(start+end)/2
if(start>end):
k[start] = search
return 0
if(start == end):
if(k[start] >search):
k[start] = search
else:
k[start+1] = search
return 0
else:
if(search<k[mid]):
return... |
There is a tree with n vertices. There are also m ants living on it. Each ant has its own color. The i-th ant has two favorite pairs of vertices: (a_i, b_i) and (c_i, d_i). You need to tell if it is possible to paint the edges of the tree in m colors so that every ant will be able to walk between vertices from one of i... | #include <bits/stdc++.h>
const int N = 100054, M = N * 2;
int n, m, V, E = 0;
int to[M], first[N], next[M];
int p[N], dep[N], size[N];
int cnt = 0, o[N], id[N], prf[N], len[N], top[N];
int tmp[N], dak[N];
int ant[N];
std::vector<int> mc[N];
inline void up(int &x, const int y) { x < y ? x = y : 0; }
inline void down(int... |
Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 ≤ x_1, x_2, x_3 ≤ n, 0 ≤ y_1, y_2, y_3 ≤ m and the area of the triangle formed by these points is equal to nm/k.
Help Vasya! Find such points (if it's possible). If there are multiple solutio... | #include <bits/stdc++.h>
using namespace std;
inline bool isvowel(char c) {
c = tolower(c);
if (c == 'a' || c == 'e' || c == 'i' || c == 'y' || c == 'o' || c == 'u')
return 1;
return 0;
}
const double eps = 0.000001;
const long double pi = acos(-1);
const int maxn = 1e7 + 9;
const int mod = 1e9 + 7;
const lon... |
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 10... | #include <bits/stdc++.h>
using namespace std;
int ile(long long int a) {
int ans = 0;
while (a) {
if (a % 2 == 1) ans++;
a /= 2;
}
return ans;
}
int main() {
int n;
cin >> n;
long long int* a;
a = new long long int[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int* b;
b = new int[... |
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Ever... | #include <bits/stdc++.h>
using namespace std;
const long long N = 4e5 + 7;
long long ans[N], be[N];
int32_t main() {
ios_base::sync_with_stdio(0);
long long n, m;
cin >> n >> m;
for (long long i = 0; i < n; i++) {
cin >> be[i];
}
sort(be, be + n);
vector<long long> vec;
for (long long i = 0; i < m; ... |
Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length n consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaa... | #include <bits/stdc++.h>
using namespace std;
long long n, a[1000005], as, bs, cs, ds;
long long f[5];
char ch[1000005];
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> ch[i];
for (int i = 0; i < n; i++) {
cin >> a[i];
if (ch[i] == 'h') f[1] += a[i];
if (ch[i] == 'a') f[2] = min(f[1], f[2] +... |
This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 15, M = 6e5 + 15, OO = 1e6 + 3;
int n, t, ss;
string in, in2, in3;
int cnt[27];
list<int> adj[N];
list<int>::iterator it;
int nums[N];
int MOD(int a, int b) {
a %= b;
if (a < 0) a += b;
return a;
}
int main() {
getline(cin, in3);
n = in3.size()... |
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n... | import org.omg.CORBA.INTERNAL;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new Pri... |
In the city of Capypaland where Kuro and Shiro resides, there are n towns numbered from 1 to n and there are m bidirectional roads numbered from 1 to m connecting them. The i-th road connects towns u_i and v_i. Since traveling between the towns is quite difficult, the taxi industry is really popular here. To survive th... | #include <bits/stdc++.h>
using namespace std;
long long a, b, c, q, w, e, o, h[200001], qq[200001], ww[200001], ee[200001],
v[200001], di[200001], fa[200001][21], de[200001], lg[200001], y[200001],
po[200001], cn, di1[200001];
struct p {
long long q, w, e;
} l[400001], ll[400001];
struct pp {
long long q, w... |
Thanks to the Doctor's help, the rebels managed to steal enough gold to launch a full-scale attack on the Empire! However, Darth Vader is looking for revenge and wants to take back his gold.
The rebels have hidden the gold in various bases throughout the galaxy. Darth Vader and the Empire are looking to send out their... | 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.io.BufferedWriter;
import java.util.Collection;
import java.util.InputMismatchException;
import java.util.Random;
import java.io.IOException;... |
Suppose you have a special x-y-counter. This counter can store some value as a decimal number; at first, the counter has value 0.
The counter performs the following algorithm: it prints its lowest digit and, after that, adds either x or y to its value. So all sequences this counter generates are starting from 0. For ... | from collections import*
s=input()
c=Counter((ord(y)-ord(x))%10for x,y in zip(s,s[1:]))
for i in range(100):
a = [-1] * 10
for j in range(1, 11):
for k in range(j+1):
x = ((j - k) * (i//10) + k * (i%10)) % 10
if a[x] == -1:
a[x] = j-1
z = 0
for x in c:
if a[x] == -1:
z = -1
break
else:
z +=... |
It is Bubble Cup finals season and farmer Johnny Bubbles must harvest his bubbles. The bubbles are in a rectangular bubblefield formed of N x M square parcels divided into N rows and M columns. The parcel in i^{th} row and j^{th} column yields A_{i,j} bubbles.
Johnny Bubbles has available a very special self-driving b... | #include <bits/stdc++.h>
using namespace std;
vector<int> ve[100005];
long long a[100005], b[10005], c[100005];
long long fun(int n) {
long long x = 0, y = 0;
for (int i = 0; i < n; i++) {
if (c[i] > x) {
y = x;
x = c[i];
} else if (c[i] > y)
y = c[i];
}
return x + y;
}
int main() {
... |
Nikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n).
If Nikolay is currently in some room, he c... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1e2 + 4;
const long long INF = 1e9;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
long long t;
cin >> t;
for (long long i = 0; i < t; i++) {
string str;
long long n;
cin >> n >> str;
long long l = INF, r = -1;
fo... |
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!
Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from... | #include <bits/stdc++.h>
using namespace std;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
const long long inf = 5e9 + 7;
const long long max_n = 2e3 + 3, log_n = 12;
long long n;
vector<vector<pair<long long, long long>>> scan(long long id) {
long long a;
cin >> a;
vector<long lo... |
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, ... | t = int(input())
def max_subarray(arr):
max_ending = max_current = arr[0]
for i in arr[1:]:
max_ending = max(i, max_ending + i)
max_current = max(max_current, max_ending)
return max_current
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
if max_subarray... |
Gildong recently learned how to find the [longest increasing subsequence](https://en.wikipedia.org/wiki/Longest_increasing_subsequence) (LIS) in O(nlog{n}) time for a sequence of length n. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though the... |
import java.util.*;
import java.io.*;
public class AirConditioner {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve() {
int t = ni();
for (int k = 0; k < t; k++) {
int n = ni();
char[] s = ns(n - 1);
int ans[] = new int[n];
... |
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there ... | import java.io.*;
import java.util.*;
public class Main {
static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
final int N = 200200;
final int LOG = 18;
List<Integer>[] g = new ArrayList[N];
int[] depth = new int[N];
int[][] par = new int[N][LOG];
void Dfs(... |
Phoenix is picking berries in his backyard. There are n shrubs, and each shrub has a_i red berries and b_i blue berries.
Each basket can contain k berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = (ll)1e18;
const int N = 505;
ll dp[N][N];
ll a[N];
ll b[N];
int main() {
ios_base::sync_with_stdio(0);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> a[i] >> b[i];
}
for (int i = 0; i <= n; i++) {
for (... |
Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought n integers, now it's time to distribute them between his friends rationally...
Lee has n integers a_1, a_2, …, a_n in his backpack and he has k friends. Lee would like to distribute all integers in his backpack betwe... | import sys
input = lambda:sys.stdin.readline().strip()
t = int(input())
while t:
t-=1
n,k = map(int,input().split())
a = list(map(int,input().split()))
w = list(map(int,input().split()))
adj = [[] for _ in range(k)]
a.sort()
w.sort()
i = 0
for i in range(k):
adj[i].append(a.... |
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j).
Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o... | for _ in range(int(input())):
n,m=map(int,input().split())
a,result=[],0
for i in range(n):
a.append(input())
for i in range(n):
if i==n-1:
for k in range(m):
if a[n-1][k]=='D':
a[n-1]=a[i][:k]+'R'+a[i][k+1:]
result += 1... |
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal a instant damage to him, and then heal that enemy b health points at the end of every second, for exactly c seconds, starting one second after the ability is used. That means that if the ability is used at time t, the ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 1;
const long long INFLL = 1e18 + 1;
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int t;
cin >> t;
while (t--) {
long long a, b, c, d;
cin >> a >> b >> c >> d;
long long left = 0, right = INF;
while (r... |
You are given four different integer points p_1, p_2, p_3 and p_4 on XY grid.
In one step you can choose one of the points p_i and move it in one of four directions by one. In other words, if you have chosen point p_i = (x, y) you can move it to (x, y + 1), (x, y - 1), (x + 1, y) or (x - 1, y).
Your goal to move poin... | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define x first
#define y second
int e (pair<int, int> p[4]) {
int ans = 0;
ans += abs (p[0].x - p[1].x);
ans += abs(p[3].x - p[2].x);
ans += abs(p[0].y- p[2].y);
ans += abs(p[1].y - p[3].y);
int x1 = min (p[2].x , p[3].x) - max(p[1].x , p[0].... |
You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.
Your task is to add spaces to the text by the following rules:
* if there is no punctuation mark between two wor... | import java.util.StringTokenizer;
import java.util.regex.*;
import java.io.*;
public class Task145A {
PrintWriter out;
BufferedReader input;
Task145A() {
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
try {
solver();
} catch(IOException ex) {}
out.close... |
A permutation is a sequence of n integers from 1 to n, in which all numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] are permutations, and [2, 3, 2], [4, 3, 1], [0] are not.
Polycarp was presented with a permutation p of numbers from 1 to n. However, when Polycarp came home, he noticed that in ... | import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range (t):
n = int(input())
a = [int(i) for i in input().split()]
vis = [0]*(n+1)
vis[a[0]]=1
for i in range (1,n):
if a[i]!=a[i-1]:
vis[a[i]]=1
mini = [a[0]]
maxi = ... |
One day Vasya got hold of a sheet of checkered paper n × m squares in size. Our Vasya adores geometrical figures, so he painted two rectangles on the paper. The rectangles' sides are parallel to the coordinates' axes, also the length of each side of each rectangle is no less than 3 squares and the sides are painted by ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int m, n, r[maxn], c[maxn], maxc[maxn], maxr[maxn], R, C, d[maxn][maxn], step,
tot;
string a[maxn];
int enough(int R, int x1, int x2, int x3, int x4) {
set<int> s;
s.insert(x1), s.insert(x2), s.insert(x3), s.insert(x4);
return s.size() == R;... |
The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.
The Two-dimensional kingdom has a regular army of n people. Each soldier registered himse... | n, m, x, y = map(int, input().split())
a_n = [i for i in map(int, input().split())]
b_m = [i for i in map(int, input().split())]
count = 0
result = []
i = 0
j = 0
while j < m and i < n:
if b_m[j] > a_n[i] + y:
i += 1
elif b_m[j] < a_n[i] - x:
j += 1
else:
count += 1
resu... |
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to... | #include <bits/stdc++.h>
using namespace std;
int a[100000] = {0};
string s;
int main() {
int min1 = 100000;
cin >> s;
int n = s.size();
for (int i = 1; i <= n; i++)
a[i] = a[i - 1] + (s[i - 1] >= 'A' && s[i - 1] <= 'Z' ? 1 : 0);
if (a[n] == n || a[n] == 0) {
cout << 0;
return 0;
}
for (int i ... |
When Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced ... | #include <bits/stdc++.h>
using namespace std;
double PI = acos(-1.0);
template <class T>
inline void checkmin(T &a, T b) {
if (b < a) a = b;
}
template <class T>
inline void checkmax(T &a, T b) {
if (b > a) a = b;
}
template <class T>
inline T gcd(T a, T b) {
if (!b) return a;
return gcd(b, a % b);
}
int main()... |
Little Vasya likes painting fractals very much.
He does it like this. First the boy cuts out a 2 × 2-cell square out of squared paper. Then he paints some cells black. The boy calls the cut out square a fractal pattern. Then he takes a clean square sheet of paper and paints a fractal by the following algorithm:
1. ... | #include <bits/stdc++.h>
using namespace std;
const int N = 500, K = 16;
const int b[4] = {8, 4, 2, 1};
const int kx[4] = {0, 0, 1, 1};
const int ky[4] = {0, 1, 0, 1};
int n, m;
bool dp[10][K][N][N];
int sum[N][N];
char c;
bool a[N][N];
int getsum(int x, int y) { return ((x >= 0 && y >= 0) ? sum[x][y] : 0); }
bool is_b... |
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.
The ... | #include <bits/stdc++.h>
using namespace std;
bool comp(int x, int y) { return x > y; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
;
int tt = 1;
long long m, n, k;
string st;
while (tt--) {
cin >> n;
int arr[n];
for (long long i = 0; i < n; i++) cin >> arr[i];
... |
Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.
Input
The single line contains two integers n and m... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const double eps = 1e-8;
const int nm = 300005;
int n, k, m, t;
long long res;
int a[nm];
char s[nm];
bool check[nm];
long long Pow(int x, int mu) {
if (mu == 0) return 1ll;
long long res = Pow(x, mu >> 1);
res = res * res % MOD;
if (mu &... |
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of ver... | #include <bits/stdc++.h>
using namespace std;
int route[1005], d[305], k[305], pre[305], p[305];
vector<int> v[305];
int cnt = 0;
void dfs(int i, int f) {
for (int j = 0; j < v[i].size(); j++) {
if (v[i][j] != f) {
pre[v[i][j]] = i;
dfs(v[i][j], i);
}
}
}
int solve(int k1, int k2, int t) {
int... |
In this problem you have to build tournament graph, consisting of n vertices, such, that for any oriented pair of vertices (v, u) (v ≠ u) there exists a path from vertex v to vertex u consisting of no more then two edges.
A directed graph without self-loops is a tournament, if there is exactly one edge between any two... | #include <bits/stdc++.h>
const int a[6][6] = {{0, 1, 1, 0, 1, 0}, {0, 0, 1, 1, 0, 1},
{0, 0, 0, 1, 1, 0}, {1, 0, 0, 0, 1, 1},
{0, 1, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0}};
const int b[3][3] = {
{0, 1, 0},
{0, 0, 1},
{1, 0, 0},
};
int c[1000 + 9][1000 + 9], n;
int main() ... |
You are given a sequence of positive integers x1, x2, ..., xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves:
* subtract 1 from the current a;
* subtract a mod xi (1 ≤ i ≤ n) from the current a.
Operation a mod xi means taking the rem... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, a, b;
scanf("%d", &n);
vector<int> v(n);
for (int i = 0; i < n; i++) scanf("%d", &v[i]);
sort(v.begin(), v.end(), greater<int>());
v.resize(unique(v.begin(), v.end()) - v.begin());
scanf("%d%d", &a, &b);
int count = 0, be = 0;
while (a ... |
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.
Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly <image> times consecutively. In other words, array a is k-periodic, if it has period... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A implements Runnable {
static String Y = "YES", N = "NO";
static lo... |
Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation:
F1 = 1, F2 = 2, Fi = Fi - 1 + Fi - 2 (i > 2).
We'll define a new number sequence Ai(k) by the formula:
Ai(k) = Fi × ik (i ≥ 1).
In this problem, your task is to calculate the following sum: A1(k) + A2(k) + ... ... | #include <bits/stdc++.h>
const int Maxk = 40;
const int Mod = 1000000007;
int C[Maxk + 5][Maxk + 5];
int pow_2[Maxk + 5];
long long n;
int k;
int len;
void init() {
pow_2[0] = 1;
C[0][0] = 1;
for (int i = 1; i <= k; i++) {
C[i][0] = C[i][i] = 1;
for (int j = 1; j < i; j++) {
C[i][j] = (C[i - 1][j] +... |
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
long long f[2005][2005], n, k;
vector<int> u[2005];
void U() {
for (int i = 1; i < 2005; i++) {
for (int j = 1; j <= i; j++)
if (i % j == 0) u[i].push_back(j);
}
}
int main() {
ios::sync_with_stdio(false);
U();
cin >> n >> k;
... |
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.
Help Andrey choose... | #include <bits/stdc++.h>
using namespace std;
double fun(double a, double b) { return (a * (1 - b)) + ((1 - a) * b); }
double Max(double a, double b, double c) { return fmax(fmax(a, b), c); }
double cmp(double a, double b) { return a > b; }
int main() {
ios::sync_with_stdio(false);
int n;
double a[1000], max;
w... |
Andrew and Eugene are playing a game. Initially, Andrew has string s, consisting of digits. Eugene sends Andrew multiple queries of type "di → ti", that means "replace all digits di in string s with substrings equal to ti". For example, if s = 123123, then query "2 → 00" transforms s to 10031003, and query "3 → " ("rep... | #include <bits/stdc++.h>
using namespace std;
char t;
int n, mod = 1e9 + 7;
pair<int, int> val[10];
string s;
pair<char, string> que[100005];
pair<int, int> calc(string x) {
int v = 0, p = 1;
for (int i = 0; i < x.size(); ++i) {
int y = x[i] - '0';
v = (1LL * val[y].second * v + val[y].first) % mod;
p =... |
There is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x1, x2, x3, x4} (x1 ≤ x2 ≤ x3 ≤ x4) arithmetic mean is <image>, median is <image> and range is x4 - x1. Th... | #include <bits/stdc++.h>
using namespace std;
struct _init_ {
_init_() {
ios_base::sync_with_stdio(0);
cin.tie(0);
setvbuf(stdout, NULL, _IOFBF, 1024);
setvbuf(stdin, NULL, _IOFBF, 1024);
}
} _init_ob_unused;
template <class T>
inline T read(T &n) {
cin >> n;
return n;
}
template <class T1, clas... |
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in l... | #include <bits/stdc++.h>
using namespace std;
vector<int> status(26);
vector<vector<int> > adjList(200000);
vector<string> names(100);
vector<int> ts;
vector<int> processing(26);
void dfs(int u, bool &valid) {
status[u] = 1;
processing[u] = true;
for (int j = 0; j < adjList[u].size(); j++) {
int v = adjList[u... |
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead.
<image>
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions... | #include <bits/stdc++.h>
using namespace std;
template <class T>
bool chkmin(T& a, T b) {
return a > b ? a = b, true : false;
}
template <class T>
bool chkmax(T& a, T b) {
return a < b ? a = b, true : false;
}
template <class T>
void read(T& a) {
char c = getchar_unlocked();
T f = 1;
a = 0;
for (; !isdigit(... |
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
... |
import java.util.*;
public class aiw {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long[] arr = new long[6];
for(int i = 0;i<6;i++){
arr[i] = sc.nextLong();
}
long x = arr[0] + arr[4] + arr[5];
x = x*x;
x = x - arr[0]*arr[0] - arr[2]*arr[2] - arr[4]*arr[4];
Syste... |
Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a let... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main() {
long long a, b;
cin >> a >> b;
if (gcd(a, b) > 1)
printf("Impossible\n");
else {
while (a && b) {
if (a > b) {
printf("%lldA", (a - 1) / b)... |
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.
Input
The first line contai... | n = int(input())
m = int(input())
a = []
for i in range(n):
a.append(int(input()))
a.sort(reverse=True)
for i in range(n):
m -= a[i]
if m <= 0:
print(i+1)
exit()
|
As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and bec... | #include <bits/stdc++.h>
using namespace std;
int gi() {
int res = 0, w = 1;
char ch = getchar();
while (ch != '-' && !isdigit(ch)) ch = getchar();
if (ch == '-') w = -1, ch = getchar();
while (isdigit(ch)) res = res * 10 + ch - '0', ch = getchar();
return res * w;
}
using LL = long long;
const LL INF = 1e1... |
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+
++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>+++++++
+++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>.<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<<
<<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<... | #include <bits/stdc++.h>
int main() {
long long base = 1, suma = 0, num, res;
int one = 0;
scanf("%I64d", &num);
do {
res = num % 8;
num = num / 8;
suma = suma + res * base;
base = base * 10;
} while (num > 0);
while (suma > 0) {
if (suma % 10 == 1) {
one++;
}
suma /= 10;
... |
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.
There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each... | import java.util.*;
import java.io.*;
import java.math.*;
public class Main implements Runnable {
final String filename="test";
final int base = 1<<20;
int[] tree = new int[base*2];
void set(int x, int val)
{
x+=base;
while (x>0)
{
tree[x] = Math.max(tree[x], val);
x /=2;
}
}
int getmax(int... |
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to d kilometers.
Vasiliy's car is not new — it breaks after driven every k kilometers and Vasiliy needs t seconds to repair it. After repairing his car Vasiliy can drive again (but after k kilometers it will ... | import math
d, k, a, b, t = map(int, input().split())
distance = a * t /((b -a )*b) + t /b
time = 0
n = math.ceil((d-distance)/k)
# print(distance)
# print(n)
if (k>d):
print(d*a)
exit(0)
if (k<distance):
time = k*a + (d-k)*b
print(time)
exit(0)
if (n*k >=d):
time = a*d + d//k*t
if (d%k==0... |
There are n cities located along the one-way road. Cities are numbered from 1 to n in the direction of the road.
The i-th city had produced pi units of goods. No more than si units of goods can be sold in the i-th city.
For each pair of cities i and j such that 1 ≤ i < j ≤ n you can no more than once transport no mor... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.stream.LongStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.OptionalLong;
import java.io.Closeable;
import java.io.Writer;
... |
Eugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct.
Nikolay has m cards, distinct numbers from 1 to m are written ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
int a[maxn];
bool vis[maxn];
map<int, int> mp, us;
int main() {
memset(vis, false, sizeof vis);
mp.clear();
us.clear();
int n, m;
scanf("%d%d", &n, &m);
int odd = 0, oodd = 0, even = 0, oeven = 0;
for (int i = 0; i < n; i++) {
sc... |
The kingdom of Olympia consists of N cities and M bidirectional roads. Each road connects exactly two cities and two cities can be connected with more than one road. Also it possible that some roads connect city with itself making a loop.
All roads are constantly plundered with bandits. After a while bandits became bo... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200;
const int MAXM = 1 << 16;
int n, m;
struct DSU {
int p[201];
int sz[201];
DSU() {
for (int i = 1; i <= MAXN; i++) p[i] = i, sz[i] = 1;
}
int parent(int u) { return p[u] = (p[u] == u ? u : parent(p[u])); }
void unite(int u, int v) {
... |
Earlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices.
Once Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offic... | #include <bits/stdc++.h>
using namespace std;
inline long long rd() {
long long x = 0;
int ch = getchar(), f = 1;
while (!isdigit(ch) && (ch != '-') && (ch != EOF)) ch = getchar();
if (ch == '-') {
f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = (x << 1) + (x << 3) + ch - '0';
ch = getch... |
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.
On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 t... | #include <bits/stdc++.h>
using namespace std;
int a[1010], b[1010];
int n;
int ans[1010];
bool used[1010];
bool judge() {
memset(used, false, sizeof(used));
for (int i = 1; i <= n; ++i) {
int tmp = ans[i];
if (used[tmp]) return false;
used[tmp] = true;
}
return true;
}
int main() {
scanf("%d", &n)... |
There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void cmax(T& a, T b) {
a = max(a, b);
}
template <typename T>
void cmin(T& a, T b) {
a = min(a, b);
}
void _BG(const char* s) {}
template <typename T, typename... TT>
void _BG(const char* s, T a, TT... b) {
for (int c = 0; *s && (c || *s != ',');... |
One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time h... | import java.io.*;
import java.util.*;
import java.math.*;
public class C implements Runnable {
static class Node {
Node l;
Node r;
int x;
boolean isLeaf;
long sum;
int max;
int min;
int path;
public Node(int x) {
sum = max = min = this.x = x;
isLeaf = true;
}
}
static void setChild(Node... |
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ... | import java.util.Scanner;
import java.util.HashMap;
public class Solution {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
HashMap<Integer, Integer> hm = new HashMap<>();
int count = 0;
hm.put(0, count++);
int n = in.nextInt();
int time = 1;
while (n-- > 0){
int t = in... |
In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An ex... | import java.util.* ;
public class PythonIndentation
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
boolean[] lst = new boolean[n] ;
for(int i=0;i<n;i++)
{
lst[i] = (in.next().equals("s"))?false:true ;
}
System.out.println(dp(lst)) ;
}
sta... |
Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to k, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.
Arkady and Kirill made some photos of the coins, each photo contained a segment of neighb... | #include <bits/stdc++.h>
using namespace std;
const int Mod = 1000000007;
int fpow(int a, int b) {
int ans = 1, t = a;
while (b) {
if (b & 1) ans = 1ll * ans * t % Mod;
t = 1ll * t * t % Mod;
b >>= 1;
}
return ans;
}
int l1[100010], r1[100010];
int l2[100010], r2[100010];
int p[400010], N;
long long... |
The Rebel fleet is afraid that the Empire might want to strike back again. Princess Heidi needs to know if it is possible to assign R Rebel spaceships to guard B bases so that every base has exactly one guardian and each spaceship has exactly one assigned base (in other words, the assignment is a perfect matching). Sin... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; i++) {
int u, v;
cin >> u >> v;
}
for (int j = 1; j <= m; j++) {
int u, v;
cin >> u >> v;
}
if (n == m)
puts("Yes");
else
puts("No... |
You work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.
Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you... | #include <bits/stdc++.h>
using namespace std;
int ab(int x) {
if (x < 0) return -x;
return x;
}
int get_bit(int id, int mask) {
int tmp = 1;
for (int i = 1; i < id; i++) tmp *= 10;
return (mask / tmp) % 10;
}
int ltm[5];
vector<int> tmv;
int on_bit(int x, int mask) {
tmv.clear();
tmv.push_back(x);
for (... |
Aaryan went to school like any usual day, The teacher asked his crush the following question.
Given an array of numbers, First she had to compute the XOR of all the subsequences that can be formed.
Suppose each subsequence had their following XOR value that came out after computing -> {P[0], P[1], P[2], and so on upto... | from sys import stdin
stdin.readline()
a=map(int, stdin.readline().split())
b=a[0]
for i in a[1:]:
b|=i
print b |
Problem Statement:
Line segment intersection is one of the important part of mathematics. Bob will be given a set of n number of line segments, followed by set of q number of query lines. He is supposed to find how many line segments from set of n intersect given query line. As bob likes only parallel lines he will... | limit = 100005
for _ in range(input()):
n, q = map(int, raw_input().split())
startx, starty, endx, endy, linex, liney=[0]*limit,[0]*limit,[0]*limit,[0]*limit,[0]*limit,[0]*limit
for i in range(n):
a, b, c, d = map(int, raw_input().split())
if a > c:
a, c = c, a
if b > d:... |
Printf{}, Pappu Bhujia, mon_ki_onkh are playing Counter Strike 1.6 . Printf{} and Pappu Bhujia are in the same team (Counter Terrorists) and mon_ki_onkh is in the opposite team (Terrorists). It is a 2 on 1 round. The players playing have enough guns and bullets to fight.
Some Facts to be known :
The number of bullets ... | def isprime(n):
for i in range(2, int(pow(n,0.5)) + 1):
if n % i == 0:
return False
return True
p = dict()
def factorization(n):
if isprime(n):
if n in p:
p[n] += 1
else:
p[n] = 1
else:
for i in range(2, int(pow(n, 0.5)) + 1):
if n % i == 0:
factorization(i)
factorization(n/i)
break... |
In Pragyan, every shop has their own discount methods to attract the customers. One discount method called Buy 1 Get 1 caught your friend's attention. That is, if your friend buys one object, then your friend can get one additional object with the same color without charge by Buy 1 Get 1.
Your friend lists the needed o... | def main():
n = input()
l = []
for i in range(n):
str = raw_input()
dict = {}
for j in str:
dict[j] = 0
for j in str:
dict[j] += 1
sum = 0
for k in dict:
if( dict.get(k) %2 == 1):
sum +... |
Champa loved traveling the world. He loved going from one city to the other. Being the miser that he is, he never wishes spend any money. Champa, instead, jumps from one city to the other. Also he likes trips of high quality.
He can start at any city of his choice. Given that he has visited the i^th city, he will not ... | t = int(input())
while(t>0):
t-=1
N,Q = map(int,raw_input().split())
arr = sorted(map(int,raw_input().split()))
prev = arr[0]
s = 0
for i in xrange(1,N):
s += abs(prev-arr[i])
prev = arr[i]
print s*Q |
Milly is very much concern about her rank in her class. So to make her feel better , her friend Pranjul will give three numbers to her denoting N, X and Y. N represents the total number of students in the class. Now he has already described about the rank predictor algorithm that he has made for her. According to this ... | test_case = int(input())
str_out = ''
while(test_case):
rank_inp = []
rank_inp = raw_input().split()
int_out = int(rank_inp[2]) + 1
if(int_out + int(rank_inp[1]) > int(rank_inp[0])):
int_out = int(rank_inp[2])
str_out += str(int_out)
test_case -= 1
str_out += "\n"
print str_out |
Motu and Chotu are Best-Friends.
They both used to play CS-GO all the time. We know that there are two teams , they are CT and T .As Motu got bored of playing CS-GO whole day. He found a different game to play.
Motu likes only if a CT guy stands beside a CT guy or a T guy stands beside a T guy . But Chotu likes the... | for _ in xrange(input()):
n = input()
a, b = map(int, raw_input().split())
if max(a,b)>min(a,b)+1:
print "Motu"
else:
print "Chotu" |
Sara and Tara were two young girls who had a really bad handwriting.So they decided to write down a word. Being highly passionate about improving their handwriting as well using there creative mind, they also wrote down the same word again but this time starting from the last letter to the first letter with the intern... | import sys
s=raw_input()
rev=s[::-1]
l=len(s)
for i in range(0,l-1,1):
sys.stdout.write(s[i]+"-")
print s[i+1]
for i in range(0,l-1,1):
sys.stdout.write(rev[i]+"-")
print rev[i+1] |
In the game of chess, there is a piece called the knight. A knight is special -- instead of moving in a straight line like other pieces, it jumps in an "L" shape. Specifically, a knight can jump from square (r1, c1) to (r2, c2) if and only if (r1 - r2)2 + (c1 - c2)2 = 5.
In this problem, one of our knights is going to... | def table(height, width):
t = []
for i in range(height):
t.append([])
for j in range(width):
t[i].append(0)
return t
def compute():
h, w, r = map(int, raw_input().split())
rocks = table(h, w)
board = table(h, w)
for i in range(r):
rr, cc = map(int, raw_input().split())
rocks[... |
Given Two matrix A and B of some order ** RXC. Both matrix contains elements from 1 to *RC** . Matrix A contains elements in Row-major order while Matrix B contains elements in Column-major order .you are asked to answer a very simple question what is the trace of the matrix formed by the addition of A and B.
Here, T... | t = int(raw_input())
counter =0
while counter< t:
s= raw_input()
L = s.split(' ')
r = int(L[0])
c=int(L[1])
l = min(r,c)
rc2 = c+r+2
print ((l*(l-1))/2)*(rc2) + l*2
counter+=1 |
There are N persons called Person 1 through Person N.
You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.
If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.
Ta... | import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(reader);
Main ins = new Mai... |
Given are an integer N and arrays S, T, U, and V, each of length N. Construct an N×N matrix a that satisfy the following conditions:
* a_{i,j} is an integer.
* 0 \leq a_{i,j} \lt 2^{64}.
* If S_{i} = 0, the bitwise AND of the elements in the i-th row is U_{i}.
* If S_{i} = 1, the bitwise OR of the elements in the i-th... | #include <bits/stdc++.h>
using namespace std;
using ul=unsigned long long;
int s[500],t[500],tmp[500][500],S[500],T[500],n,bit=-1,IN;
ul ans[500][500],u[500],v[500];
void ng(){
cout<<-1;
exit(0);
}
struct P{int va,idx,ve,ne,al;};
bool operator <(const P&a,const P&b){return a.va<b.va;};
priority_queue<P>que;
#def... |
For an integer n not less than 0, let us define f(n) as follows:
* f(n) = 1 (if n < 2)
* f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
Constraints
* 0 \leq N \leq 10^{18}
Input
Input is given from Standard Input in the following format:
... | n=int(input())
if n%2==1:print(0);exit()
A=0
add=10
while n>=add:
A +=n//add
add *=5
print(A) |
There are N apple trees in a row. People say that one of them will bear golden apples.
We want to deploy some number of inspectors so that each of these trees will be inspected.
Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector ... | a,b = map(int, input().split())
t = 2*b + 1
print((a-1)//t+1) |
You are given positive integers A and B.
Find the K-th largest positive integer that divides both A and B.
The input guarantees that there exists such a number.
Constraints
* All values in input are integers.
* 1 \leq A, B \leq 100
* The K-th largest positive integer that divides both A and B exists.
* K \geq 1
In... | #include <bits/stdc++.h>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
int d=0;
for(int i=a;i>=1;i--){
if(a%i==0&&b%i==0){
c--;
if(c==0){
cout<<i<<endl;
return 0;
}
}
}
}
|
You are given positive integers N and M.
How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.
Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.
Constraints
* All valu... | n, m = map(int, input().split())
yd = {}
i = 2
while m != 1:
while m % i == 0:
if i in yd:
yd[i] += 1
else:
yd[i] = 1
m //= i
i += 1
ans = 1
for v in yd.values():
start = v + n - 1
c = 1
for _ in range(v):
c *= start
start -= 1
d = 1
for _v in range(v):
d *= (_v + 1)
... |
There are 2^N players, numbered 1, 2, ..., 2^N. They decided to hold a tournament.
The tournament proceeds as follows:
* Choose a permutation of 1, 2, ..., 2^N: p_1, p_2, ..., p_{2^N}.
* The players stand in a row in the order of Player p_1, Player p_2, ..., Player p_{2^N}.
* Repeat the following until there is only ... | #include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>
#define SIZE 18
#define BT (1<<18)
#define MX 100005
#define MOD 1000000007
using namespace std;
typedef long long int ll;
typedef pair <int,int> P;
ll fac[MX],finv[MX],inv[MX];
int A[SIZE];
ll dp[2][BT];
void make()
{
fa... |
We have a string s consisting of lowercase English letters. Snuke can perform the following operation repeatedly:
* Insert a letter `x` to any position in s of his choice, including the beginning and end of s.
Snuke's objective is to turn s into a palindrome. Determine whether the objective is achievable. If it is ... | import java.io.*;
import java.time.Year;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.lang.Math.*;
import static java.lang.String.format;
public class Main {
public static void main(String[] args) {
solve(... |
Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.
First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.
Then, Aoki gave him M queries. The i-th of them is as follows:
* Increment the number written at each edge along the... | N,M = map(int,input().split())
cnt = [0]*(N+10)
for i in range(M):
a,b = map(int,input().split())
cnt[a]+=1
cnt[b]+=1
for c in cnt:
if c%2 == 1:
print('NO')
import sys
sys.exit()
print('YES')
|
In an electric circuit, when two resistors R_1 and R_2 are connected in parallel, the equivalent resistance R_3 can be derived from the following formula:
* \frac{1}{R_1} + \frac{1}{R_2} = \frac{1}{R_3}
Given R_1 and R_2, find R_3.
Constraints
* 1 \leq R_1, R_2 \leq 100
* R_1 and R_2 are integers.
Input
The inp... | #include<iostream>
#include<iomanip>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<cctype>
#define D (double)
using namespace std;
int n,m;
signed main()
{
scanf("%d%d",&n,&m);
printf("%.10... |
Snuke is having a barbeque party.
At the party, he will make N servings of Skewer Meal.
<image>
Example of a serving of Skewer Meal
He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i. Also, he has an infinite supply of ingredients.
To make a serving of Skew... | #include<bits/stdc++.h>
using namespace std;
int main(){
int N;cin>>N;
vector<int>L(2*N);for(int i=0;i<2*N;i++)cin>>L[i];
sort(L.begin(),L.end());
int ans=0;
for(int i=0;i<N;i++){
ans+=L[2*i];
}cout<<ans;
}
|
Taro is playing with a puzzle that places numbers 1-9 in 9x9 squares. In this puzzle, you have to arrange the numbers according to the following rules.
* One number appears exactly once in the same column
* A number appears exactly once on the same line
* In each of the 3x3 ranges separated by double lines, a number a... | #include <stdio.h>
int a[9][9];
void check(int x,int y){
for(int i=0;i<9;i++){
if(a[i][y]==a[x][y]&&i!=x){
printf("*%d",a[x][y]);
return;
}
}
for(int i=0;i<9;i++){
if(a[x][i]==a[x][y]&&i!=y){
printf("*%d",a[x][y]);
return;
}
... |
The reciprocal of all non-zero real numbers is real, but the reciprocal of an integer is not necessarily an integer. This is the reason why 3/2 * 2 = 2 even though 3.0 / 2.0 * 2.0 = 3.0 in C language. However, if you consider integers with the same remainder after dividing by a prime number as the same, you can make al... | import java.util.*;
class Main{
int INF=Integer.MAX_VALUE;
char[] in;
int prime;
int p;
void solve(){
Scanner sc = new Scanner(System.in);
while(true){
String[] line = sc.nextLine().split(":");
if(line[0].equals("0")) break;
... |
problem
There are the following two-player card games.
* This game uses a total of 2n cards with each integer from 1 to 2n written on it. Here, n is an integer between 1 and 100.
* Deal n cards to each of the two.
* Put cards into play alternately one by one according to the following rules.
* If there are no cards i... | import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(true) {
int N=sc.nextInt();
if(N==0) {
System.exit(0);
}
ArrayList<Integer> taro=new ArrayList<Integer>();
Arr... |
To write a research paper, you should definitely follow the structured format. This format, in many cases, is strictly defined, and students who try to write their papers have a hard time with it.
One of such formats is related to citations. If you refer several pages of a material, you should enumerate their page num... | #include <iostream>
#include <vector>
#include <string>
using namespace std;
string make_str(int s, int e) {
if (s == e) return to_string(s);
return to_string(s) + '-' + to_string(e);
}
int main() {
int n;
while (cin >> n, n) {
vector<int> x(n);
for (int& i : x) cin >> i;
int i... |
Goldbach's Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2.
This conjecture has not been proved nor refused yet. No one is sure whether this conjecture actually holds. However, one can find such a pair of prime numbers, if an... | #include <iostream>
using namespace std;
const int MAX_PRIME = (1 << 15);
bool prime[MAX_PRIME + 1];
void init_prime()
{
for (int i = 0; i <= MAX_PRIME; i++)
prime[i] = true;
prime[0] = prime[1] = false;
for (int i = 2; i * i <= MAX_PRIME; i++)
if (prime[i])
for (int j = 2 *... |
In AD 3456, the earth is too small for hundreds of billions of people to live in peace. Interstellar Colonization Project with Cubes (ICPC) is a project that tries to move people on the earth to space colonies to ameliorate the problem. ICPC obtained funding from governments and manufactured space colonies very quickly... | #include<cstdio>
#include<vector>
#include<cmath>
#include<queue>
#include<cassert>
#include<utility>
#include<algorithm>
using namespace std;
typedef double Real;
typedef pair<int,int> P;
const Real eps=1e-7;
const Real inf=1e9;
template<class T> bool eq(T a,T b){
return abs(a-b)<eps;
}
template<class T> int sgn(... |
Problem
Chieno and Cacao are sisters who work in the same coffee shop. The two are very close, and one day they decided to play a table game.
The game uses the board of R square x C square and the rabbit TP as a piece. Each square on the board is painted white or black. First, place the TP in the lower right corner (... | #define REP(i,n) for(int i=0; i<(int)(n); i++)
#include <cstdio>
inline int getInt(){ int s; scanf("%d", &s); return s; }
#include <set>
using namespace std;
char b[1024][1024];
int memo[1024][1024];
bool win[1024][1024];
int main(){
const int h = getInt();
const int w = getInt();
const int k = getInt();
... |
Ron is a master of a ramen shop.
Recently, he has noticed some customers wait for a long time. This has been caused by lack of seats during lunch time. Customers loses their satisfaction if they waits for a long time, and even some of them will give up waiting and go away. For this reason, he has decided to increase s... | #include<iostream>
#include<cassert>
#include<vector>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
#define ALL(C) (C).begin(),(C).end()
typedef long long ll;
const int N = 100;
const int M =... |
You are enthusiastic about the popular web game "Moonlight Ranch". The purpose of this game is to grow crops in the fields, sell them to earn income, and use that income to grow the ranch.
You wanted to grow the field quickly. Therefore, we decided to arrange the crops that can be grown in the game based on the income... | #include<bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);i++)
#define ALL(v) (v).begin(),(v).end()
#define int long long
typedef pair<int,int> P;
//-----------------------------------------------------------------------
double calc(int p,int a,int b,int c,int d,int e,int f,int s,int m){
in... |
Time Limit: 8 sec / Memory Limit: 64 MB
Example
Input
3 3 2
1 1
2 1 1
3 1 1 1
Output
8 | #include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
using namespace std;
int n,m,W,k,kt,w;
int weight[17];
int load[10001];
int memo[1<<17];
void memoize() {
for(int i=1; i<(1<<k); ++i) {
memo[i] = 1<<29;
int sumw = 0;
for(int j=0; j<k; ++j)
if((i>>j)&1)... |
* This story is fiction and has nothing to do with real people or groups.
Social games have become very popular these days, and many companies are developing social games.
You are infiltrating one of the competing social game developers as a spy.
problem
The company you work for develops social games. The game we a... | #include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
const double lim = 0.0001;
int n; double p[309], sq[309], a[309];
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> p[i], sq[i] = sqrt(p[i]), a[i] = 0.03 / n;
double ret = 1.0e+9; int cnt = 0;
while (true) {
double curval = 0.0;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.