input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Problem
N ignited fuses and one bomb for each are placed on a vertical H x horizontal W grid. Each fuse and bomb is placed on a pathi consisting of Li cells, and the jth cell of pathi is (pxij, pyij). Each bomb is in the last square of pathi (pxiLi, pyiLi). The fire of the lead wire is in the square (pxi1, pyi1) in th... | #define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <limits>
#include <ctime>
#include <cassert>
#include <map>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include... |
Isaac H. Ives attended an international student party and made a lot of girl friends (as many other persons expected). To strike up a good friendship with them, he decided to have dates with them. However, it is hard for him to schedule dates because he made so many friends. Thus he decided to find the best schedule us... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct BipartiteMatching {
int V;
vector<vector<bool> > G;
vector<int> match;
vector<bool> used;
BipartiteMatching(int v) {
V = v;
G = vector<vector<bool> >(v, vector<bool>(v));
match = vector<int>(v);
used = vector<bool>(v);
}
void a... |
Kyo, 垓, {Reiyo}, 穣, Mizo, 澗, Tadashi, Ryo, Goku, Tsunekawasa, Amongi, Decillion, etc.
Minutes, 厘, hair, thread, 忽, fine, fine, fine, sha, dust, dust, 渺, vagueness, vagueness, patrolling, su 臾, sigh, bullet finger, moment, Rokutoku, emptiness, cleanliness, Ariya, Ama Luo, tranquility
Do you know what these are? These ... | #include<iostream>
#include<sstream>
#include<map>
#include<string>
using namespace std;
#define INF 100000000
int main()
{
int n;
string temp;
int a;
int cost[201][201],minicost[201];
while(cin>>n && n!=0){
for(int i=0;i<=200;i++){
for(int j=0;j<=200;j++){
cost[i][j]=INF;
}
minicost[i]=INF;
}... |
Example
Input
4
Output
4
0 0
1 0
2 0
1 1 | #include<stdio.h>
#include<algorithm>
#include<set>
using namespace std;
int x[2100];
int y[2100];
set<pair<pair<int,int>,pair<long long,long long> > >S;
int gcd(int a,int b){
while(a){
b%=a;
int c=a;a=b;b=c;
}
return b;
}
int ABS(int a){return max(a,-a);}
bool chk(int ax,int ay,int at){
for(int j=0;j<at;j++){
... |
Problem Statement
Chelsea is a modern artist. She decided to make her next work with ladders. She wants to combine some ladders and paint some beautiful pattern.
A ladder can be considered as a graph called hashigo. There are n hashigos numbered from 0 to n-1. Hashigo i of length l_i has 2 l_{i} + 6 vertices v_{i, 0}... | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define FOR(i,k,n) for(int i=(k);i<(int)(n);i++)
#define getb(i,j) (((i)>>(j))&1)
using namespace std;
const int mod = 1000000007;
struct Mod {
int num;
Mod () : num(0) {;}
Mod (int n) : num(n) {;}
operator int() { return num; }
};
Mod o... |
Alternate Escape
Alice House
Alice and Bob are playing board games. This board game is played using a board with squares in rows H and columns and one frame. In this game, the upper left square of the board is set as the 1st row and 1st column, and the rows are counted downward and the columns are counted to the righ... | #include <bits/stdc++.h>
#define REP(i,n) for(int i=0;i<(int)n;++i)
using namespace std;
template<typename T>
using table = vector<vector<T>>;
using wall = bitset<4>;
int main() {
while(1){
int h,w,r,c;
cin>>h>>w>>r>>c;
if(!h)break;
int H=h+2, W=w+2;
table<wall> g(H,vector<wall>(W));
REP(i,... |
C: Only one subsequence --Unique Subsequence-
problem
One day Ebi-chan noticed that a text string T of length n and a pattern string P (m \ leq n) of length m were placed on the desk. Ebi-chan loves the "only one subsequence" that appears in strings, so she immediately began investigating whether P was the only subse... | #include<bits/stdc++.h>
using namespace std;
// macro
#define rep(i,n) for(i=0;i<n;i++)
#define ll long long
#define all(v) v.begin(), v.end()
// code starts
int main()
{
string t,p;cin>>t>>p;
int nowi=0;
vector<int> use_front(0);
vector<int> use_back(0);
int i;
rep(i,t.size())
{
if(t[i]==p[nowi])
... |
B: AddMulSubDiv
Problem Statement
You have an array A of N integers. A_i denotes the i-th element of A.
You have to process one of the following queries Q times:
* Query 1: The query consists of non-negative integer x, and two positive integers s, t. For all the elements greater than or equal to x in A, you have to... | #include<bits/stdc++.h>
using namespace std;
using i64 = int64_t;
struct Query{
i64 q, x, s, t;
};
void update(int idx, vector<i64> &v, deque<bool> &updated, const vector<Query> &query){
if(updated[idx])return;
for(auto q: query){
if(q.q == 1){
if(v[idx] < q.x)continue;
v[... |
Problem statement
A $ 2 $ human-player match-up game tournament is about to take place in front of Kyoto University Camphor Tree.
There are $ 2 ^ N $ participants in this tournament, numbered from $ 1 $ to $ 2 ^ N $.
Winning or losing when $ 2 $ of participants fight is represented by the $ 2 ^ N-1 $ string $ S $ co... | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#include <tuple>
#define mkp make_pair
#define mkt make_tuple
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
const ll ... |
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The f... | #include <bits/stdc++.h>
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
using namespace std;
const int nmax=100010;
vector<int> graph[nmax];
int parent[nmax][20]; // all is -1
int depth[nmax];
void dfs(int v,int p,int d){
parent[v][0]=p;
depth[v]=d;
for(auto &v2:graph[v]) if(v2!=p) dfs(v2,v,d+1);
}
int lca(int u... |
Harry is a bright student. To prepare thoroughly for exams, he completes all the exercises in his book! Now that the exams are approaching fast, he is doing book exercises day and night. He writes down and keeps updating the remaining number of exercises on the back cover of each book.
Harry has a lot of books messed o... | import sys
filein = sys.stdin
#filein = open("bex.in2",'r')
def main() :
n = int(filein.readline())
ll = []
bookcnt = 0
outstr = []
for str in filein :
if str[0] == "-" :
outstr.append("%d %s" % (bookcnt-ll[-1][2],ll[-1][1]))
#print "%d %s" % (bookcnt-ll[-1][2],ll[-1][1])
bookcnt = ll[-... |
Sheh ! You are bored again. :P
You guys decide to play a game, this time based on your names. All of you write your name on a sheet of paper and the one whose name has the maximum number of distinct substrings of his name wins the game.
But counting this is a tiresome task, isn't it ?
So, you think about writing a clev... | n=input()
for i in range(n):
inp=raw_input()
li=[]
for j in range(len(inp)):
string=inp[j]
li.append(string)
for k in range(j+1,len(inp)):
string+=inp[k]
li.append(string)
print len(set(li)) |
Chef changed the password of his laptop a few days ago, but he can't remember it today. Luckily, he wrote the encrypted password on a piece of paper, along with the rules for decryption.
The encrypted password is a string S consists of ASCII printable characters except space (ASCII 33 - 126, in decimal notation, the sa... | def get_rules(num_rules):
"""
Read the input for num_rules times.
Return - Dictionary with keys mapping
to values.
"""
rules = {}
for _ in xrange(num_rules):
key, val = raw_input().split()
rules[key] = val
return rules
def decode_pass(password, rules):
"""
... |
In this problem, the divisors of N do not include the number N itself. For example, if N=24, the divisors of N (excluding N) are 1, 2, 3, 4, 6 and 12. Thus, the product of divisors is 1x2x3x4x6x8x12=13824. Since the result may be very large, if the result has more than 4 digits, the program only needs to compute the la... | def factors(n):
return reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))
t = long(raw_input())
while t:
t-=1
a = long(raw_input())
b = []
b = factors(a)
b = list(set(b))
b.sort()
c = 1
for i in xrange(len(b)-1):
c*=b[i]
c =... |
Print sum of prime numbers upto n
Input
n - the number till which sum has to be done.
Output
print sum of primes ≤n.
Example
Input:
5
Output:
10 | def ps(n):
r = int(n**0.5)
assert r*r <= n and (r+1)**2 > n
V = [n//i for i in range(1,r+1)]
V += list(range(V[-1]-1,0,-1))
S = {i:i*(i+1)//2-1 for i in V}
for p in range(2,r+1):
if S[p] > S[p-1]: # p is prime
sp = S[p-1] # sum of primes smaller than p
p2 = p*p
... |
Once Chef decided to divide the tangerine into several parts. At first, he numbered tangerine's segments from 1 to n in the clockwise order starting from some segment. Then he intended to divide the fruit into several parts. In order to do it he planned to separate the neighbouring segments in k places, so that he coul... | def solve():
N, K, P = map(int, raw_input().split())
pos = set()
for k in xrange(K):
l, r = map(int, raw_input().split())
pos.add(r)
okay = True
for p in xrange(P):
l, r = map(int, raw_input().split())
if okay and r not in pos:
okay = False
return 'Yes... |
The Main Martian Tree grows on Mars. It is a binary tree (a rooted tree, with no more than two sons at each vertex) with n vertices, where the root vertex has the number 1. Its fruits are the Main Martian Fruits. It's summer now, so this tree does not have any fruit yet.
Autumn is coming soon, and leaves and branches ... | #include <bits/stdc++.h>
using namespace std;
int n;
long long kk;
int Pow(int x, int a) {
int ans = 1, cur = x % 998244353;
while (a) {
if (a & 1) ans = 1ll * ans * cur % 998244353;
cur = 1ll * cur * cur % 998244353, a >>= 1;
}
return ans;
}
int Wn[2][1000006], rev[1000006];
void getwn(int len) {
for... |
You are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0).
The given points are vertices of a plot of a piecewis... |
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Scanner;
import java.io.IOException;
public class Task2 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
long k =in.nextLong();
... |
There are n candy boxes in front of Tania. The boxes are arranged in a row from left to right, numbered from 1 to n. The i-th box contains r_i candies, candies have the color c_i (the color can take one of three values — red, green, or blue). All candies inside a single box have the same color (and it is equal to c_i... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
if (a == 0LL) return b;
if (b == 0LL) return a;
return gcd(b, a % b);
}
const int N = 51;
const int M = 2501;
int dp[N][M], type[N], R[N];
priority_queue<pair<int, pair<int, int>>> pq;
bool visited[N][M];
void solve() {
int ... |
Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array a of the size of 10^9 elements that is filled as follows:
* a_1 = -1
* a_2 = 2
* a_3 = -3
* a_4 = 4
* a_5 = -5
* And so on ...
... | for i in range(int(input())):
a,b=map(int,input().split())
if (b-a)%2!=0:
if a%2==0:
print(-(b-a+1)//2)
else:
print((b-a+1)//2)
else:
if a%2!=0:
print((b-a)//2 - b)
else:
print(-(b-a)//2 + b) |
Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minut... | #!/usr/bin/python
import sys
(n, p1, p2, p3, t1, t2) = sys.stdin.readline().split()
n = int(n)
p1 = int(p1)
p2 = int(p2)
p3 = int(p3)
t1 = int(t1)
t2 = int(t2)
p = 0
rprev = 0
for i in range(1,n+1):
(l, r) = sys.stdin.readline().split()
l = int(l)
r = int(r)
p += p1 * (r - l)
if i == 1:
rprev = l
delta =... |
Little W and Little P decided to send letters to each other regarding the most important events during a day. There are n events during a day: at time moment t_i something happens to the person p_i (p_i is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the othe... | #include <bits/stdc++.h>
using namespace std;
int ara[300000], kk[300000], last[4], nexto[300000], c, d, n;
long long dp[300000][2][2];
long long dp_func(int pos, int f, int s) {
if (pos == n + 1) {
return 0;
}
if (dp[pos][f][s] != -1) return dp[pos][f][s];
long long ret = 1LL << 55;
if (kk[pos] == 0) {
... |
Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.
There are n flights from A to B, they depart at time moments a_1, a_2, a_3, ..., a_n and arrive at B t_a moments later.
There are m flights from B to C... | #include <bits/stdc++.h>
using namespace std;
vector<long long int> ar, br;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int sum = 0, cnt, b;
long long int x = 0, k, ans = 0;
long long int n, m = 1, mx = 0, a, mn = 0;
cin >> n >> m >> a >> b >> k;
for (int i = 1; i <= n; i++) {
... |
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 ≤ l ≤ r ≤ n and there is at least one pair of integers x, k such that 1 ≤ x, k ≤ n, l ≤ x < x + 2k ≤ r, and s_x = s_{x+k} = s_{x+2k}.
Find th... | import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve(){
char s[]=ns().toCharArray();
long ans=0;
int n=s.length;
int mnR[]=new int[n+1];
for(int i=1;i<=n;i++){
... |
Let x be an array of integers x = [x_1, x_2, ..., x_n]. Let's define B(x) as a minimal size of a partition of x into subsegments such that all elements in each subsegment are equal. For example, B([3, 3, 6, 1, 6, 6, 6]) = 4 using next partition: [3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6].
Now you don't have any exact values of x,... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 10;
const long long MOD = 1e9 + 7;
int n;
int l[MAX];
int r[MAX];
void init() {
cin >> n;
for (int i = 0; i < (int)(n); i++) cin >> l[i];
for (int i = 0; i < (int)(n); i++) {
cin >> r[i];
r[i]++;
}
}
template <typename T>
T extgcd(T a, ... |
This is an interactive problem
You are given a grid n× n, where n is odd. Rows are enumerated from 1 to n from up to down, columns are enumerated from 1 to n from left to right. Cell, standing on the intersection of row x and column y, is denoted by (x, y).
Every cell contains 0 or 1. It is known that the top-left ce... | #include <bits/stdc++.h>
using namespace std;
void E1206();
bool askE1206(int x1, int y1, int x2, int y2);
int main() {
E1206();
return 0;
}
void E1206() {
int n;
cin >> n;
vector<vector<int>> arr(n, vector<int>(n, -1));
arr[0][0] = true;
arr[n - 1][n - 1] = false;
arr[0][1] = true;
bool a = askE1206(... |
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.
Can you reconst... | #include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
if (a == 9 && b == 1) {
cout << a << " " << 10 * b;
return 0;
}
if (abs(a - b) > 1) {
cout << "-1";
} else {
if (a == b)
cout << 10 * a << " " << 10 * b + 1;
else if (a > b)
cout << "-1";
... |
The only difference between easy and hard versions is the maximum value of n.
You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.
The positive integer is called good if it can be represented as a sum of distinct powers of 3 (... |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class CF {
private static Scanner cin = new Scanner(System.in);
static final int N = 100111;
static final long MAX = 1350851717672992089L;
static... |
Karl is developing a key storage service. Each user has a positive integer key.
Karl knows that storing keys in plain text is bad practice. So, instead of storing a key, he decided to store a fingerprint of a key. However, using some existing fingerprint algorithm looked too boring to him, so he invented his own one.
... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int cnt[MAX];
long long bin[MAX][MAX];
void init() {
for (int i = 0; i < int(100); i++) {
bin[i][0] = bin[i][i] = 1;
for (int j = 1; j < i; j++) bin[i][j] = bin[i - 1][j - 1] + bin[i - 1][j];
}
}
long long dp[MAX][MAX];
bool visited[MAX][MAX... |
Anna's got a birthday today. She invited many guests and cooked a huge (nearly infinite) birthday cake decorated by n banana circles of different sizes. Maria's birthday is about to start in 7 minutes too, and while Anna is older, she decided to play the boss a little. She told Maria to cut the cake by k straight-line ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1005;
int n, k, ans;
int x[N], y[N], R[N];
pair<double, int> q[N * 2];
double eps = 1e-10;
int calc(double ang) {
double dx = sin(ang);
double dy = cos(ang);
int top = 0;
for (int i = (int)(1); i <= (int)(n); i++) {
double tmp = x[i] * dx + y[i] * ... |
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively ... | import heapq
n = int(input())
*a, = map(int, input().split())
*t, = map(int, input().split())
i = 0
sorted_idxs = sorted(range(n), key=lambda o: (a[o], -t[o]))
cur_val = a[sorted_idxs[0]]
dupls = []
ans = 0
s = 0
for i, idx in enumerate(sorted_idxs):
cur_val = a[idx]
heapq.heappush(dupls, (-t[idx], a[idx]))
... |
Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.
Given a graph G=(V,E), an independent set is a subset of vertices V' ⊂ V such that for every pair u,v ∈ V', (u,v) not ∈ E (i.e. no edge in E connects two vertices from V').
An edge-induced subgraph consists of a ... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = (119 << 23) + 1;
long long add(long long a, long long b) {
a += b;
if (a < 0) {
a += MOD;
}
if (a >= MOD) {
a -= MOD;
}
return a;
}
long long sub(long long a, long long b) {
a -= b;
if (a < 0) a += MOD;
return a;
}
long long m... |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | def swap_sum(a,b,cnt,k):
if cnt==k or min(a)>=max(b):
return sum(a)
else:
i=a.index(min(a))
j=b.index(max(b))
a[i],b[j]=b[j],a[i]
#print(a)
#print(b)
return swap_sum(a,b,cnt+1,k)
for ii in range(int(input())):
n,k=map(int,input().sp... |
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ... | import sys
input = sys.stdin.readline
def main():
t = int(input())
for _ in range(t):
A, B, C = [int(x) for x in input().split()]
ans1 = -1
ans2 = -1
if A < C:
ans1 = 1
if A * B > C:
ans2 = B
print(ans1, ans2)
if __name__ == '... |
Boboniu defines BN-string as a string s of characters 'B' and 'N'.
You can perform the following operations on the BN-string s:
* Remove a character of s.
* Remove a substring "BN" or "NB" of s.
* Add a character 'B' or 'N' to the end of s.
* Add a string "BN" or "NB" to the end of s.
Note that a strin... | #include <bits/stdc++.h>
using namespace std;
#pragma GCC target("avx2")
#pragma GCC optimization("O3")
#pragma GCC optimization("unroll-loops")
const long long INFll = 1e18;
const int INFint = 1e9;
const long long MOD = 1e9 + 9;
void needForSpeed() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
bool ... |
So nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks... | import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
if (y % a==0) {
System.out.println(-1);
return;
}
... |
You're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 ≤ i ≤ n).
Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers... | //package Problems;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.ArrayList;
//import com.sun.tools.javac.code.Attribute.A... |
You are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has a health points, the second has b health points, and the third has c.
To kill the monsters, you can use a cannon that, when fired, deals 1 damage to the selected ... | def zip_sorted(a,b):
# sorted by a
a,b = zip(*sorted(zip(a,b)))
# sorted by b
sorted(zip(a, b), key=lambda x: x[1])
return a,b
import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
S = lambda : list(map(str,input()))
t,=I()
for t1 in range(t):
a = I()
if sum(a)%9==0:
if min(... |
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | import java.util.Scanner;
import java.util.ArrayList;
public class codeforces
{
public static void main(String[] args)
{
Scanner in = new Scanner( System.in);
int answer;
int k = in.nextInt();
int l = in.nextInt();
int m = in.nextInt();
int n = in.nextInt();
int d = in.nextInt();
an... |
You have a large rectangular board which is divided into n × m cells (the board has n rows and m columns). Each cell is either white or black.
You paint each white cell either red or blue. Obviously, the number of different ways to paint them is 2^w, where w is the number of white cells.
After painting the white cell... | #include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <unordered_map>
using namespace std;
typedef long long LL;
const int N = 3e5 + 10, mod = 998244353;
string g[N];
int dp[N];
int fastPow(int a, int k) {
int res = 1;
while (k) {... |
There are n students numerated from 1 to n. The level of the i-th student is a_i. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than x.
For example, if x = 4, then the group with levels [1, 10, ... | n,k,x =list(map(int ,input().split()))
arr = list(map(int ,input().split()))
arr.sort()
groups =1
re = []
for i in range(n-1):
diff = arr[i+1]-arr[i]
if diff>x :
if x==0:
groups+=1
continue
if diff%x==0:
diff = diff//x -1
else:
diff =diff//x
re.append(di... |
Two integers x and y are compatible, if the result of their bitwise "AND" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.
You are given an array of integers a1, a2,... | #include <bits/stdc++.h>
using namespace std;
const int maxn = (1 << 23);
bool mark[maxn];
int a[maxn], in_sub[maxn];
queue<int> q;
int tilda(int x) { return (1 << 22) - 1 - x; }
void reverse_bfs() {
while (q.size()) {
int tmp = q.front();
for (int i = 0; i < 22; i++)
if (!(tmp & (1 << i))) {
in... |
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the perm... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 200 * 1000 + 100;
int n, a[MAXN], b[MAXN], p[MAXN], x;
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
p[a[i]] = i;
}
for (int i = 0; i < n; ++i) cin >> b[i];
for (int i = 0; i < n; ++i) a[p[b[i]]] = i;
x = 1;
while (... |
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:
You've got some training set of documents. For each document you know its su... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
n /= 1000;
if (n & 1)
cout << 2 << endl;
else
cout << 1 << endl;
}
|
Let's consider equation:
x2 + s(x)·x - n = 0,
where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.
You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.
Input
A sing... | import java.util.*;
public class Books {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long n=sc.nextLong();
long ans=-1;
for(int i=1;i<=90;i++){
long a=(long)Math.sqrt(i*i/4+n)-i/2;
... |
The Little Elephant loves chess very much.
One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8 × 8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doe... | flag=True
for i in range(8):
k=input()
if k!='BWBWBWBW' and k!='WBWBWBWB':
flag=False
if (flag):
print ("YES")
else:
print ("NO")
|
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | n = int(input())
counter= 0
for i in range(n):
if input().find('+') > -1:
counter = counter + 1
else:
counter = counter - 1
print(counter) |
You have been given n distinct integers a1, a2, ..., an. You can remove at most k of them. Find the minimum modular m (m > 0), so that for every pair of the remaining integers (ai, aj), the following unequality holds: <image>.
Input
The first line contains two integers n and k (1 ≤ n ≤ 5000, 0 ≤ k ≤ 4), which we have... | #include <bits/stdc++.h>
using namespace std;
int num[5010], cnt[1000010];
int vi[1000010];
int main() {
int n, k, kk, mlen;
while (scanf("%d%d", &n, &k) == 2) {
kk = k * (k + 1) / 2;
mlen = 0;
for (int i = 0; i < n; ++i) scanf("%d", &num[i]);
sort(num, num + n);
for (int i = 0; i < n; ++i)
... |
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?
— Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night?
At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcomin... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
void solve() {
long long n;
cin >> n;
long long arr[n];
map<long long, long long> m;
long long psum[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
if (i == 0) {
if (arr[i] >= 0)
psum[i] = arr[i];
else
... |
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjace... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 3050;
const long long Mod = 152076289;
int p[MAXN];
int cnt;
int temp[MAXN];
void Merge(int low, int mid, int high) {
int i = low;
int j = mid + 1;
int x = low;
while (i <= mid && j <= high) {
if (p[i] > p[j]) {
cnt += mid - i + 1;
t... |
You have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you.
You can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, e... | #include <bits/stdc++.h>
using namespace std;
int n, m, ans, cnt, flag, tot;
int sx, sy;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int dp[25][25][1 << 8];
int val[8], w[1 << 8];
int gx[8], gy[8];
char mp[25][25];
char s[25];
struct Node {
int x, y, k;
} cur, now;
bool issur(int nx, int ny, int tx, int ty, i... |
User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack.
* While the top ball inside the stack is red, pop the ball from the top of the stack.
* Then replace the blue ball on the top with a red ball.
* And finally push some blue ba... | #include <bits/stdc++.h>
using namespace std;
long long lookup[51];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long init = 1;
for (int i = 0; i < 51; i++) {
lookup[i] = init;
init *= 2;
}
int n;
cin >> n;
long long out = 0;
for (int i = 0; i < n; i++) {
char c;
... |
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.
One day the director of the F ... | #include <bits/stdc++.h>
using namespace std;
void RD(int &x) { scanf("%d", &x); }
void RD(long long &x) { scanf("%I64d", &x); }
void RD(double &x) { scanf("%lf", &x); }
void RD(int &x, int &y) { scanf("%d%d", &x, &y); }
void RD(long long &x, long long &y) { scanf("%I64d%I64d", &x, &y); }
void RD(double &x, double &y) ... |
Bizon the Champion is called the Champion for a reason.
Bizon the Champion has recently got a present — a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an... | import math
print 'YES' if int(math.ceil(sum(map(int,raw_input().split()))/5.0)) + int(math.ceil(sum(map(int,raw_input().split()))/10.0)) <= int(raw_input()) else 'NO'
|
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not ... | #include <bits/stdc++.h>
using namespace std;
int a[5], t;
string e[5] = {"S", "M", "L", "XL", "XXL"}, s;
int p() {
if (s == "S") return 0;
if (s == "M") return 1;
if (s == "L") return 2;
if (s == "XL") return 3;
if (s == "XXL") return 4;
}
int main() {
for (int i = (0); i < (5); i++) cin >> a[i];
cin >> ... |
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi es... | #include <bits/stdc++.h>
using namespace std;
struct node {
long long a;
int b;
};
struct node node_arr[100010];
int sort_b(struct node n1, struct node n2) {
if (n1.b < n2.b) return -1;
return 0;
}
void solveTestCase() {
int n;
scanf("%d", &n);
;
long long r, avg;
scanf("%I64d", &r);
;
scanf("%I64... |
Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:
"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."
But Draz... | #include <bits/stdc++.h>
using namespace std;
struct punkt {
int x;
int y;
};
punkt stos[4000001];
int n, m, i, x, y, s;
char znak, w[2004][2004];
bool tab[2004][2004], blad;
int ile(int x, int y) {
int r = 0;
if (x < 1 || x > n || y < 1 || y > m || tab[x][y] == 0) return 111;
if (!tab[x + 1][y]) r++;
if (!... |
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any ... | #include <bits/stdc++.h>
using namespace std;
const int NMAX = 3005;
int n, m;
vector<int> e[NMAX];
int s[2], t[2], l[2];
int d[NMAX][NMAX];
void bfs(int sid, int* d) {
for (int i = 0; i < NMAX; i++) d[i] = 0x7FFF;
d[sid] = 0;
queue<int> q;
q.push(sid);
while (!q.empty()) {
int vid = q.front();
q.pop(... |
There is a string s, consisting of capital Latin letters. Let's denote its current length as |s|. During one move it is allowed to apply one of the following operations to it:
* INSERT pos ch — insert a letter ch in the string s in the position pos (1 ≤ pos ≤ |s| + 1, A ≤ ch ≤ Z). The letter ch becomes the pos-th s... | import java.io.*;
import java.util.*;
public class Main {
static PrintWriter pw;
static Scanner sc;
static HashMap<Pair, Integer> map;
static String end;
static String st;
static int inf=(int)1e9;
static HashMap<Pair, Pair> next;
static long ceildiv(long x, long y){ return (x+y-1)/y;}
... |
The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan... | import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.InputMismatchException;... |
You are given a circular array with n elements. The elements are numbered from some element with values from 1 to n in clockwise order. The i-th cell contains the value ai. The robot Simba is in cell s.
Each moment of time the robot is in some of the n cells (at the begin he is in s). In one turn the robot can write o... | #include <bits/stdc++.h>
using namespace std;
int a[2010], b[2010], bn, n;
vector<int> oc[2010];
int memo[2010];
int mn_dist(int a, int b) { return min(abs(a - b), n - abs(a - b)); }
int solve(int i);
int solve_aux(int i, int val) {
int on = oc[val].size();
if (on == 1) {
return mn_dist(i, oc[val][0]) + solve(o... |
You're given a matrix A of size n × n.
Let's call the matrix with nonnegative elements magic if it is symmetric (so aij = aji), aii = 0 and aij ≤ max(aik, ajk) for all triples i, j, k. Note that i, j, k do not need to be distinct.
Determine if the matrix is magic.
As the input/output can reach very huge size it is r... | #include <bits/stdc++.h>
using namespace std;
int n, flag = 0;
int matrix[2505][2505];
int parent[2505];
vector<int> graph[2505];
int vis[2505], num[2505];
struct Edge {
int u, v, w;
Edge() {}
Edge(int u, int v, int w) : u(u), v(v), w(w) {}
};
vector<Edge> edge;
bool cmp(const Edge &a, const Edge &b) { return a.w... |
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.
Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is bl... | #include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
ostream &operator<<(ostream &s, const pair<A, B> &p) {
return s << "(" << p.first << "," << p.second << ")";
}
template <typename T>
ostream &operator<<(ostream &s, const vector<T> &c) {
s << "[ ";
for (auto it : c) s << it << " ";
... |
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}.
In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matc... | #include <bits/stdc++.h>
using namespace std;
int calc(int x) {
if (x == 0) return 0;
for (int i = 1; i <= 1000000; i++) {
if (i * (i - 1) == x * 2) return i;
}
return -1;
}
int main() {
int a00, a01, a10, a11;
scanf("%d%d%d%d", &a00, &a01, &a10, &a11);
int x = calc(a00), y = calc(a11);
if (!x && (a... |
A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.
The ugliness of a string is the minimum possible number of characters to rem... | #include <bits/stdc++.h>
using namespace std;
#pragma comment(linker, "/STACK:102400000,102400000")
const int inf = 0x3f3f3f3f;
const int maxn = 200000 + 5;
struct Node {
int dp[5][5];
} tree[maxn << 2];
int n, q;
char ch[maxn];
map<char, int> id;
inline void init(Node &t) {
for (int i = 0; i < 5; i++)
for (int... |
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.
<image>
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be high... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int INF = 1e9;
const int base = 1e9;
const int MAX = 2e5;
const long double EPS = 1e-10;
const long double PI = acos(-1.);
int n;
int main() {
ios_base::sync_with_stdio(0);
cin >> n;
if (n % 2) {
cout << 7;
n -= 3;
}
while (n... |
Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allow... | import operator
fc = []
fd = []
n, c, d = map(int, input().split())
for _ in range(n):
b, p, m = input().split()
b, p = int(b), int(p)
if m == 'C':
if p <= c:
fc.append((b, p))
else:
if p <= d:
fd.append((b, p))
fc.sort(key=operator.itemgetter(0), reverse=True... |
Mister B has a house in the middle of a giant plain field, which attracted aliens life. For convenience, aliens specified the Cartesian coordinate system on the field in such a way that Mister B's house has coordinates (0, 0). After that they sent three beacons to the field, but something went wrong. One beacon was com... | #include <bits/stdc++.h>
using namespace std;
int t, s[3], m[3], n[3];
long long N, M;
map<int, int> factn, facts;
vector<pair<int, int> > vp;
vector<long long> gm;
long long ans;
void dfs(int ind, long long val) {
if (ind == vp.size()) {
ans++;
return;
}
for (int i = 0; i <= vp[ind].second && val <= N; i... |
Berland annual chess tournament is coming!
Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.
Thus, organizers sh... | import java.util.*;
import java.io.*;
public class ChessTourney {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] a = new int[2*n];
for(int i = 0 ; i < 2*n ; i++)
a[i] = scan.nextInt();
Arrays.sort(a);
System.out.println(a[n-1] < a[n]?"YES":... |
You're trying to set the record on your favorite video game. The game consists of N levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the i-th level in either Fi seconds or Si ... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int AK = 1, IOI = 0;
char ch = 0;
while (ch < '0' || ch > '9') {
AK = ch == '-' ? -1 : 1;
ch = getchar();
}
while (ch <= '9' && ch >= '0') {
IOI *= 10;
IOI += ch - 48;
ch = getchar();
}
return AK * IOI;
}
struct nod {
... |
For a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible.
You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. Yo... | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 1;
struct union_find {
int par[N];
int sz[N];
vector<array<int, 2>> stk;
void init(int n) {
iota(par, par + n, 0);
fill(sz, sz + n, 1);
}
int find(int u) {
if (par[u] != u) {
return find(par[u]);
}
return par[u];
}... |
There is a chess tournament in All-Right-City. n players were invited to take part in the competition. The tournament is held by the following rules:
1. Initially, each player plays one game with every other player. There are no ties;
2. After that, the organizers build a complete directed graph with players as v... | #include <bits/stdc++.h>
using namespace std;
long long n, a, b, F[2222], G[2222], C[2222][2222], Rev1[2222][2222],
Rev2[2222][2222], cyc[2222], mulA[2222], mulB[2222];
long long asdfg[12345678];
long long powmod(long long x, long long y = 998244353 - 2,
long long p = 998244353) {
long long ans =... |
Fafa has an array A of n positive integers, the function f(A) is defined as <image>. He wants to do q queries of two types:
* 1 l r x — find the maximum possible value of f(A), if x is to be added to one element in the range [l, r]. You can choose to which element to add x.
* 2 l r x — increase all the elements i... | #include <bits/stdc++.h>
using namespace std;
vector<long long int> diff;
struct iii {
long long int d, e, f;
};
iii comb(iii const& a, iii const& b) {
return {max(a.d, b.d), max(a.e, b.e), max(a.f, b.f)};
}
vector<iii> st;
void build(int idx, int l, int r) {
if (l + 1 == r) {
long long int d1 = -diff[l - 1],... |
One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the ... | #include <bits/stdc++.h>
using namespace std;
const int N = 200010;
vector<int> seg[4 * N];
int arr[N], n;
void build(int s, int e, int idx) {
if (s == e) {
seg[idx].push_back(arr[s]);
return;
}
build(s, (s + e) / 2, idx * 2);
build((s + e) / 2 + 1, e, idx * 2 + 1);
seg[idx] = seg[idx * 2];
for (int... |
Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river.
"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino.
"See? The clouds are coming." Kanno gazes into the distance.
"That can't be better... | #include <bits/stdc++.h>
using namespace std;
long long n, l, w, res;
vector<pair<long long, int> > v;
vector<long long> x, wx, wwx;
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> l >> w;
v.resize(n);
for (int i = 0; i < n; ++i) cin >> v[i].first >> v[i].second;
sort(v.begin(), v.end());
long lo... |
See Russian Translation
Adam and Bob are playing a game. The game is parameterized by the three integers a,b,c. They start out with the integer 1, with Adam going first. Suppose the current integer is S. On a player's turn, he may change the current integer to any integer between a×S and b×S, inclusive. The first play... | t = input()
for i in xrange(t):
a,b,c = map(int, raw_input().split())
y = 0
while c!=1:
if y%2==0:
l = b
else:
l = a
k = c/l
q = (1.0*c)/l
if k==q:
c=k
else:
c = k+1
y+=1
if y%2==0:
print 'Bob'
else:
print 'Adam' |
When the day begins, it's time to sing carols. Unfortunately, not all the family members know the lyrics to the same carols. Everybody knows at least one, though.
You are given a array of lyrics. The j-th character of the i-th element of lyrics is Y if the i-th person knows the j-th carol, and N if he doesn't. Print th... | def arr(p,ar):
n=[]
for i in ar:
if i[p]=='N':
n.append(i)
return n
t=input()
for i in range(t):
n=input()
st=raw_input().split()
ar=[]
for k in range(len(st[0])):
p=k
i=0
c=1
rem=st
while(i<n):
rem=arr(p%len(st[0]),rem)
i=n-len(rem)
#print rem
if len(rem)>0:
p+=1
c+=1
# print... |
Given a square matrix of size N×NN×N, calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, NN. The next NN lines denote the matrix's rows, with each line containing NN space-separated integers describing the columns.
Output Format
Print the abso... | n=input()
prim=[]
seco=[]
arr=[]
k=0
while k<n:
arr=[]
arr=list(map(int,raw_input().split()))
rarr=arr[::-1]
prim.append(arr[k])
seco.append(rarr[k])
k=k+1
addprim=0
addsec=0
for item in prim:
addprim=addprim+item
for key in seco:
addsec=addsec+key
print abs(addprim - addsec) |
Geeko is very happy because his exam are over so he is busy in playing
games and watching movies, today he has watched lord of the rings
He got so fascinated after watching the movie that he is seeing himself
in the movie in his dreams. Suddenly Gollum arrives in his dream and
Ask a riddle to Geeko.
Gollum ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
t = int(raw_input())
while t :
k, n = map(int, raw_input().split())
nodes = 1 + k * (k ** n - 1) / (k -1)
m = 0
while(nodes):
m += nodes%10
nodes... |
There are 'n' ants on a 'n+1' length rod. The ants are numbered from 1 to n and are initially placed at positions starting from position 1 till position n. They are moving either in left direction (denoted by '-1') or in the right direction (denoted by '1'). Whenever an ant crosses the boundary of the rod it falls off ... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
T = input()
for t in xrange(T):
n = input()
directions = map(int, raw_input().split())
p = len([x for x in directions if x == 1])
n = len([x for x in directions if x == -1])
if p >... |
As the Monk is also taking part in the CodeMonk Series, this week he learned about hashing. Now he wants to practice some problems. So he came up with a simple problem. Firstly, he made a hash function F such that:
F(x) = x % 10
Now using this function he wants to hash N integers and count the number of collisions th... | # encoding=utf-8
'''
Created on 2015?8?14?
@author: limw
'''
t = input()
for _ in range(t):
l = input()
kk = raw_input().strip().split(' ')
# print kk
ss = []
for k1 in kk:
ss.append(k1[len(k1) - 1])
ss.sort()
# print ss
sstr = ''.join(ss)
# print sstr
co = 0
for i ... |
Chinna is preparing for an online entrance examination. The performance in the examination is measured on a rating scale of 1 to 10^6. Recently, Chinna came across an advertisement of an institution which guarantees an increase of 'd' in the rating for an examination for an hour of coaching. Chinna wants to excel the p... | n = input()
d = input()
arr = map(int,raw_input().split())
time = 0
prev_rating = arr[0]
for i in range(1,n):
current_rating = arr[i]
if current_rating<=prev_rating:
temp = (prev_rating- current_rating) /d
values = [temp,temp+1]
index = 0
while current_rating<=prev_rating:
current_rating += values[index]*d... |
Roy has a matrix of size NxN. Rows and Columns are numbered from 0 to N-1.
j^th column of i^th row contains i xor j.
In other words, Matrix[i][j] = i ^ j where 0 ≤ i,j < N. ( ^ is a bitwise operation used in C/C++ for xor, please use appropriate symbol if you're using any other language)
Your task is to find the... | for ldskfaj in xrange(int(raw_input())):
n = int(raw_input())
next_max_2_n = 1<<(len(bin(n)) - 2)
if(n<<1 == next_max_2_n):
print n-1, n
else:
print next_max_2_n - 1, next_max_2_n - 2*(next_max_2_n - n) |
Subodh's CS department has been continuously organizing mock placement drives for students. If a student under-performs negative point is rewarded otherwise positive points is rewarded. The HOD wants to find consistency of a student. So, he wants to find out maximum consistent sum of a student score only if his/her ove... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
def mssl(l):
best = cur = 0
for i in l:
cur = max(cur + i, 0)
best = max(best, cur)
return best
n = int(raw_input())
a = []
whil... |
As we have seen that Vaishnav was a smart kid and today he has grown up(but he is still childish)
and he is in High school.
Today he was back from school and found that 4 pieces of Pizza was
ordered- one for his father, one for this mother, and one for Vaishnavi and one for him. But
Vaishnav was little late from schoo... | # http://www.hackerearth.com/tcetcyphers-2/algorithm/vaishnav-and-pizzas/
LIMIT = 10010
phi = [i for i in xrange(LIMIT)]
for i in xrange(2, LIMIT):
if phi[i] == i:
j = i
while j < LIMIT:
phi[j] = phi[j] / i * (i - 1)
j += i
phi[1] = 0
for i in xrange(2, LIMIT):
phi[i] +... |
M-kun is a student in Aoki High School, where a year is divided into N terms.
There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:
* For the first through (K-1)-th terms: not given.
* For each of the K-th through N-th terms: the multipl... | N, K = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N-K):
print('Yes' if A[i+K]>A[i] else 'No') |
We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is `0`, and white if S_{i,j} is `1`.
We will cut the bar some number of times to divide it into some number of blocks. In ea... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,a) for(int i=0;i<(a);i++)
const ll MOD=1000000007;
//const ll MOD=998244353;
int num[11];
int pcnt,H,W,K;
string S[11];
int sum[11];
int judge(){
rep(i,pcnt+1) sum[i]=0;
int res=0,pre=0;
rep(i,W){
rep(j,H){
int k=num[j];... |
Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N. Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:
* Choose two distinct integers x and y between 1 and N (inclusive), and swap the val... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<int, int> > a(n), b(n);
for (int i = 0; i < n; i++) {
cin >> a[i].first;
a[i].second = i;
}
for (int i = 0; i < n; i++) {
cin >> b[i].first;
b[i].second = i;
}
sort(a.begin(), a.end()); // 从小到大排序
sort(... |
There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H). You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the p... | w,h,x,y = map(int,input().split())
print(w*h/2)
print((x==w/2)*(y==h/2))
|
There is a rooted tree (see Notes) with N vertices numbered 1 to N. Each of the vertices, except the root, has a directed edge coming from its parent. Note that the root may not be Vertex 1.
Takahashi has added M new directed edges to this graph. Each of these M edges, u \rightarrow v, extends from some vertex u to it... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
int main() {
int n,m;cin>>n>>m;
vi parent[n], child[n];
vi n_parent(n,0);
int a,b;
rep(i,n-1+m) {
cin>>a>>b;
a--;b--;
child[a].push_back(b);
parent[... |
Given an integer N, find the base -2 representation of N.
Here, S is the base -2 representation of N when the following are all satisfied:
* S is a string consisting of `0` and `1`.
* Unless S = `0`, the initial character of S is `1`.
* Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S... | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
string s;
cin>>n;
if(!n){cout<<0;return 0;}
while(n){
if(n%2){s="1"+s;n--;}
else s="0"+s;
n/=(-2);
}
cout<<s;
} |
You are given a tree with N vertices. The vertices are numbered 0 through N-1, and the edges are numbered 1 through N-1. Edge i connects Vertex x_i and y_i, and has a value a_i. You can perform the following operation any number of times:
* Choose a simple path and a non-negative integer x, then for each edge e that b... | #include<bits/stdc++.h>
#define testbit(mask,i) (((mask)>>(i))&1)
#define setbit(mask,i) ((mask)|(1<<i))
#define delbit(mask,i) ((mask)^(1<<i))
#define randome_generate srand(std::chrono::high_resolution_clock::now().time_since_epoch().count())
using namespace std;
vector<pair<int,int> > ga[100100];
int u,v,w;
int n;
i... |
In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads. The following are known about the road network:
* People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
long long ans = 0;
vector<vector<long long>> a(n, vector<long long>(n));
for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin >> a[i][j];
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
bool need = true;
for(int k=0;k<n;k++... |
Snuke loves "paper cutting": he cuts out characters from a newspaper headline and rearranges them to form another string.
He will receive a headline which contains one of the strings S_1,...,S_n tomorrow. He is excited and already thinking of what string he will create. Since he does not know the string on the headlin... | import java.io.*;
import java.util.*;
public class Main{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next(){
try{
while(st==null||!st.hasMoreElements()){
st = new StringTokeniz... |
Sample testcase 3 has a mistake, so we erased this case and rejudged all solutions of this problem. (21:01)
Snuke got a sequence $a$ of length $n$ from AtCoder company. All elements in $a$ are distinct.
He made a sequence $b$, but actually, he is not remembered it.
However, he is remembered a few things about sequence... | M=10**9+7
o=lambda:map(int,raw_input().split())
n,k=o()
a=o()
dp=[[0]*256 for _ in [0]*(n+1)]
dp[0][0]=1
for i in range(n):
_dp=dp
for l in reversed(range(1,i+2)):
for j in range(256):_dp[l][j]+=dp[l-1][a[i]^j]
dp=_dp
p=[1]*(n+1)
for i in range(n):p[i+1]=p[i]*(i+1)%M
print sum([dp[l][k]*p[l] for l i... |
Ignoring the air resistance, velocity of a freely falling object $v$ after $t$ seconds and its drop $y$ in $t$ seconds are represented by the following formulas:
$ v = 9.8 t $
$ y = 4.9 t^2 $
A person is trying to drop down a glass ball and check whether it will crack. Your task is to write a program to help this ex... | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
double v;
while(cin >> v)
{
cout << ceil(v*v/98.0)+1 << endl;
}
} |
The hero of justice, the Spider, can pull a rope out of his arm and jump from building to building. However, due to the short rope, you can only move to buildings that are less than 50 distances from you. To move to a building farther away, you have to jump to another building.
<image>
Create a program that inputs... | #include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <cfloat>
#include <cmath>
struct Building {
int id;
int x;
int y;
std::vector<int> edge_to;
std::vector<double> dist_to;
};
int main()
{
int n;
while (true) {
std::cin >> n;
if (n==0) break;
Building* bldgs = new Building[n];
... |
A frog is about to return to the burrow. The burrow is D centimeters ahead of the frog, and the frog goes straight toward the burrow. There are only two actions that a frog can do:
* Large jump (go forward L centimeters)
* Small jump (go 1 cm forward)
The frog aims to just land in the burrow without jumping over it... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
// Welcome to my source code!
int main() {
int d, l;
cin >> d >> l;
int t = d - (d / l) * l;
int ans = t + (d / l);
cout << ans << endl;
}
|
problem
You want to get a treasure on the Nth basement floor of a dungeon. First, you are on the 1st basement floor and your health is H (H is a positive integer). Go downstairs. Sometimes physical strength is consumed. The physical strength consumed when descending to the lower floor on each floor is known in advance... | #include<cstdio>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
long long n,h,d,p,y,x,z;
deque<pair<long long,long long> > w;
int main(){
scanf("%lld%lld", &n, &p);
y = p;
for(int i = 0;i < n - 1;i++){
scanf("%lld%lld", &d, &h);
while(!w.empty() && w.back().first < h){
w.pop... |
The morning of office workers is early. When I went through the elite course, joined a first-class company, and graduated from the title of newcomer, the resignation I received was a business activity on an undeveloped planet. I have been forced to live inconveniently in a remote area, but for the time being, it is not... | import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
class Main {
private static void solve() {
final Scanner scanner = new Scanner(System.in);
while (true) {
final int q = scanner.nextInt();
final int lim = scanner.nextInt();
if (q == 0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.