input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki... | import java.io.IOException;
import java.math.BigInteger;
import java.util.Locale;
import java.util.Scanner;
public class A {
private void processInput() throws IOException {
Scanner in = new Scanner(System.in);
String str = in.next();
String res = go(str);
System.out.printf(Locale.ENGLISH, "%s\n", res);
... |
This problem is about a little pig named Benny. Benny was given an array of N integers and another separate integer X. Benny has to find the number of subsets (not necessarily contiguous) of A such that Bitwise XOR of all elements contained within the subset evaluates to X.
Probably, you have already guessed that she ... | MOD=10000007
N,X=map(int, raw_input().split())
nums={}
nums[0]=1
arrA=sorted(map(int, raw_input().split()))
for A in arrA:
old=nums.copy()
for num in old:
B=num^A
nums[B]=(old[num]+old[B])%MOD if B in old else old[num]
print nums[X] if X in nums else "0" |
A string is said to be complete if it contains all the characters from a to z. Given a string, check if it complete or not.
Input
First line of the input contains the number of strings N. It is followed by N lines each contains a single string.
Output
For each test case print "YES" if the string is complete, else pri... | mydict={}
for i,each in enumerate("abcdefghijklmnopqrstuvwxyz"):
mydict[each]=i
lettercount = int(raw_input())
for each in range(lettercount):
letters = raw_input()
isexists=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for each in letters:
isexists[mydict[each]]=1
if 0 in isexists:
print "NO"
el... |
Write a command line tool which takes a file path as input and prints the number of lines, number of words, number of characters in the file, userid of the owner of the file, groupid of owner of the file and last modification time of the file in UNIX timestamp format. Please note that a word is identified as sequence o... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
name = raw_input()
if name == "/home/sample.txt":
print 1
print 2
print 13
print 1000
print 1000
print 1258001628
else:
print 19
print 402
print 2612
print 0
print 0
print... |
Ikshu and his machine gun
To celebrate his new year Ikshu went to play "beyond to beyond" (abbreviated as BOB) with his friends.
BOB can be described as follows :
It consists of Infinite boxes arranged one over another, Lowest box being 1.
Given a list 'L' of indices, Ikshu needs to knockoff L[i]th box for 0 ≤ i<|L| w... | n=input()
l=map(int,raw_input().split())
l.sort()
for i in range(n):
print l[i]-i, |
Rahul likes to play with mathematics and geometry and when it comes for 2D geometry, he just can’t stop himself doing experiments. While working with 2D geometry, he came up with an interesting pattern of numbers as shown below.
He started at the point (0, 0) and wrote all non-negative integers. They are-
(0, 0) – 0
... | for _ in range(input()):
a, b = map(int, raw_input().split())[:2]
if a==b or a==b+2:
print (a+b-1) if b%2==1 else (a+b)
else:
print "No Number" |
Guri and Prary are good friends and are chocolate lovers. They win a lottery and get a chance to visit ChocoLand for few minutes.
In ChocoLand, there are N number of chocolate containers kept one next to other, one unit apart. Each of the container contains Ki number of chocolates. Guri and Prary should pack as many c... | n,m=map(int,raw_input().split())
a=[0]+map(int,raw_input().split())
for i in range(1,n+1):
a[i]+=a[i-1]
for i in range(m):
q,w=map(int,raw_input().split())
e,r=map(int,raw_input().split())
if e<q: e,q=q,e
if r<w: r,w=w,r
if r<q: print a[r+1]-a[w]+a[e+1]-a[q]
elif r<=e and w<=q: print a[e+1]-a[w]
elif r<=e: prin... |
Rachel works at a big Raf Laurens. There is a big event coming up and she has to select dresses for an exhibition.
She has N dresses numbered 1 to N. There are total 62 types of dresses, each represented by a different alphanumeric character (a-z, A-Z, 0-9). The N dresses are represented by a string S of length N of al... | for _ in xrange(int(raw_input())):
a = str(raw_input()).split()
N,K,L,R = map(int,a)
dress = str(raw_input())
sp = str(raw_input())
arr = [0]*N
cnt=0
for i in range(N):
if dress[i] in sp:
arr[i] = 1
for i in range(N):
s = arr[i]
if s>=L and s <=R:
cnt +=1
for j in range(i+1,N):
s += arr[j... |
Given a sequence A1 , A2 , A3 .. AN of length N . Find total number of wave subsequences having length greater than 1.
Wave subsequence of sequence A1 , A2 , A3 .. AN is defined as a set of integers i1 , i2 .. ik such that Ai1 < Ai2 > Ai3 < Ai4 .... or Ai1 > Ai2 < Ai3 > Ai4 .... and i1 < i2 < ...< ik.Two subseq... | def readLine(func):
return [func(v) for v in raw_input().strip().split(' ')]
(n) = readLine(int)
arr = readLine(int)
MAX = 100001
MOD = 10**9+7
constTree = [0] * (MAX)
lowTree = [0] * (MAX)
highTree = [0] * MAX
def update(tree, num, val):
while num < MAX:
tree[num] += val
tree[num]%=MOD
... |
Everyone has got to know that HELL and Printf{} use cheats while playing Counter-Strike 1.6. Everyone decides to give them a punishment.
They are going to be made to paint all the rooms of the ground floor of the hostel.
There are a total of N rooms on the ground floor arranged in a single row side by side numbered f... | t=input()
while(t>0):
t-=1
n,k=[int(x) for x in raw_input().split()]
#x = int(input())
#y = int(input())
#n=input()
#k=input()
foo=(10**k-1)*(10**(n-k)-1)
print foo |
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read th... | #include<bits/stdc++.h>
#define ll long long
#define mxn 200005
#define mod 998244353ll
using namespace std;
ll p10[mxn], p11[mxn], lazy[4*mxn], seg[4*mxn];
int N;
void propagate(int n, int s, int e)
{
lazy[n*2]= lazy[n];
lazy[n*2 +1]= lazy[n];
int mid= (s+e)/2;
seg[n*2]= (((p11[mid-s+1]*lazy[n])%mod)*p... |
You start with the number 0 and you want to reach the number N.
You can change the number, paying a certain amount of coins, with the following operations:
* Multiply the number by 2, paying A coins.
* Multiply the number by 3, paying B coins.
* Multiply the number by 5, paying C coins.
* Increase or decrease the num... | #include<cstdio>
#include<map>
#include<algorithm>
using namespace std;
long long c[10];
const long long INF=2e18;
map<long long,long long> dp;
long long dfs(long long x)
{
if(!x)return 0;
if(dp.count(x))return dp[x];
long long tmp[6]={x/2,x/2+1,x/3,x/3+1,x/5,x/5+1},t[6]={2,2,3,3,5,5};
long long ans=INF;for(in... |
We have N cards numbered 1, 2, ..., N. Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side. Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.
Determine whether it is ... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i=0; i<n; i++)
#define pb push_back
#define int long long
int N;
int A[20], B[20];
int dp[1<<20][20];
signed main() {
cin.tie(0); ios::sync_with_stdio(false);
cin >> N;
rep(i, N) cin >> A[i];
rep(i, N) cin >> B[i];
rep(... |
Given is a sequence of N integers A_1, \ldots, A_N.
Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.
Constraints
* 1 \leq N \leq 100
* 1 \leq A_i \leq 1000
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \... | n,a=open(0)
print(1/sum(1/int(i)for i in a.split())) |
There are two buttons, one of size A and one of size B.
When you press a button of size X, you get X coins and the size of that button decreases by 1.
You will press a button twice. Here, you can press the same button twice, or press both buttons once.
At most how many coins can you get?
Constraints
* All values i... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
int sum = 0;
for(int i = 0; i < 2; i++) {
if(A < B) {
sum += B;
B--;
}
else {
sum += A;
... |
You are given an integer N. Among the divisors of N! (= 1 \times 2 \times ... \times N), how many Shichi-Go numbers (literally "Seven-Five numbers") are there?
Here, a Shichi-Go number is a positive integer that has exactly 75 divisors.
Constraints
* 1 \leq N \leq 100
* N is an integer.
Input
Input is given from S... | N = int(input())
e = [0 for _ in range(N + 1)]
for i in range(2, N + 1):
for j in range(2, i + 1):
while i % j == 0:
i //= j
e[j] += 1
c = tuple(filter(lambda x: x > 0, e)) # 素因数の指数
dp = [[0 for _ in range(75 + 1)] for _ in range(len(c) + 1)] # dp[素因数のidx][約数の個数] = 条件を満たす個数
dp[0... |
Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions:
* a_i (1 \leq i \leq N) is a prime number at most 55 555.
* The values of a_1, a_2, ..., a_N are all different.
* In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite n... | #include <iostream>
#include <math.h>
using namespace std;
bool IsPrime(int x){
if(x==2)return true;
if(x%2==0)return false;
for(int i=3;i<=sqrt(x);i+=2){
if(x%i==0)return false;
}
return true;
}
int n;
int main(){
cin>>n;
int x=0;
for(int i=2;x<n;i+=5){
if(IsPrime(i)){... |
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the ... | #include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<string>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll, int> pli;
const int MX = 1<<19;
ll ans[MX];
vector<pii> T[MX];
int cn... |
Snuke is playing a puzzle game. In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}).
The objective is to draw a curve connecting the pair of points where the same integer i... | import sys
def main():
# res = []
inps = map(lambda s: s.strip(), sys.stdin.readlines())
iid = 0
r, c, n = map(int, inps[iid].split())
iid += 1
def boundary(x,y):
if x==0 or y==0 or x==r or y==c:
return True
return False
def downright(x, y):
if x==0 or ... |
Snuke has a calculator. It has a display and two buttons.
Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:
* Button A: When pressed, the value on the display is incremented by 1.
* Button ... | import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
long x = sc.nextLong();
long y = sc.nextLong();
sc.close();
long abs = Math.abs(Math.abs(x) - Math.abs(y));
if(x * y < 0 || (x == 0 && y < 0) || (y == 0 && x > 0)){
System... |
We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:
* There is at least one red block and at least one blue block.
* The union of all red blocks forms a rectangular parallelepiped.
* The union of all blue blocks for... | #include<iostream>
#include<algorithm>
using namespace std;
long long a[3];
int main(){
cin>>a[0]>>a[1]>>a[2];
sort(a,a+3);
cout<<((a[0]&1&a[1]&1&a[2]&1)?a[0]*a[1]:0)<<endl;
} |
There is a "cloth" of 10 × 10 squares as shown in Fig. 1, and the squares are indicated by a pair of X-coordinate and Y-coordinate values as shown in (1 and 2). The coordinate value is an integer starting from 0. For example, the coordinates of ◎ in Figure 1 are (1, 2). Dye is made by adding dye to this "cloth" littl... | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb emplace_back
#define INF (1e9+1)
vector<pii> ansa, ansb, ansc;
int cc = 0;
bool allZero(vector<vector<int>> v){
rep(i,10){
... |
Takayuki and Kazuyuki are good twins, but their behavior is exactly the opposite. For example, if Takayuki goes west, Kazuyuki goes east, and if Kazuyuki goes north, Takayuki goes south. Currently the two are in a department store and are in different locations. How can two people who move in the opposite direction mee... | //Shuncha's code???
#include "bits/stdc++.h"
typedef struct {
int ax, ay, bx, by, cnt;
} TWIN_t;
TWIN_t queue[300000];
int head, tail;
void enq(TWIN_t t)
{
queue[(tail++) % 300000] = t;
}
void deq(TWIN_t *t)
{
*t = queue[(head++) % 300000];
}
int main(void)
{
TWIN_t first, temp;
int x, y,... |
A mysterious device was discovered in an ancient ruin. The device consists of a disc with integers inscribed on both sides, a bundle of cards with an integer written on each of them and a pedestal within which the cards are placed. The disc rotates when the bundle of cards is put into the pedestal. Only one side of the... | #include<bits/stdc++.h>
using namespace std;
using UL = unsigned int;
using ULL = unsigned long long;
using LL = long long;
#define rep(i, n) for(UL i = 0; i < (n); i++)
UL K, N, Q;
struct RMQ {
UL N;
vector<pair<UL, UL>> V;
static pair<UL, UL> F(pair<UL, UL> l, pair<UL, UL> r) {
if (l.second) r.first = K - r.f... |
What you have in your hands is a map of Aizu-Wakamatsu City. The lines on this map represent streets and the dots are street corners. Lion Dor Company is going to build food stores at some street corners where people can go to buy food. It is unnecessary and expensive to build a food store on every corner. Their plan i... | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
static int ans = 0;
static ArrayList<ArrayList<Integer>> g;
static int x;
public static void main(String[] args) throws Exception {
while (true) {
x = sc.nextInt();
int y = sc.nextInt();... |
Let's play a game using a robot on a rectangular board covered with a square mesh (Figure D-1). The robot is initially set at the start square in the northwest corner facing the east direction. The goal of this game is to lead the robot to the goal square in the southeast corner.
<image>
Figure D-1: Example of a boar... | #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> >;
struct Edge { int to, cost; };
template<class T, class Edge> V<T> dijkstra(const VV<Edge>& g, int s = 0) {
V<T> dist(g.size(), numeric_limits<T>::max());
... |
Numbers of black and white points are placed on a plane. Let's imagine that a straight line of infinite length is drawn on the plane. When the line does not meet any of the points, the line divides these points into two groups. If the division by such a line results in one group consisting only of black points and the ... | //Hello. I'm Peter.
//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<cctype>
#include<ctime>
#include<stack>
#include<queue>
#include<vector... |
Problem
You decide to play a weird game with your friend A, who loves gathering.
Given a set S of non-negative integers consisting of n elements that can be duplicated. Each element contained in the set S is a non-negative pi-ary number. With Steps 1 to 3 below as one turn for the set S, you and your opponent repeat ... | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0; i<(int)(n); ++i)
using namespace std;
typedef long long LL;
inline int toint(char c){
if(isdigit(c)) return c - '0';
else if(isupper(c)) return c - 'A' + 10;
else if(islower(c)) return c - 'a' + 36;
}
int main(){
int n;
while(cin >> n){
... |
Square Route
Square root
English text is not available in this practice contest.
Millionaire Shinada, who has decided to build a new mansion, is wondering in which city to build the new mansion. To tell the truth, Mr. Shinada is a strange person who likes squares very much, so he wants to live in a city with as many... | #include<bits/stdc++.h>
using namespace std;
#define reps(i,f,n) for(int i=f;i<int(n);i++)
#define rep(i,n) reps(i,0,n)
const int N = 1600;
int h,w;
int A[N];
int B[N];
void init(){
}
bool input(){
cin>>h>>w;
if(h==0)return 0;
rep(i,h)cin>>A[i];
rep(i,w)cin>>B[i];
return true;
}
int solve(){
int C[... |
A country Gizevom is being under a sneak and fierce attack by their foe. They have to deploy one or more troops to every base immediately in order to defend their country. Otherwise their foe would take all the bases and declare "All your base are belong to us."
You are asked to write a program that calculates the min... | #include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
vector<int>E[100];
bool used[200];
int match[200];
bool dfs(int u) {
used[u] = true;
for (int v : E[u]) {
int w = match[v];
if (w == -1 || (!used[w] && dfs(w))) {
match[u] = v; match[v] = u;
return true;
}
}
return fal... |
All space-time unified dimension sugoroku tournament. You are representing the Earth in the 21st century in the tournament, which decides only one Sugoroku absolute champion out of more than 500 trillion participants.
The challenge you are currently challenging is one-dimensional sugoroku with yourself as a frame. Sta... | #include <algorithm>
#include <iostream>
#define INF (1e9)
#define N 100001
using namespace std;
int main(){
int n,p[N],dp[N];
cin>>n;
for(int i=0;i<n;i++) cin>>p[i];
for(int i=0;i<n;i++) dp[i]=INF;
dp[n-1]=0;
for(int i=n-1;i>=0;i--){
if(p[i]>0) dp[i]=min(dp[i],dp[i+p[i]]);
if(!p[i])
for(int ... |
Problem I: Train King
Roland has been given a mission of dangerous material transfer by Train King. The material is stored in the station A and subject to being transferred to the station B. He will bring it by direct trains between A and B, one (or zero) unit per ride.
Your task is to write a program to find out the... | #include <bits/stdc++.h>
#define FOR(i,a,b) for(int i= (a); i<((int)b); ++i)
#define RFOR(i,a) for(int i=(a); i >= 0; --i)
#define FOE(i,a) for(auto i : a)
#define ALL(c) (c).begin(), (c).end()
#define RALL(c) (c).rbegin(), (c).rend()
#define DUMP(x) cerr << #x << " = " << (x) << endl;
#define SUM(x) std::accumulate... |
A robot, a wall, and a goal are installed on the board, and a program that describes the behavior pattern of the robot is given.
The given program is represented by the following EBNF.
Program: = {statement};
Statement: = if statement | while statement | action statement;
if statement: = "[", condition, program, "]"... | #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps=1e-9;
const int dx[4] = { -1,0,1,0 };
const int dy[4] = { 0,1,0,-1 };
vector<vector<int>>field;
int memo[5... |
This issue is a reactive issue. It is necessary to create a program that derives the correct answer by interactively responding to the program prepared on the server side.
Example
Input
Output | #include <bits/stdc++.h>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int ans=0;
for(int i=0;i<n;i++){
cout <<"lst "<<i<<endl;
int a,b;
cin>>a;
for(int i=0;i<a;i++) cin>>b;
ans+=a*(a-1);
}
cout <<"ans "<<ans<<endl;
return 0;
} |
C: Divisor Game
problem
tsutaj is trying to play about a few games.
In a divisor game, a natural number N of 2 or more is given first, and then the game progresses according to the following procedure.
* Declare one integer from the divisors of N other than N. However, at this time, it is not possible to declare a ... | // need
#include <iostream>
#include <algorithm>
// data structure
#include <bitset>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <complex>
//#include <deque>
#include <valarray>
#include <unordered_map>
#include <unordered_set>
#include... |
problem
A mysterious $ X $ [cm] plant grows in one place. This plant has the following mysterious properties.
* Say "nobiro" to this plant and it will grow $ A $ [cm].
* Say "tidime" to this plant and it will grow $ B $ [cm].
* If you say "karero" to this plant, it will be $ 0 $ [cm].
However, this plant does not ... | #include<bits/stdc++.h>
using namespace std;
int main(){
int x,a,b,n; cin>>x>>a>>b>>n;
for(int i=0;i<n;i++){
string s; cin>>s;
switch(s[0]){
case 'n':
x=max(x+a,0);
break;
case 't':
x=max(x+b,0);
break;
case 'k':
x=0;
break;
}
}
cout<<x<<endl;
return 0;
}
|
Find the edit distance between given two words s1 and s2.
The disntace is the minimum number of single-character edits required to change one word into the other. The edits including the following operations:
* insertion: Insert a character at a particular position.
* deletion: Delete a character at a particular posi... | #include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int dp[1001][1001];
int main(){
string s1,s2;
cin>>s1>>s2;
for(int i=0;i<=s1.length();i++){
dp[i][0] = i;
}
for(int j=0;j<=s2.length();j++){
dp[0][j] = j;
}
for(int i=1;i<=s1.length();i++){
for(int j=1;j<=s2... |
Find the union of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a... | #include<bits/stdc++.h>
#define all(x) (x).begin(),(x).end()
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
set<int> a,b,c;
int n,m;
int x;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x;
a.insert(x);
}
cin>>m;
for(int i=0;i<m;i++)
... |
Today is Chef's birthday. His mom decided to surprise him with a truly fantastic gift: his favourite binary string B. But, unfortunately, all the stocks of binary string B have been sold out, and only a binary string A (A ≠ B) is available in the market.
She purchases the string A and tries to convert it to string B by... | for i in range(int(raw_input())):
a = list(raw_input())
b = list(raw_input())
d = []
summ = 0
if len(list(set(a))) == 1:
print "Unlucky Chef"
else:
c = 0
for x in range(len(a)):
if a[x] != b[x]:
c = c + 1
d.append(int(a[x]))
l1 = d.count(1)
l0 = d.count(0)
if l1 >= l0:
summ = len(d) ... |
Chef has a special affection for sets of binary strings of equal length which have same numbers of 1's. Given three integers n, k and m, your task is to find the the lexicographically m^th smallest string among strings which have length n and have k 1's. If no such string exists output -1.
Tips:
To see what lexic... | from math import *
def nCr(n, k):
if ((k>n) or (k<0)):
return 0
if (k==0):
return 1
if (k==1):
return n
if (k==n):
return 1
return factorial(n)/(factorial(n-k)*factorial(k))
def solve(m, n, k):
global ans
if (n==0):
return
check = nCr(n-1, k)
if (m <= check):
ans += '0'
solve(m, n-1, k)
else:
... |
Chef likes to travel a lot. Every day Chef tries to visit as much cities as possible. Recently he had a quite a few trips of great Chefland for learning various recipes. Chefland had N cities numbered from 1 to N. People in Chefland are very friendly, friendliness of i-th city is given by Fi.
Before starting of each t... | import math
n = int(raw_input())
friendliness = map(int, raw_input().split())
logSum = [0]
prodSum = [0]
d = [[] for i in range(n)]
for r in range(1, n+1):
l = 0
p = 1
for j in range(r,n, r):
l += math.log10(friendliness[j])
p = (p*friendliness[j])%(10**9 + 7)
d[j].append(r)
logSum.append(l)
prodSum.append... |
Today is the reunion of all chefs in the world. Our Chef wants to make this moment more happier. He arranged a mass wedding in this reunion. For this, he made a strange stage and drew two horizontal parallel lines on the stage. There are N unmarried male chefs in the reunion and he gave each male chef i an unique numbe... | """
She's just like the first rays of sunshine,
after a stormy night.
"""
def update_tree(bit,index,val):
index += 1
while index < len(bit):
bit[index] += val
index += index & -index
return bit
def sum_till(bit,index):
index += 1
ans = 0
while index > 0:
ans += bit[index]... |
There is a very large field, colored white and divided into squares. There is a coordinate system attached to the field: y-axis goes from south to north and x-axis goes from west to east. Sides of the squares are parallel to the axes. There is a robot in the (0, 0) square. Robot starts to move in spiral as depicted. Fi... | def millerRabin(n):
# Returns true if probable prime, false if composite
bases = [2,3,5,7,11,13,17,19,23]
nm1 = n-1
m = nm1
d = 0
if n in bases:
return True
if n < 2:
return False
while not m&1:
d += 1
m >>= 1
for a in bases:
done_for_base = False
b = pow(a,m,n)... |
You are given two strings A and B of the same length. Each string contains N Lower case Latin character (from 'a' to 'z'). A shift operation will remove the first character of a string and add the same character at the end of that string. For example after you perform a shift operation on a string 'abcd', the new strin... | '''
KMP algorithm
'''
# making the table
def border(s):
table={}
table[0]=-1
table[1]=0
n=len(s)
j=0
for i in range(2,n+1):
while s[i-1]!=s[j] and j!=-1:
j=table[j]
j+=1
table[i]=j
return table
#searching
n=input()
a=raw_input()
b=raw_input()*2
table=b... |
Natasha is planning an expedition to Mars for n people. One of the important tasks is to provide food for each participant.
The warehouse has m daily food packages. Each package has some food type a_i.
Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the sam... | '''input
3 9
42 42 42 42 42 42 42 42 42
'''
from collections import Counter
n, m = map(int, input().split())
if n > m:
print(0)
quit()
a = list(map(int, input().split()))
d = 1
c = Counter(a).values()
while True:
s = sum([i//d for i in c])
if s >= n:
d += 1
else:
break
print(d - 1) |
Let's call some positive integer classy if its decimal representation contains no more than 3 non-zero digits. For example, numbers 4, 200000, 10203 are classy and numbers 4231, 102306, 7277420000 are not.
You are given a segment [L; R]. Count the number of classy integers x such that L ≤ x ≤ R.
Each testcase contain... | import java.awt.Point;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class cf1036c {
public static void main(String[] args) throws IOException {
List<Long> classy = getClassyNumbers();
IO in = new IO();
int ... |
Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of ... | import sys, math
n, m = map(int, sys.stdin.readline().split())
arr = [list(sys.stdin.readline().rstrip()) for _ in range(n)]
ans = [['.'] * m for _ in range(n)]
dx = [0,1,0,-1,1,1,-1,-1]
dy = [1,0,-1,0,1,-1,1,-1]
for i in range(n):
for j in range(m):
cnt = 0
for k in range(8):
nx, ny =... |
Recently, Olya received a magical square with the size of 2^n× 2^n.
It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly k splitting operations.
A Splitting operation is an operation during which Olya takes a square with side a and cuts it into 4 equal squares with side a/2. ... | t = int(raw_input())
f = [0]
for __ in xrange(100):
f.append(f[-1] * 4 + 1)
p = [0]
for g in xrange(100):
p.append(p[-1] + (pow(2,g+1)-1))
for __ in xrange(t):
n,k = map(int, raw_input().split())
if k == 1:
print "YES", n-1
continue
if n < len(f) and k > f[n]:
print "NO"
continue
on = n
n = min(n, l... |
Not long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x ... | #include <bits/stdc++.h>
using namespace std;
long long int cant[9];
int main() {
int n;
cin >> n;
for (int r = 0; r < (int)(9); r++) cant[r] = n / 9;
for (int r = (int)(((n / 9) * 9) + 1); r < ((int)n + 1); r++) cant[r % 9]++;
long long int res = 0;
for (int i = 0; i < (int)(9); i++)
for (int j = 0; j ... |
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.
Mike has n sweets with sizes a_1, a_2, …, a_n. All his sweets have different sizes. That is, there is no such pair ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int a[N];
vector<int> sum;
map<int, int> mp;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n, greater<int>());
for (int i = 0; i < n; i++) {
for (in... |
You are given n pairs of integers (a_1, b_1), (a_2, b_2), …, (a_n, b_n). All of the integers in the pairs are distinct and are in the range from 1 to 2 ⋅ n inclusive.
Let's call a sequence of integers x_1, x_2, …, x_{2k} good if either
* x_1 < x_2 > x_3 < … < x_{2k-2} > x_{2k-1} < x_{2k}, or
* x_1 > x_2 < x_3 >... |
import sys,os,math
from collections import Counter, defaultdict
import bisect
from sys import stdin, stdout
# n, k = map(int, raw_input().split())
# da = map(int, raw_input().split())
# db = map(int, raw_input().split())
n = map(int, raw_input().split())[0]
da = [tuple(map(int, raw_input().split())) for j in range... |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | n = int(input())
tram = []
current = []
curr = 0
for i in range(0, n):
tram.extend([int(x) for x in input().split()])
for i in range(0, 2*n, 2):
curr -= tram[i]
curr += tram[i+1]
current.append(curr)
print(max(current))
|
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al... | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int n, u, v;
cin >> n;
vector<int> deg(n, 0);
for (int i = 0; i < n - 1; i++) cin >> u >> v, u--, v--, deg[u]++, deg[v]++;
for (auto x : deg)
if (x == 2) {
cout << "NO" << endl;
... |
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet.
You have b buns, p beef patties and f chicken cutlets in your restaurant. You can sell one hamburger for ... | t = int(input())
for case in range(t):
profit = 0
buns, beef_patties, cutlets = [int(b) for b in input().split()]
beef_price, cutlet_price = [int(h) for h in input().split()]
possible_burgers = buns // 2
if beef_price >= cutlet_price:
if beef_patties > possible_burgers:
beef_patties = possible_burgers
pr... |
The only difference between easy and hard versions is constraints.
The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day.
The... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) ... |
The only difference between easy and hard versions is constraints.
You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i.
The integer point is called bad... | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int dr8[] = {0, 0, 1, -1, 1, 1, -1, -1};
int dc8[] = {1, -1, 0, 0, -1, 1, -1, 1};
int dr4[] = {0, 1, -1, 0};
int dc4[] = {1, 0, 0, -1};
int pts[200010];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
int n, k;
cin >... |
You are given an integer x of n digits a_1, a_2, …, a_n, which make up its decimal notation in order from left to right.
Also, you are given a positive integer k < n.
Let's call integer b_1, b_2, …, b_m beautiful if b_i = b_{i+k} for each i, such that 1 ≤ i ≤ m - k.
You need to find the smallest beautiful integer y,... | '''input
3 2
354
'''
s=list(map(int,input().split()))
x,k=s[0],s[1]
s=input()
m=x-k
print(x)
if k<m:
abc=s[0:k]
p=(m//k)+1
abc=abc*p
abc=abc[0:m]
abd=abc[::-1]
abc=abc+abd[0:k][::-1]
if int(abc)>=int(s):
print(abc)
else:
abc=str(int(s[0:k])+1)
p=(m//k)+1
abc=abc*p
abc=abc[0:m]
abd=abc[::-1]
abc=ab... |
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.
Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k ≥ 2 and 2k non-empty strings s_1, t_1, s_... |
import java.io.*;
import java.util.*;
/**
* @author Tran Anh Tai
* Prob D contest #616 Div 2;
* Some funny anagrams problem;
*/
public class IrreducibleAnagrams {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input... |
VK just opened its second HQ in St. Petersburg! Side of its office building has a huge string s written on its side. This part of the office is supposed to be split into m meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, bu... | #include <bits/stdc++.h>
using namespace std;
const int N = 1005;
string a, s[N * N];
int n, m, tot;
long long k;
long long f[N][N], g[N][N];
long long Rank(string ss) {
int len = ss.size();
memset(f, 0, sizeof(f)), memset(g, 0, sizeof(g));
f[n][0] = 1, g[n][0] = 1;
for (register int i = n - 1; i >= 0; i--) {
... |
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n × m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | case = int(input())
for i in range(case):
a = list(map(int, input().rstrip().split()))
column = a[1]
row = a[0]
l = [["W"] * a[1] for _ in range(a[0])]
b = ((a[1] * a[0]) // 2)+1
w = b - 1
x = 0
y = 0
while (b > 0 and y < row):
l[y][x] = "B"
x += 2
if x >= col... |
You are given an array a of length n consisting of zeros. You perform n actions with this array: during the i-th action, the following sequence of operations appears:
1. Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;
2. Let ... | import java.io.ObjectInputStream;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t;
t = input.nextInt();
while (t > 0) {
int n = input.nextInt();
i... |
You are given a string s consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode:
res = 0
for init = 0 to inf
cur = init
ok = true
for i = 1 to |s|
res = res + 1
... | for _ in range(int(input())):
arr=list(input())
n=len(arr)
fix=1;mis=0;plus=0
ans=0
for i in range(n):
if(arr[i]=="-"):
if(plus>0):
plus-=1
continue
else:
ans+=(i+1)
if(arr[i]=="+"):
plus+=1
... |
T is playing a game with his friend, HL.
There are n piles of stones, the i-th pile initially has a_i stones.
T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th... | #include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MOD = 1e9 + 7, MAX = 1e6 + 5;
const long long INF = 1e18 + 5;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> A(n);
for (int in = 0; in < 0 + n; in+... |
Vasya participates in a ski race along the X axis. The start is at point 0, and the finish is at L, that is, at a distance L meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second.
Besides, there are n take-off ramps on the track, ea... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const long long MO = 1e9 + 7;
const long long IN = 1e18;
map<int, int> mp;
map<pair<int, int>, int> mpramp;
set<pair<long long, long long> > st;
vector<pair<int, int> > g[maxn];
vector<int> v1;
vector<int> ans;
long long dis[maxn];
int x[maxn], d[... |
Ksenia has an array a consisting of n positive integers a_1, a_2, …, a_n.
In one operation she can do the following:
* choose three distinct indices i, j, k, and then
* change all of a_i, a_j, a_k to a_i ⊕ a_j ⊕ a_k simultaneously, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwi... | #include <bits/stdc++.h>
#pragma GCC target("sse4.2")
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long mod = int(1e9) + 7;
const int INF = 1e9;
const long long LINF = 2e18;
int main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cout << setprecisi... |
You have a robot that can move along a number line. At time moment 0 it stands at point 0.
You give n commands to the robot: at time t_i seconds you command the robot to go to point x_i. Whenever the robot receives a command, it starts moving towards the point x_i with the speed of 1 unit per second, and he stops when... | import sys
import bisect
input=sys.stdin.readline
t=int(input())
for you in range(t):
n=int(input())
l=[]
for i in range(n):
z=input().split()
u=int(z[0])
v=int(z[1])
l.append((u,v))
l.append((10**18,0))
counter=0
currtime=0
currpos=0
reqtime=0
reqpos=... |
«Next please», — the princess called and cast an estimating glance at the next groom.
The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous on... | #include <bits/stdc++.h>
int a[110];
int main() {
int n, x, y;
scanf("%d%d%d", &n, &x, &y);
a[1] = 1;
for (int i = 2; i <= n; i++) {
if (y) {
a[i] = 1 << (i - 1);
y--;
} else if (x && i > 2) {
a[i] = a[i - 1] + 1;
x--;
} else
a[i] = a[i - 1];
}
if (x || y) {
pri... |
You are given an array a consisting of n (n ≥ 3) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array [4, 11, 4, 4] all numbers except one are equal to 4).
Print the index of the element that does not equal others. The numbers in the array are numbered f... |
import java.io.BufferedInputStream;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(new BufferedInputStream(System.in));
int t = input.nextInt();
int[] result = new int[t];
int p = 0;
for (int i = 0; i < t... |
The Alice's computer is broken, so she can't play her favorite card game now. To help Alice, Bob wants to answer n her questions.
Initially, Bob holds one card with number 0 in the left hand and one in the right hand. In the i-th question, Alice asks Bob to replace a card in the left or right hand with a card with nu... | #include <bits/stdc++.h>
#define INF 1e18
#define EPS 1e-8
#define pb push_back
#define pause system("pause")
#define exit exit(0)
#define endl '\n'
using namespace std;
using ull = unsigned long long;
using ll = long long;
typedef pair<int,int> pii;
const int N = 100005, LG = 18, MOD = 1000000007;
int n, m, k[N], ... |
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecu... | import sun.print.resources.serviceui;
import java.io.*;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
Point[] A = new Point[n];
for(... |
Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.
The park has n intersections numbered 1 through n. There are m bidir... | #include <bits/stdc++.h>
using namespace std;
vector<int> V;
vector<int> E[200005];
int d[200005];
int p[200005];
int find(int x) { return x == p[x] ? x : p[x] = find(p[x]); }
void meld(int x, int y) {
x = find(x), y = find(y);
p[x] = y;
}
int s, t;
void build() {
fill(begin(d), end(d), 1e9);
queue<int> Q;
fo... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | word = input()
word = str.replace(word,'WUB',' ')
list1 = word.split()
print(' '.join(list1))
|
John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points.
John Doe wondered, how many distinct ways to fill the table with points are there, provided that... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B232 {
static StringTokenizer st;
static BufferedReader in;
static ... |
The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | #include <bits/stdc++.h>
using namespace std;
char num[100005];
int main() {
scanf("%s", num);
int time = 0;
if (strchr(num, '0')) {
for (int i = 0; num[i]; i++) {
if (num[i] == '0' && time == 0) {
time++;
} else {
putchar(num[i]);
}
}
putchar(10);
} else {
num[... |
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.
A Bitlandish string is a string made only of characters "0" and "1".
BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish ... | #include <bits/stdc++.h>
using namespace std;
int main() {
string a, b;
int i, j;
cin >> a >> b;
if (b.size() != a.size()) {
cout << "NO";
return 0;
}
for (i = 0; i < a.size(); i++)
if (a[i] != '0') break;
for (j = 0; j < b.size(); j++)
if (b[j] != '0') break;
if ((i == a.size() || j == ... |
A continued fraction of height n is a fraction of form <image>. You are given two rational numbers, one is represented as <image> and the other one is represented as a finite fraction of height n. Check if they are equal.
Input
The first line contains two space-separated integers p, q (1 ≤ q ≤ p ≤ 1018) — the numerat... | #include <bits/stdc++.h>
using namespace std;
const int MM = 1200000;
bool solve(long long int p, long long int q, vector<long long int> x) {
if (p <= 0 || q <= 0) {
return 0;
}
if (x.size() == 1) {
return (p / q == x.back() && p == x.back() * q);
}
long long int tp = x.back();
x.pop_back();
if (a... |
The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!
There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., a... | #include <bits/stdc++.h>
inline int in() {
int x;
scanf("%d", &x);
return x;
}
using namespace std;
constexpr int mod = 1e9 + 7, N = 3e5 + 7;
int a[N], ps[N], n;
struct node {
int l, r, ans;
} seg[4 * N];
node make(node x, node y) {
node ans;
ans.l = x.l, ans.r = y.r, ans.ans = x.ans + y.ans;
if (x.r < y.... |
Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do t... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader br;
static PrintWr... |
Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the ... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5 + 10;
int n, m, s;
int a[MAXN], b[MAXN], c[MAXN];
vector<pair<pair<int, int>, int> > v;
vector<pair<int, int> > p;
bool check(int mid) {
int st = n - 1, gv = 0;
priority_queue<pair<int, int> > te;
for (int i = m - 1; i >= 0;) {
int nxt = ... |
User ainta decided to paint a wall. The wall consists of n2 tiles, that are arranged in an n × n table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below.
1. Firstly user ainta looks at the wall. If there is at least one painted cell on each row and a... | #include <bits/stdc++.h>
bool r[2222], c[2222];
int nr, nc;
int n, m;
double f[2222][2222];
void init(void) {
scanf("%d", &n);
scanf("%d", &m);
for (int i = 0; i < (m); i = i + 1) {
int x, y;
scanf("%d", &x);
scanf("%d", &y);
r[x] = true;
c[y] = true;
}
for (int i = (1); i <= (n); i = i + ... |
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble... |
import com.sun.org.apache.bcel.internal.generic.AALOAD;
import java.io.*;
import java.util.*;
import java.math.BigInteger.*;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import java.util.logging.Level;
import java.util.logging.Logger;
// https://netbeans.org/... |
Bizon the Champion isn't just attentive, he also is very hardworking.
Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.Integer;
impo... |
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of... | #include <bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
int L, b, f;
struct car {
int s, t, i;
};
list<car> car;
int park(int x, int i) {
int x0 = -b;
for (auto it = car.begin(); it != car.end(); it++) {
if (x0 + b + x + f <= it->s) {
car.insert(it, {x0 + b, x0 + b + x, i});
retu... |
Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell <image>. The following condition is satisfi... | n, m, vx, vy = map(int, raw_input().split())
dp = [0 for i in range(n)]
x, y = 1, 1
for i in range(n):
x = (x + vx) % n
y = (y + vy) % n
dp[x] = y
counts = [[] for i in range(n)]
for i in range(m):
x, y = map(int, raw_input().split())
p = (y - dp[x] + n) % n
counts[p].append((x, y))
res = 0
m... |
Drazil and Varda are the earthworm couple. They want to find a good place to bring up their children. They found a good ground containing nature hole. The hole contains many rooms, some pairs of rooms are connected by small tunnels such that earthworm can move between them.
Let's consider rooms and small tunnels as th... | #include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, int> > G[100006];
long long dis[100006], sid[100006];
int p, s, t;
void dfs(int u, int f, long long* d) {
if (dis[u] > dis[p]) p = u;
for (auto t : G[u])
if (t.first != f) {
int v = t.first;
d[v] = d[u] + t.second;
dfs(v,... |
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.
All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that... | #include <bits/stdc++.h>
using namespace std;
const double error = 1e-15;
const double pi = 2 * acos(0);
const int maxn = (int)1e5 + 10;
const int mod = (int)1e9 + 7;
int dx[] = {0, -1, 0, +1, -1, -1, +1, +1};
int dy[] = {-1, 0, +1, 0, -1, +1, +1, -1};
long dp[200005], pv[200005];
vector<long> L[200005], R[200005], g[2... |
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.
The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each... | N, M = [int(x) for x in input().split()]
results = [0] * N
for i in range(M):
city_results = [int(x) for x in input().split()]
city_max = max(city_results)
city_max_idx = city_results.index(city_max)
results[city_max_idx] += 1
max_result = max(results)
max_index = results.index(max_result)
print(ma... |
A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.
We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at poi... | import java.io.IOException;
import java.util.InputMismatchException;
public class ChipNDaleRescueRangers {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int X1 = sc.nextInt();
int Y1 = sc.nextInt();
int X2 = sc.nextInt();
int Y2 = sc.nextI... |
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai — the current skill level. All skills have the same maximum level A.
Along with... | #include <bits/stdc++.h>
using namespace std;
long long n, A, cf, cm, m, a[100005], ex[100005], pref[100005], Ans[100005];
pair<long long, long long> b[100005];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> A >> cf >> cm >> m;
long long cnt = 0;
for (long long i = 1; i <= n; ++i) {
cin... |
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem?
Input
The only line of input contains ... | #include <bits/stdc++.h>
using namespace std;
int solve(int i) {
int ret = 0;
while (i) {
ret += (i / 5);
i /= 5;
}
return ret;
}
vector<int> x;
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < 1000000; i++) {
if (solve(i) == n) x.push_back(i);
}
cout << (int)x.size() << endl;
fo... |
Gerda is travelling to the palace of the Snow Queen.
The road network consists of n intersections and m bidirectional roads. Roads are numbered from 1 to m. Snow Queen put a powerful spell on the roads to change the weather conditions there. Now, if Gerda steps on the road i at the moment of time less or equal to i, s... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 3e5;
const int base = 1e9 + 7;
int n, m, q;
int x[maxn], y[maxn];
int l[maxn], r[maxn], s[maxn], t[maxn];
int ans[maxn];
int d[2000][2000];
vector<int> lst[maxn];
int main() {
ios_base::sync_with_stdio(0);
cin >> n >> m >> q;
for (int i = 1; i <= m; i... |
At the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to... | #include <bits/stdc++.h>
using namespace std;
namespace io {
const int SI = 1 << 21 | 1;
char IB[SI], *IS, *IT, OB[SI], *OS = OB, *OT = OS + SI - 1, c, ch[100];
int f, t;
inline void flush() { fwrite(OB, 1, OS - OB, stdout), OS = OB; }
inline void pc(char x) {
*OS++ = x;
if (OS == OT) flush();
}
template <class I>
... |
A group of n friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the i-th friend is ri.
The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consist... | import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by Jeremy on 11/30/2016.
*/
public class CodeForces730A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numFriends = scan.nextInt();
int[] skillz = new int[numFriends];
for... |
The New Year tree is an infinite perfect binary tree rooted in the node 1. Each node v has two children: nodes indexed (2·v) and (2·v + 1).
<image>
Polar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of no... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 51;
const long long one = 1LL;
const int N = 222;
int d[N];
long long f[N][N][N];
long long x[N];
int main() {
long long lol;
cin >> lol;
long long ans = 0;
for (int h1 = 1; h1 <= MAX; ++h1) {
for (int h2 = h1; h2 <= MAX; ++h2) {
for (int l... |
Stepan has a very big positive integer.
Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203... | #include <bits/stdc++.h>
using namespace std;
char s[400010];
long long m, slen, g[200010];
long long pow10(long long n) {
long long ans = 1, a = 10;
while (n) {
if (n & 1) ans = (ans * a) % m;
n >>= 1;
a = (a * a) % m;
}
return ans % m;
}
signed main() {
long long ans, cnt0, powww;
scanf("%s", ... |
Arkady and Masha want to choose decorations for thier aquarium in Fishdom game. They have n decorations to choose from, each of them has some cost. To complete a task Arkady and Masha need to choose exactly m decorations from given, and they want to spend as little money as possible.
There is one difficulty: Masha lik... | import java.util.*;
public class Test {
int n, m, k;
int[] c;
List<List<Integer>> qs = new ArrayList<>();
short[] mask;
Scanner sca = new Scanner(System.in);
long best = -1;
void start() {
n = sca.nextInt();
m = sca.nextInt();
k = sca.nextInt();
c = new i... |
In order to fly to the Moon Mister B just needs to solve the following problem.
There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.
We are sure that Mister B will solve the problem soon and will fly to the Mo... | #!/usr/bin/env python3
from collections import defaultdict
DEBUG = False
def main():
if DEBUG:
test()
n = int(input())
paths = cycles(n)
print(len(paths))
for p in paths:
print('%d %s' % (len(p), ' '.join([str(v) for v in p])))
def cycles(n):
"""Builds a set of cycles fo... |
Polycarp is a great fan of television.
He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.
Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given mom... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
impo... |
Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string... | #include <bits/stdc++.h>
using namespace std;
const int N = (1 << 14), M = 15;
bool fl[M];
long long n, sum, ret, ans, g[M], f[N];
char s[M];
inline int getvac(long long v, int d) { return ((v >> (4 * (d - 1))) & 15); }
inline void solve() {
memset(f, -1, sizeof(f)), f[0] = 0;
for (int i = 0; i < (1 << n); i++) {
... |
A false witness that speaketh lies!
You are given a sequence containing n integers. There is a variable res that is equal to 0 initially. The following process repeats k times.
Choose an index from 1 to n uniformly at random. Name it x. Add to res the multiply of all ai's such that 1 ≤ i ≤ n, but i ≠ x. Then, subtrac... | #include <bits/stdc++.h>
const int N = 5005, mod = 1000000007;
int n, k, ans;
int a[N];
int pow(int x, int y, int ans = 1) {
for (; y; y >>= 1, x = (long long)x * x % mod)
if (y & 1) ans = (long long)ans * x % mod;
return ans;
}
int main() {
std::ios::sync_with_stdio(0), std::cin.tie(0);
std::cin >> n >> k,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.