input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
It is a balmy spring afternoon, and Farmer John's n cows are ruminating about link-cut cacti in their stalls. The cows, labeled 1 through n, are arranged so that the i-th cow occupies the i-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has f... | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.... |
Kekoland is a country with n beautiful cities numbered from left to right and connected by n - 1 roads. The i-th road connects cities i and i + 1 and length of this road is wi kilometers.
When you drive in Kekoland, each time you arrive in city i by car you immediately receive gi liters of gas. There is no other way ... | #include <bits/stdc++.h>
using namespace std;
int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch - '0' < 0 || ch - '0' > 9) {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch - '0' >= 0 && ch - '0' <= 9) {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int n, m, top;... |
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate.
<image>
Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the ... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
String[] s2 = s.split("e");
String pre = s2[0];
String sub = s2[1];
int subInt = Integer.valueOf(sub);
if (subInt == 0){
if (pre.endsWith(".... |
Cowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rot... | #include <bits/stdc++.h>
using namespace std;
double eps(1e-10);
int sign(const double& x) { return (x > eps) - (x + eps < 0); }
bool equal(const double& x, const double& y) {
return x + eps > y && y + eps > x;
}
struct Point {
double x, y, z;
Point() {}
Point(const double& x, const double& y, const double& z) ... |
Gosha is hunting. His goal is to catch as many Pokemons as possible. Gosha has a Poke Balls and b Ultra Balls. There are n Pokemons. They are numbered 1 through n. Gosha knows that if he throws a Poke Ball at the i-th Pokemon he catches it with probability pi. If he throws an Ultra Ball at the i-th Pokemon he catches i... | #include <bits/stdc++.h>
using namespace std;
inline int gi() {
int data = 0, m = 1;
char ch = 0;
while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if (ch == '-') {
m = 0;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
data = (data << 1) + (data << 3) + (ch ^ 48);
ch = getchar(... |
You are given a rectangular table 3 × n. Each cell contains an integer. You can move from one cell to another if they share a side.
Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximu... | #include <bits/stdc++.h>
using namespace std;
long long memo[5][100005];
int grid[5][100005];
int N;
long long DP(int start, int idx) {
if (idx == N) {
if (start == 2)
return 0;
else
return -1000000000000000;
}
if (idx > N) return -1000000000000000;
if (memo[start][idx] != -1) return memo[st... |
Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1, a2, ..., an}, in which every number from 1 to n appears exactly once.
One day Anton got a new permutation and started to play with it. He does the following operation q times: he... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e6 + 10;
int eli = 9;
int nozomi;
int n, Q;
int L[MAXN], R[MAXN], a[MAXN], b[MAXN];
long long change(int x, int u, int v) {
int p = x >> eli;
long long ret = 0;
for (int i = 0; i <= nozomi; i++) {
if (i < p) {
int pos = lower_bound(b + L[i]... |
It can be shown that any positive integer x can be uniquely represented as x = 1 + 2 + 4 + ... + 2k - 1 + r, where k and r are integers, k ≥ 0, 0 < r ≤ 2k. Let's call that representation prairie partition of x.
For example, the prairie partitions of 12, 17, 7 and 1 are:
12 = 1 + 2 + 4 + 5,
17 = 1 + 2 + 4 + 8 + 2,
... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
long long int n, cnt1;
vector<long long int> v(N);
map<long long int, long long int> m;
bool f(long long int x) {
m.clear();
for (long long int i = (long long int)0; i <= (long long int)n - 1; i++)
m[v[i]]++;
vector<long long int> last(x, 1)... |
Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high.
Vladimir has just planted n bamboos in a row, each of... | #include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, a[N];
long long ans, k;
bool check(long long d, long long k) {
long long sum = 0;
for (int i = 1; i <= n; i++) sum += (a[i] + d - 1) / d;
return sum <= k;
}
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) cin >> a[i], k += a[i];
... |
Smith wakes up at the side of a dirty, disused bathroom, his ankle chained to pipes. Next to him is tape-player with a hand-written message "Play Me". He finds a tape in his own back pocket. After putting the tape in the tape-player, he sees a key hanging from a ceiling, chained to some kind of a machine, which is conn... | #include <bits/stdc++.h>
using namespace std;
int Trie[5000050][5], tz;
int N, M;
int leaf[5000050];
int cnt[5000050];
char B[55];
int lc;
int chk[5000010];
int v[100010], vz;
int ans;
void dfs(int x, int y) {
if (B[x] == 0) {
if (chk[y] == 0) {
chk[y] = 1;
v[vz++] = y;
ans += cnt[y];
}
... |
One day Nikita found the string containing letters "a" and "b" only.
Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".
Nikita wants to make... | """
Satwik_Tiwari ;) .
28 june , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOB... |
You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.
We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.
Input
The first line contains the onl... | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import javax.sound.midi.Synthesizer;
public class Main
{
private InputStream is;
private PrintWriter out;
int time = 0, freq[], start[], end[], dist[], black[], MOD = (int) (1e9 + 7), arr[], weight[][], x[], y[], parent[];
int MAX =... |
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and anno... | import java.util.*;
public class Main{
public static void main(String[] args) {
// Use the Scanner class
Scanner sc = new Scanner(System.in);
/*
int n = sc.nextInt(); // read input as integer
long k = sc.nextLong(); // read input as long
double d = sc.n... |
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences o... | #include <bits/stdc++.h>
using std::endl;
using std::map;
using std::priority_queue;
using std::string;
using std::vector;
int main(void) {
using std::cin;
using std::cout;
std::ios_base::sync_with_stdio(false);
cin.tie(0);
string S;
cin >> S;
const int N = S.size();
int lastInd = -1;
priority_queue<i... |
In BerSoft n programmers work, the programmer i is characterized by a skill r_i.
A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel.
You are given the skills of ea... | from bisect import *
n, k = map(int, input().split())
r = list(map(int, input().split()))
s = sorted(r)
l = [0] * n
for i in range(n):
l[i] = bisect_left(s, r[i])
for i in range(k):
x, y = map(int, input().split())
x -= 1
y -= 1
if r[x] < r[y]:
l[y] -= 1
elif r[x] > r[y]:
l[x] -= 1... |
On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game.
It is well known that one month on this planet consists of n^2 days, so calendars, represented as square matrix n by n are extremely popular.
Weather conditions are even more unusual. Due to the unique composition o... | #include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1000005;
const long long MOD = 998244353;
const long long inv3 = 332748118;
long long n, ans;
long long Read() {
long long x = 0, f = 1;
char c = getchar();
while (c > '9' || c < '0') {
if (c == '-') f = -1;
c = getchar();
}
while (c... |
Rajat Singh , a student of Delhi University is learning the ways of finding the mean of N numbers. Rajat is a weak students as far as mathematics is concerned and his teacher gave lots of problem sets to find the means. Please help rajat with his homework.
Note:- Truncate the Fraction Part of result.
Input
First Line... | t = input();
while(t > 0):
n = input(); cp = n; s = 0;
while(n > 0):
no = input(); s += no;
n -= 1;
print s / cp;
t -= 1; |
Chintu and Mintu are good friends and they have so many coins of different amount so they decided to play a game using a stack consisting of N coins.
In this game, anyone can alternatively remove 1, 2 or 3 from the top, and the amount on the removed coins are added to their score.
Players have to play so that they o... | import sys
t = int(sys.stdin.readline())
def solve(xs):
xn = len(xs)
ss = [(0, 0)]
for ix in range(xn):
eix = xn - ix - 1
best = None
for dx in (1, 2, 3):
if eix + dx > xn:
continue
p = sum(xs[eix:eix + dx])
a, b = ss[ix + 1 - dx]... |
From the childhood we are taught that a comes before b then b comes before c and so on.So whenever we try to sort any given string we sort it in that manner only placing a before b and so on.But what happens if we initially change the pattern of sorting .This question arrived in Arav's young mind. He thought what woul... | n = int(input())
for _ in range(n):
key = raw_input()
st = raw_input()
freq = [0 for i in range(26)]
for s in st : freq[ord(s)-ord('a')]+=1;
ans = ""
for i in key:
ans+=i * freq[ord(i)-ord('a')]
print(ans) |
There are K lemurs on Madagascar and Kevin has N bananas. He has to give away all his bananas to lemurs. Lemurs are happy if all of them get the same number of bananas (even if they don't get any). In one minute Kevin can do one of the following:
Find one banana.
Discard one banana (eat).
Increase a population of ... | s=f=1000000
n,k=map(int,raw_input().split())
if(n%k==0):
print 0
else:
j=k
for i in range(1000000):
a=n//k
b=(n//k)+1
x=b*k-n
y=n-(a*k)
g=min(x,y)
d=k-j
if((g+d)<f):
f=g+d
#print g,d
k+=1
k=j
for l in range(1000000):
#print "tatti"
if k<=0:
break
#print k
a=n//k
b=(n//k)+1
x=(... |
A palindrome is a word that reads the same forward and backward. Given a string s, you need to make it a palindrome by adding 0 or more characters to the end of s, and remember, we want the palindrome to be as short as possible.
INPUT
First line is T, the number of test cases.
T strings follow, every string s needs ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n = int(raw_input())
i = 0
pal = ""
while i < n:
try:
s = raw_input()
except (EOFError):
break
if s == s[::-1]:
print len(s)
continue
j = 1
while j <= len(s):
pal = ... |
Shinchan and Kazama both are playing with numbers. Shinchan gives Kazama an array of numbers and asks him to tell the minimum possible last number of a non decreasing sequence of length L.
Note- Check the sample I/O for more clarity.
INPUT-
Input consists of number of test cases T. Each test case contains size of a... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def binarysearch(arr,target):
if target<=arr[0]:
return 0
if target>=arr[-1]:
return len(arr)-1
low=0
high=len(arr)-1
while low<=high:
mid=(l... |
Russian Translation Available
It is very important to understand relationship between variables to draw the right conclusion from a statistical analysis. The relationship between variables determines how the right conclusions are reached. Without an understanding of this, you can fall into many pitfalls that accompany... | import collections
import heapq
MOD = 1000000007
def mst(graph, n):
total = 1
seen = set([1])
q = graph[1]
heapq.heapify(q)
while q:
cost, node = heapq.heappop(q)
if node in seen: continue
seen.add(node)
total = (total * cost) % MOD
if len(seen) == n: break
... |
Shil decided to go for hill climbing on this weekend, but he doesn't have the map of all the hills. However, he's smart enough to make his own map.
There are N hills arranged on a line, each in the form of a vertical line segment with one endpoint on the ground. The hills are numbered with numbers from 1 to N from ... | n=input()
hills=[]
for _ in range(n):
hills.append(map(int,raw_input().split()))
count=0
for a in range(n):
x1=hills[a][0]
y1=hills[a][1]
mcurr=(100000000,1)
for b in range(a+1,n):
#if (hills[b][0]-hills[a][0]>10000):
# break
#if hills[b][1]>hills[a][1]:
# count+=1
#print a,b
# break
x2=hills[b][0]... |
Tanmay is a legendary spammer - everyone in the spamming world knows and admires his abilities to spam anyone, anytime, anywhere. He decided to guide one of his mentors, named Arjit, as part of the Apex body of spamming.
Tanmay has no doubts on his skills of teaching and making his mentor, Arjit, learn about the art ... | def prod(xs):
p = 1
for x in xs:
p *= x
return p
def solve(xs):
negatives = sorted(x for x in xs if x < 0)
positives = sorted(x for x in xs if x > 0)
zeros = [0] if 0 in xs else []
if len(negatives) % 2 == 0: maxi = negatives + positives
else: maxi = negatives[:-1] + positives
... |
Zeke loves to spend time with Penny and likes her. Penny is having an issue to solve a mathematics problem and is confused. She seeks Zeke's help as she feels he could help her with the problem. He finds this problem very simple. The problem is to count the number of unique triplets of different numbers (N1, N2, N3), w... | for _ in range(int(raw_input())):
a = sorted(map(int, raw_input().split()))
ans = a[0]
for i in range(1, 3):
a[i] -= i
if a[i] < 1:
ans = 0
ans *= a[i]
print ans % 1000000007 |
Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.
For a non-empty subset T of the set \\{1, 2, \ldots , N \\}, let us define f(T) as follows:
* f(T) is the number of different non-empty subsets \\{x_1, x_2, \ldots , x_k \\} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k}... | N, S = map(int, input().split())
A = list(map(int, input().split()))
mod = 998244353
L = [[0 for i in range(S+1)] for j in range(N+1)]
L[0][0] = 1
for j, a in enumerate(A):
for i in range(S+1):
if i < a:
L[j+1][i] = (2 * L[j][i]) % mod
else:
L[j+1][i] = (2 * L[j][i] + L[j][i-a]) % mod
print(L[N][S... |
Given is a permutation P_1, \ldots, P_N of 1, \ldots, N. Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:
* For any integer j (1 \leq j \leq i), P_i \leq P_j.
Constraints
* 1 \leq N \leq 2 \times 10^5
* P_1, \ldots, P_N is a permutation of 1, \ldots, N.
* All values in input are ... | #include<bits/stdc++.h>
using namespace std;
int n,r,x,m=0x3f3f3f3f;
int main()
{
cin>>n;
for(int i=1;i<=n;i++,r+=(m>x),m=min(m,x))cin>>x;
cout<<r;
return 0;
} |
Today is August 24, one of the five Product Days in a year.
A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day):
* d_1 \geq 2
* d_{10} \geq 2
*... | import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int M = sc.nextInt();
int D = sc.nextInt();
int count = 0;
for(int i = 1; i <= M; i++... |
There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.
You can perform the following operation on this integer sequence any number of times:
Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.
Let B_1, B_2, ..., B_N be the integer sequence after your ... | import java.util.*;
import java.lang.*;
public class Main {
static long mod = 998244353;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] a = new long[n];
int count = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
if (a[i] < 0) {
c... |
In some other world, today is December D-th.
Write a program that prints `Christmas` if D = 25, `Christmas Eve` if D = 24, `Christmas Eve Eve` if D = 23 and `Christmas Eve Eve Eve` if D = 22.
Constraints
* 22 \leq D \leq 25
* D is an integer.
Input
Input is given from Standard Input in the following format:
D
... | D = int(input())
a = "Christmas"
print(a + " Eve"*(25-D)) |
You are given a string s. Among the different substrings of s, print the K-th lexicographically smallest one.
A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = `ababc`, `a`, `bab` and `ababc` are substrings of s, while `ac`, `z` and an empty string are not. Also,... | #include <iostream>
#include <set>
using namespace std;
int main(void) {
string s;
int k;
cin >> s >> k;
set<string> st;
for (int i = 0; i < s.size(); ++i) {
string subs;
for (int j = i; j < s.size(); ++j) {
subs += s[j];
if (subs.size() > k) break;
st.insert(subs);
}
}
int cnt = 0;
for (auto x :... |
There are N islands floating in Ringo Sea, and M travel agents operate ships between these islands. For convenience, we will call these islands Island 1, 2, …, N, and call these agents Agent 1, 2, …, M.
The sea currents in Ringo Sea change significantly each day. Depending on the state of the sea on the day, Agent i (... | #include <bits/stdc++.h>
using namespace std;
using lint = long long;
template<class T = int> using V = vector<T>;
template<class T = int> using VV = V< V<T> >;
template<unsigned P> struct ModInt {
using M = ModInt;
unsigned v;
constexpr ModInt() : v(0) {}
constexpr ModInt(unsigned _v, int) : v(_v) {}
templa... |
You are given an integer sequence of length n, a_1, ..., a_n. Let us consider performing the following n operations on an empty sequence b.
The i-th operation is as follows:
1. Append a_i to the end of b.
2. Reverse the order of the elements in b.
Find the sequence b obtained after these n operations.
Constraints... | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from collections import deque
N,*A = map(int,read().split())
B = deque()
reverse = False
for x in A:
if reverse:
B.appendleft(x)
else:
B.append(x)
reverse = not reverse
B =... |
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the ... | N,A,B = map(int,input().split())
X = [int(x) for x in input().split()]
ans = 0
for i in range(1,N):
d = X[i]-X[i-1]
ans += min(A*d, B)
print(ans) |
There are N arrays. The length of each array is M and initially each array contains integers (1,2,...,M) in this order.
Mr. Takahashi has decided to perform Q operations on those N arrays. For the i-th (1≤i≤Q) time, he performs the following operation.
* Choose an arbitrary array from the N arrays and move the intege... | from sys import stdin
from itertools import repeat
def main():
n, m = map(int, stdin.readline().split())
q = int(stdin.readline())
a = map(int, stdin.readline().split(), repeat(10, q))
a = [x - 1 for x in a]
l = [[] for i in xrange(m)]
la = []
for i in xrange(q - 1, -1, -1):
x = a[i]... |
Internet search engines, such as Google, automatically sort and categorize web pages around the world to create a huge database. It also parses the search keywords entered by the user and creates an inquiry statement for database search.
In each case, complicated processing is performed to realize efficient search, bu... | code = str(raw_input())
code = code.replace(",","")
code = code.replace(".","")
code = code.split()
list = []
for var in code:
if len(var) >= 3 and len(var) <= 6:
list.append(var)
for var in list:
print var, |
Mr. Matsudaira is always careful about eco-friendliness in his life. Last month's water charge was 4280 yen, which exceeded the usual target of 4000 yen, so we have been trying to save water this month. How much have you saved on your water bill compared to last month?
Enter this month's water usage w [m3] and create ... | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
for(int w;cin>>w,~w;){
int p=1150; w-=min(w,10);
p+=125*min(w,10); w-=min(w,10);
p+=140*min(w,10); w-=min(w,10);
p+=160*w;
cout<<4280-p<<endl;
}
return 0;
} |
It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed.
When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate ... | #include<bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin >> a >> b;
cout << abs(b-a) << endl;
return 0;
}
|
On a clear night, a boy, Campanella looked up at the sky, there were many stars which have different colors such as red, yellow, green, blue, purple, etc. He was watching the stars and just lost track of time. Presently, he wondered,
| <image>
---|---
"There are many stars in the space. What color is the universe if... | #include<stdio.h>
#include<map>
int main()
{
int n,x,i,f;
while(scanf("%d",&n),n)
{
typedef std::map<int,int>M;
M m;
for(f=i=0;i<n;++i)scanf("%d",&x),m[x]++;
for(M::iterator t=m.begin();t!=m.end();++t)
if(t->second>n/2)f=printf("%d\n",t->first);
if(!f)puts("NO COLOR");
}
return 0;
} |
Today is the birthday of Mr. Bon Vivant, who is known as one of the greatest patissiers in the world. Those who are invited to his birthday party are gourmets from around the world. They are eager to see and eat his extremely creative cakes. Now a large box-shaped cake is being carried into the party. It is not beautif... | #include<algorithm>
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
typedef struct
{
int x,y;
}rect;
int area(rect r)
{
return r.x * r.y;
}
int main()
{
while(1)
{
int n,w,h;
cin >> n >> w >> h;
if(n == 0&&w == 0&&h == 0)break;
vector<rect> v;
v.resize(1);
v[0].x = w;... |
The amount of information on the World Wide Web is growing quite rapidly. In this information explosion age, we must survive by accessing only the Web pages containing information relevant to our own needs. One of the key technologies for this purpose is keyword search. By using well-known search engines, we can easily... | #include<iostream>
#include<cstring>
using namespace std;
#define REP(i, N) for(int i = 0; i < (int)(N); i++)
bool dp[32][1 << 12];
int main() {
for(int N, M; cin >> N >> M, (N || M); ) {
string str;
string word[12];
REP(i, N) cin >> word[i];
REP(i, M) {
string s;
cin >> s;
str += s;
}
int len =... |
Problem
At a certain arcade, there is a game of playing Japanese drums according to the musical score that flows along with the song. The score consists of cells of length L, and each cell has a blank or note, a symbol that represents the action the player should take. There are two types of notes, each with a "ton" t... | #include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
typedef vector<double> vec;
typedef vector<vec> vec2;
typedef vector<vec2> vec3;
typedef vector<vec3> vec4;
template<class T> inline void chmax(T& a, T b) { if(b > a) a = b; }
enum { LT, RT, LK, RK, NONE };
int main() {... |
Peace, which was supposed to last forever, suddenly ended. The Demon King, who had been sealed long ago, has finally revived. But when the world was about to be covered in darkness, a brave man appeared. The hero then set out on a journey to collect legendary crystals scattered around the world. Legend has it that if y... | #define DEBUG_ON
#define CONDITION true
using namespace std;/*{{{*/
#include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <iterator>
#include <list>
#include ... |
You are a programmer working for your local city hall. The town you live in has a thriving tourism industry, especially the beaches on the shores of remote islands. The area around this island is composed of sandy beaches, but in recent years the area of the sandy beaches has decreased due to coastal erosion. The Tou... | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-6;
int n;
double r;
P[] ps;
void run(){
f... |
A robot in a two-dimensional maze again. The maze has an entrance and an exit this time, though.
Just as in the previous problem, the maze is made up of H × W grid cells, its upper side faces north, and each cell is either empty or wall. Unlike the previous, on the other hand, one of the empty cells is connected to th... | #include<queue>
#include<cstdio>
#include<cstring>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
const int INF=1<<29;
const int dx[]={1,0,-1,0},dy[]={0,-1,0,1};
struct Stat{
int x,y,d; // d : ̽ßÔ
bool operator<(const Stat &S)const{ return d>S.d; }
};
int main(){
for(int h,w,n;scanf("%d%d... |
Problem A: Approximate Circle
Consider a set of n points (x1, y1), ..., (xn,yn) on a Cartesian space. Your task is to write a program for regression to a circle x2 + y2 + ax + by + c = 0. In other words, your program should find a circle that minimizes the error. Here the error is measured by the sum over square dista... | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
// Approximate Circle
public class Main{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-12;
int n;
double[] xs, ... |
There are n cities and n − 1 roads, which are trees. Cities are numbered from 1 to n. When city 1 is taken as the root, the parent of city i is pi, and the distance between i and pi is di. Sunuke wants to solve the following problem for each k of 1 or more and n or less.
Minimum value of the sum of the distances from ... | #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
... |
Example
Input
1 10 2
1 1 1
Output
2.0 | #include <bits/stdc++.h>
#define ll long long
#define INF (1LL << 60)
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i)
#define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i)
#define each(a,b) for(auto& (a): (b))
#define all(v) (v).beg... |
K: Relief (Angel Relief)
Tenma, an angel, decides to save a city.
The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with houses in each parcel.
The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $.
The house in parc... | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#include <functional>
#include <map>
using namespace std;
long long H, W, A[509][509], sum;
int main() {
cin >> H >> W;
for (int i = 1; i <= H; i++) {
for (int j = 1; j <= W; j++) {
cin >> A[i][j];
... |
Problem
There are $ N $ bus stops clockwise, numbered from $ 1 $ to $ N $ in a circle. Adjacent bus stops are connected by a road. For each $ i \ (1 \ le i \ le N) $, the length of the direct connection between the bus stop $ i $ and the bus stop $ i + 1 $ is $ d_i $ meters. However, bus stop $ N + 1 $ means bus stop ... | #include <iostream>
#include <vector>
#include <algorithm>
#define llint long long
#define inf 1e18
using namespace std;
typedef pair<llint, llint> P;
struct LiChaoTree{
int size;
vector<P> seg;
vector<llint> x;
LiChaoTree(){}
LiChaoTree(int size){
this->size = size;
seg.resize(1<<(size+1));
x.resize(1... |
For given a circle $c$ and a line $l$, print the coordinates of the cross points of them.
Constraints
* $p1$ and $p2$ are different
* The circle and line have at least one cross point
* $1 \leq q \leq 1,000$
* $-10,000 \leq cx, cy, x1, y1, x2, y2 \leq 10,000$
* $1 \leq r \leq 10,000$
Input
The input is given in the... | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
#include <cstring>
#include <utility>
#include <numeric>
#include <complex>
#include <iomanip>
using namespace std;
// common
#define X real()
#define Y imag()
using Vector2 = complex<double>;
using Line = pair<Vector2, Vec... |
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique.
* insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation.
* find($x$): Report the number of $x$ in $S$ (0 or 1).
* delete($x$): Delete $x$ from $S$.
Constraints
... | #include <cstdio>
#include <utility>
#include <unordered_set>
using namespace std;
#define gcu getchar_unlocked
#define pcu putchar_unlocked
#define _T template <typename T>
#define _HT template <typename H, typename... T>
#define _il inline
#define _in _il int in
#define _sc _il bool scan
_T T in(int c){T n=0;bool m=... |
Zombies zombies everywhere!!
In a parallel world of zombies, there are N zombies. There are infinite number of unused cars, each of same model only differentiated by the their colors. The cars are of K colors.
A zombie parent can give birth to any number of zombie-children (possibly zero), i.e. each zombie will have... | mod = 10 ** 9 + 7
def powmod(n, p):
if p == 0:
return 1
if p == 1:
return n % mod
if p % 2 == 1:
return n * powmod(n, p - 1) % mod
x = powmod(n, p / 2) % mod
return x * x % mod
t = int(raw_input())
for i in xrange(t):
n, k = map(int, raw_input().split())
print k * powmod... |
Jagjit Singh (Jaggi) is among the few fastest athletes of Thapar. Just before the Thapar Olympics he thought of a new way to practice. He decided he will run in intervals. In each interval , he will run at a particular speed. You have to calculate the total distance traveled by him, given the speed M and time S for eac... | import sys
t=sys.stdin.readline()
t=int(t)
for k in range(0,t):
n=sys.stdin.readline()
n=int(n)
d=0
for i in range(0,n):
string=sys.stdin.readline()
t,s=string.split(" ")
t=int(t)
s=int(s)
d=d+t*s
print d |
Alice's school is planning to take some students from her class on a field trip. Alice is really excited about it. There are a total of S students in her class. But due to budget constraints, the school is planning to take only N students for the trip. These students will be picked randomly. And each student has equal ... | nCr = [[0 for x in xrange(1001)] for x in xrange(1001)]
for i in range (0,1001):
nCr[i][0]=1
nCr[i][i]=1
for i in range (1,1001):
for j in range (1,1001):
if i!=j:
nCr[i][j] = nCr[i-1][j] + nCr[i-1][j-1]
t=input()
for _ in range(0,t):
s,n,m,k=map(int,raw_input().split(' '))
y=0
... |
Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Let Fd(x) equals to the number of digits d in decimal representation of the positive integer x. Chef... | #codechef feb long quest
M=[0]*100001
A=[0]*100001
M[0]=1
s4=0
s7=0
ret=0
for el in range(1,100001):
n=el
while n>0:
k=n%10
if(k==4):s4+=1
if(k==7):s7+=1
n=n/10
ret+=M[s4-s7]
A[el]=ret
M[s4-s7]+=1
t=int(raw_input())
for i in range(t):
n=int(raw_input())
print(... |
Damian Wayne and Carrie Kelly are classmates and best friends. Since class 5, they have been in the same section. They usually sat on the last bench so that they could chat all they want during the class. One day, during the ancient martial arts period, Master Kirigi caught them and asked Damian to sit in the first ben... | a=input()
for i in range(a):
b=raw_input()
string=""
for j in b:
k=ord(j)
if(48<=k<=57):
string+=chr(k+57)
elif(97<=k<=104):
string+=chr(k+18)
elif(105<=k<=114):
string+=chr(k-57)
elif(115<=k<=122):
string+=chr(k-18)
else:
string+=j
print string |
ABC School is organising a sporting event. But they don’t know which game they should take up, so that every person can be divided in equally-sized teams with no one left over. Now, the school consists of various classes. You are given an array ‘A’ consisting of strength of these classes. Assuming a game of every possi... | for b in range(input()):
c = input()
d = map(int,raw_input().split())
d.sort()
for k in range(d[0],0,-1):
for l in d:
if l % k == 0:
flag = 1
else:
flag = 0
break
if flag == 1:
print k
break |
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex 1, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, whi... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const long long mod = (int)1e9 + 7;
const int N = 1e6 + 100;
int n;
int op[N];
int ok[N];
int val[N];
int ans[2];
char s[10];
vector<int> son[N];
void dfs(int u) {
if (op[u] == 4) return;
for (int i =... |
You are given an acyclic directed graph, consisting of n vertices and m edges. The graph contains no multiple edges and no self-loops.
The vertex is called a source if it has no incoming edges. The vertex is called a sink if it has no outgoing edges. These definitions imply that some vertices can be both source and si... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000000, M = 20;
int n, m;
struct side {
int y, next;
} e[N * 2 + 9];
int lin[N + 9], cs;
void Ins(int x, int y) {
e[++cs].y = y;
e[cs].next = lin[x];
lin[x] = cs;
}
int in[N + 9], out[N + 9];
void into() {
scanf("%d%d", &n, &m);
for (int i = 1; i ... |
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes... |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Property> list = new Arr... |
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.
Chouti remembered that n persons took part in that party. To make the party funnier, each person wore one hat among n kinds of ... | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5, MOD = 998244353;
pair<long long, long long> c[N];
long long a[N], b[N];
unordered_map<long long, long long> m;
signed main() {
long long n;
cin >> n;
for (long long i = 1; i <= n; i++) {
cin >> a[i];
c[i] = {a[i], i};
}
sort(c ... |
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features n problems of distinct difficulty, the difficulties are numbered from 1 to n.
To hold a round Arkady needs n new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems... | import java.io.*;
import java.util.*;
public class Main{
static class Re
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Re()
{
din = new DataInputStream(Syste... |
Suppose you are given a string s of length n consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.
To compress the string, you have to represent s as a concatenation of several non-empty strings: s = t_{1} t_{2} … t_{k}. The i-th of these strings should be encode... | import java.io.*;
import java.util.*;
public class Main {
private void solve() throws Exception {
n = nextInt();
a = nextLong();
b = nextLong();
s = nextToken();
memo = new Long[n];
out.println(doit(0));
}
Long[] memo;
long a;
long b;
int n;
... |
You are given an array which is initially empty. You need to perform n operations of the given format:
* "a l r k": append a to the end of the array. After that count the number of integer pairs x, y such that l ≤ x ≤ y ≤ r and \operatorname{mex}(a_{x}, a_{x+1}, …, a_{y}) = k.
The elements of the array are nume... | #include <bits/stdc++.h>
using ll = long long;
const int MN = 2e5 + 100;
int N;
struct node {
public:
node *l, *r;
ll v, z;
node() : l(nullptr), r(nullptr), v(0LL), z(0LL){};
};
const int pool_sz = 50000;
node *pool;
int pool_ctr;
node *nn(node *p = nullptr) {
if (!pool_ctr) pool = new node[pool_ctr = pool_sz]... |
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.
In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows:
<image>
Each pipe segment has two ends, illustrated ... |
import java.math.BigInteger;
import java.util.Scanner;
public class Plumber
{
static final int MOD = 1000003;
static final int EMPTY = 0;
static final int UP = 1;
static final int DOWN = 2;
static final int LEFT = 4;
static final int RIGHT = 8;
static final int UL = UP|LEFT;... |
You are given n numbers a_1, a_2, ..., a_n. In one operation we can add to any one of those numbers a nonnegative integer power of 2.
What is the smallest number of operations we need to perform to make all n numbers equal? It can be proved that under given constraints it doesn't exceed 10^{18}.
Input
The first line... | #include <bits/stdc++.h>
using namespace std;
long long a[100010], M;
int f[70][100010], n, p1[100010], p[100010], as = 1e9 + 1, m;
bool Cmp(int x, int y) { return (a[x] % M > a[y] % M); }
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
memset(f, 31, sizeof(f));
int nm = 0;
fo... |
You are given an array a consisting of 500000 integers (numbered from 1 to 500000). Initially all elements of a are zero.
You have to process two types of queries to this array:
* 1 x y — increase a_x by y;
* 2 x y — compute ∑_{i ∈ R(x, y)} a_i, where R(x, y) is the set of all integers from 1 to 500000 which hav... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class P1207F {
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = 500000;
int sqrt = (in... |
Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.
The tree in question is a rooted tree with n vertices labelled with distinct integers from 0 to n - 1. The vertex ... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 50;
int fa[MAXN], p[MAXN], high[MAXN], a[MAXN], n, cnt = 0;
vector<int> e[MAXN], ans;
inline int read() {
int res = 0;
char ch;
ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) {
res = (res << 3) + (res << 1) + ch... |
You are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.
Input
The first line contains integers n and k — the number and digit capacity of numbers cor... | #include <bits/stdc++.h>
using namespace std;
char arr[10][10];
char my[10][10];
int n, k;
int ans = 1000000000;
int getLen() {
int mi = 1000000000, ma = 0;
for (int i = 0; i < n; i++) {
int num = 0;
int st = 1;
for (int j = k - 1; j >= 0; --j) {
num += st * arr[i][j];
st *= 10;
}
if... |
You are given a cactus graph, in this graph each edge lies on at most one simple cycle.
It is given as m edges a_i, b_i, weight of i-th edge is i.
Let's call a path in cactus increasing if the weights of edges on this path are increasing.
Let's call a pair of vertices (u,v) happy if there exists an increasing path t... | #include <bits/stdc++.h>
using namespace std;
void read(int &x) {
char ch = getchar();
x = 0;
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar();
}
const int N = 5e5 + 5, M = N << 1;
int n, m, num, dfn[N], fa[N], up[N], dp[N], f[N];
int cnt, c, mx[N], mn[N], q[M], in[N... |
You are given n pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion:
1. Start at the origin (0, 0).
2. Choose a vector and add the segment of the vector to the current point. For example, if your current point is at (x, y) and... | #include <bits/stdc++.h>
using namespace std;
constexpr int mod = 998244353;
int x[5], y[5];
int px[32], nx[32], py[32], ny[32];
int dp[32][20][20][20][20][2][2];
void add(int& x, const int& y) {
x += y;
if (x >= mod) x -= mod;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
... |
You are given two positive integers a and b.
In one move, you can change a in the following way:
* Choose any positive odd integer x (x > 0) and replace a with a+x;
* choose any positive even integer y (y > 0) and replace a with a-y.
You can perform as many such operations as you want. You can choose the sam... | for i in range(int(input())):
a,b=map(int,input().split())
if a==b:
print(0)
elif a<b:
if (b-a)%2==0:
print(2)
else:
print(1)
elif a>b:
if (a-b)%2==0:
print(1)
else:
print(2) |
Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!
Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, i... | #include <bits/stdc++.h>
using namespace std;
int a[512][512];
void solve() {
int n;
cin >> n;
if (n < 3) {
cout << -1;
return;
}
int x = 1;
for (int j = n - 1; j >= 2; j--) {
a[2][j] = x++;
}
for (int i = 3; i <= n; i++) {
a[i][2] = x++;
}
for (int j = 1; j <= n; j++)
if (j != 2... |
You are given a string s such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of s such that it contains each of these three characters at least once.
A contiguous substring of string s is a string that can be obtained from s by removing some (possibly zero) character... | import math
from sys import stdin,stdout
def L():
return list(map(int,stdin.readline().split())) #For array input
def Si():
return sorted(list(map(int,stdin.readline().split()))) #For sorted array
def In():
return map(int,stdin.readline().split()) #For multiple input
def I():
return stdin.readline() #Fo... |
You are given a chessboard consisting of n rows and n columns. Rows are numbered from bottom to top from 1 to n. Columns are numbered from left to right from 1 to n. The cell at the intersection of the x-th column and the y-th row is denoted as (x, y). Furthermore, the k-th column is a special column.
Initially, the ... | #include <bits/stdc++.h>
using namespace std;
int read() {
char c = getchar();
while (!isdigit(c)) c = getchar();
int num = 0;
while (isdigit(c)) num = num * 10 + c - '0', c = getchar();
return num;
}
struct node {
int tag, maxn, cnt = 0;
} nd[1600001];
void pushdown(int p) {
nd[p * 2].tag += nd[p].tag, n... |
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters.
In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal?
In... | for _ in range(int(input())):
#n,k=map(int,input().split())
ll=[0]*26
n=int(input())
bool=True
for _ in range(n):
s=input()
pp=set(s)
for c in pp:
cc=s.count(c)
ll[ord(c)-97]+=cc
# print(ll)
for x in ll:
if x%n!=0 :
bool=False
if bool == True :
print('YES')
... |
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R... | import java.util.*;
import java.io.*;
public class EdB {
public static void main(String[] args) throws Exception{
int num = 998244353;
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integ... |
This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | #include <bits/stdc++.h>
using namespace std;
long long mod = 998244353;
int n, m, a[103][103];
char s[103][103];
vector<int> ans;
int main() {
int t;
cin >> t;
while (t--) {
ans.clear();
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> s[i];
for (int j = 0; j < m; j++) {
a[i][j... |
Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.
There are n trees growing along the river, where Argus tends Io. For this problem, the river ca... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TaskGB2020A {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in... |
You are given a number n (divisible by 3) and an array a[1 ... n]. In one move, you can increase any of the array elements by one. Formally, you choose the index i (1 ≤ i ≤ n) and replace a_i with a_i + 1. You can choose the same index i multiple times for different moves.
Let's denote by c_0, c_1 and c_2 the number o... | #include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin>>n;
int a[n],c0=0,c1=0,c2=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
if(a[i]%3==0)
{
c0++;
}
else if(a[i]%3==1)
{
c1+... |
A permutation is a sequence of n integers from 1 to n, in which all the 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 given four integers n, l, r (1 ≤ l ≤ r ≤ n) and s (1 ≤ s ≤ (n (n+1))/(2)) and asked to find a permutatio... | import java.util.ArrayList;
import java.util.HashSet;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
... |
In some country live wizards. They love to ride trolleybuses.
A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it lea... | import java.io.*;
import java.util.StringTokenizer;
/**
* 167A
* θ(n) time
* θ(n) space
*
* @author artyom
*/
public class _167A implements Runnable {
private BufferedReader in;
private StringTokenizer tok;
private Object solve() throws IOException {
int n = nextInt();
double a = nex... |
Polycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.
Let's call person a a 1-ancestor of person b, if a is the parent of b.
Let's call person a a k-ancestor (k > 1) of person b, if person b ha... | import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.H... |
Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.
Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a ther... | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class C {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("input.txt"));
PrintWriter pw = new PrintWriter(new File("output.txt"));
int n ... |
Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three d... | from sys import stdin
n = int(stdin.readline())
m = stdin.readline()[:-1]
rv = ''
while len(m) > 3:
rv += m[:2] + '-'
m = m[2:]
rv += m
print rv |
Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a1, a2, ..., an of positive integers:
1. Initially, x = 1 and y = 0. If, after any step, x ≤ 0 or x > n, the program immediately terminates.
2. The p... |
import java.io.OutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
/**
*
* @author MEGNAD
*
*/
public class CowProgram {
public static ... |
Polycarpus has got n candies and m friends (n ≥ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such ai, where ai is the number of candies in the i-th friend's prese... | n,m=map(int,input().split())
print(*[n//m+1 if i<n%m else n//m for i in range(m)]) |
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open ... | #include <bits/stdc++.h>
using namespace std;
map<pair<long long, long long>, pair<long long, long long> > mp;
pair<long long, long long> solve(long long N, long long mxd) {
if (N == 0 && mxd == 0) return {0LL, 0LL};
if (N < 10) {
if (mxd == 0) return {1LL, 0LL};
if (mxd > N) return {1LL, N - mxd};
retu... |
You have a directed acyclic graph G, consisting of n vertexes, numbered from 0 to n - 1. The graph contains n edges numbered from 0 to n - 1. An edge with number i connects vertexes i and (i + 1) mod n, and it can be directed in either direction (from i to (i + 1) mod n, or vise versa).
Operation x mod y means taking ... | //package round205;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class E3 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
char[] s = ns().to... |
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number a, the second player wrote number b. How many ways ... | import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int a=in.nextInt();
int b=in.nextInt();
int winA=0,winB=0,draw=0;
if(a==b){
draw=6;
winA=0;
winB=0;
}
if(a>b){
if((a+b)%2==1){
draw=0;
}
else{... |
There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes.
An extraterrestrial intelligence research spec... | #include <bits/stdc++.h>
using namespace std;
int pct(int x) { return __builtin_popcount(x); }
int pct(long long x) { return __builtin_popcountll(x); }
int bt(int x) { return 31 - __builtin_clz(x); }
int bt(long long x) { return 63 - __builtin_clzll(x); }
int cdiv(int a, int b) { return a / b + !(a < 0 || a % b == 0); ... |
Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.
To construct a bi... | #include <bits/stdc++.h>
using namespace std;
int n, m, t, tu, tp, td, pi, pii, pj, pjj;
int U[305][305], D[305][305], L[305][305], R[305][305], a[305][305];
int cal(int x, int y) {
if (x == y) return tp;
return x < y ? tu : td;
}
int main() {
int ans = 0x7fffffff;
scanf("%d%d%d", &n, &m, &t);
scanf("%d%d%d",... |
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One ... | #include <bits/stdc++.h>
using namespace std;
const int N = 100001;
const long long MAX = 123456897213124;
int n, m, k, ans;
vector<pair<int, long long> > a[N];
priority_queue<pair<long long, int> > q;
bool Visited[N];
int main() {
ios_base::sync_with_stdio(0);
cin >> n >> m >> k;
for (int i = 1; i <= m; i++) {
... |
Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.
The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell cont... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
n... |
Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Solve6 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out... |
Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes.
Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m... | #include <bits/stdc++.h>
using namespace std;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr ... |
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns — from left to right with numbers from 1 to m. Let's denote t... | #include <bits/stdc++.h>
using namespace std;
long long powmod(long long a, long long b, long long MOD) {
long long res = 1;
a %= MOD;
for (; b; b >>= 1) {
if (b & 1) res = res * a % MOD;
a = a * a % MOD;
}
return res;
}
struct Point {
int x, y;
Point(int x, int y) {
this->x = x;
this->y =... |
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
<image>
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
... | #include <bits/stdc++.h>
using namespace std;
long long t, a, b, k, mk, ans;
long long gcd(long long x, long long y) {
while (y) {
long long t = x;
x = y;
y = t % y;
}
return x;
}
int main() {
scanf("%I64d%I64d%I64d", &t, &a, &b);
k = gcd(a, b);
mk = 1000000000;
mk *= 5;
if (a / k / mk * (b ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.