input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by <image>. A Modular Equation, as Hamed's teacher described, is an equation of the form <image> in which a and b are two non-negative integers a... | /* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(Syste... |
A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.
... | #include <bits/stdc++.h>
using namespace std;
template <class T1>
void deb(T1 e1) {
cout << e1 << endl;
}
template <class T1, class T2>
void deb(T1 e1, T2 e2) {
cout << e1 << " " << e2 << endl;
}
template <class T1, class T2, class T3>
void deb(T1 e1, T2 e2, T3 e3) {
cout << e1 << " " << e2 << " " << e3 << endl;
... |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | price = 0
iter = 1
k,n,w = list(map(int,input().split()))
for i in range (w):
price += k*iter
iter += 1
if price <= n:
print(0)
else:
output = price - n
print(output)
|
You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the l... | #include <bits/stdc++.h>
using namespace std;
long long ans = 0;
const int mod = 1e9 + 7;
long long rec(int a, int b, int c, int s) {
if (a < b + c) return (long long)0;
long long cur = min(s, a - b - c);
return (cur + 1) * (cur + 2) / 2;
}
int main() {
long long a[6], l;
cin >> a[0] >> a[1] >> a[2] >> l;
f... |
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.
V... | #include <bits/stdc++.h>
using namespace std;
int n, i, ans, a[500100];
int main() {
cin >> n;
for (i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + n + 1);
ans = 1000000000;
for (i = 1; i + n / 2 <= n; i++) ans = min(ans, a[i + n / 2] - a[i]);
cout << ans;
return 0;
}
|
Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.
Input
The first line of the input contains a sing... | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.security.KeyStore.Entry;
import java.util.*;
public class Main {
private InputStream is;
private PrintWriter out;
int time = 0, dp[][], DP[][], prime[], start[], parent[], end[], val[], black[], arr[], arr1[];
long MOD = (long)(1... |
Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count ... | #include <bits/stdc++.h>
using namespace std;
const int N = 3005;
struct node {
int x, y;
} a[N], b[N];
int r, c, n, K, cnt, nxt[N], lst[N], w, i, j, k, x, y;
long long ans;
vector<int> vct[N];
bool cmp(node a, node b) {
if (a.y != b.y) return a.y < b.y;
return a.x < b.x;
}
int work(int l) {
int i = l;
for (i... |
Consider a regular Codeforces round consisting of three problems that uses dynamic scoring.
You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack i... | #include <bits/stdc++.h>
using namespace std;
int n;
tuple<int, int, int> ar[5005];
int h[] = {0, 0, 0};
int nonzero[] = {0, 0, 0};
bool ok(int s, int i) {
switch (s) {
case 500:
return (nonzero[i] * 2) > n && ((nonzero[i] - h[i]) * 2 <= 2 * n);
break;
case 1000:
return (nonzero[i] * 4) > n ... |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | import java.util.Scanner;
public class ugh {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
StringBuilder s = new StringBuilder(in);
System.out.println(s.toString()+s.reverse().toString());
}
}
|
The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here https://en.wikipedia.org/wiki/King_(chess).
<image> King moves from the posi... | if __name__ == '__main__':
P = list(raw_input())
r, c = P
r = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}[r]
c = int(c)
if 2 <= r <= 7 and 2 <= c <= 7:
print 8
elif abs(r-c) in [0, 7]:
print 3
else:
print 5
|
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | import sys
from math import ceil,log
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in ra... |
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For e... | #include <bits/stdc++.h>
using namespace std;
long long parent(long long par[], long long idx) {
if (par[idx] == idx) return idx;
return par[idx] = parent(par, par[idx]);
}
void solve() {
long long n;
cin >> n;
long long arr[n], i, par[n + 1], x, y, ans = 0;
for (i = 0; i < n; i++) cin >> arr[i];
for (i =... |
Moriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are m switches. Each switch control doors of some rooms, but each door is controlled by... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, m, a[N], p[N << 1], b[N][2];
void nhap() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
for (int i = 1; i <= m; ++i) {
int sz;
scanf("%d", &sz);
for (int j = 1; j <= sz; ++j) {
int u;
sc... |
Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. T... | #include <bits/stdc++.h>
using namespace std;
string expr[200];
int dp[200][2];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
cin.ignore();
map<string, int> id;
for (int i = 0; i <= n; i++) {
string line;
getline(cin, line);
stringstream ss(line);
string tmp;
if (i... |
Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point (x, y) in the 2D plane such that x and y are integers and 0 ≤ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other point... | import java.util.Scanner;
public class P821B
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int m = scan.nextInt();
int b = scan.nextInt();
long max = 0;
int y = b;
int rem = 0;
int x = 0;
while (y >= 0)
{
max = Math.max(max, sum(x)*(y+1) + sum(y)*(x+1));
if... |
Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.
Ivan represent his array with increasing sequences with h... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long inf = 1e9 + 21;
long long powmod(long long a, long long b) {
long long res = 1;
a %= mod;
assert(b >= 0);
for (; b; b >>= 1) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
}
return res;
}
template <ty... |
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation ... | #include <bits/stdc++.h>
using namespace std;
char s[105][105];
char pre[205][10], nxt[205][10];
set<int> S[205][10];
int main() {
int n = 0, q, a, b;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%s", s[i]);
int m = strlen(s[i]);
for (int j = 0; j < m; ++j)
for (int k = j; k < j + 9 &&... |
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoy... | import java.util.Scanner;
public class Temp1
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
String s = obj.nextLine();
int n = s.length();
boolean visited[] = new boolean[n];
int counter = 0;
for(int i=0 ; i<n-2 ; i++)
{
if(s.charAt(i) == 'Q')
{
fo... |
You are given a [directed graph](https://en.wikipedia.org/wiki/Directed_graph) consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph [acyclic](https://en.wikipedia.org/wiki/Directed_acyclic... | import java.io.*;
import java.util.*;
public class CF915D
{
static final boolean _DEBUG = true;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(BufferedReader _br) {
br = _br;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new S... |
You are given an array a of length n. We define fa the following way:
* Initially fa = 0, M = 1;
* for every 2 ≤ i ≤ n if aM < ai then we set fa = fa + aM and then set M = i.
Calculate the sum of fa over all n! permutations of the array a modulo 109 + 7.
Note: two elements are considered different if their i... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6 + 99;
const long long mod = 1e9 + 7;
long long N, cur, res, arr[MAX], fact[MAX], ifact[MAX];
long long power(long long base, long long exp) {
long long res = 1;
while (exp) {
if (exp % 2) res *= base;
base *= base;
res %= mod;
base %=... |
A chip was placed on a field with coordinate system onto point (0, 0).
Every second the chip moves randomly. If the chip is currently at a point (x, y), after a second it moves to the point (x - 1, y) with probability p1, to the point (x, y - 1) with probability p2, to the point (x + 1, y) with probability p3 and to t... | #include <bits/stdc++.h>
using namespace std;
bool debug = 0;
int n, m, k;
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
string direc = "RDLU";
long long ln, lk, lm;
void etp(bool f = 0) {
puts(f ? "YES" : "NO");
exit(0);
}
void addmod(int &x, int y, int mod = 1000000007) {
assert(y >= 0);
x += y;
if (x >... |
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.
Some of them celebrated in the BugDonalds restaurant, some of them... | n=list(map(int,input().split()))
s=n[0]-n[2]
v=n[1]-n[2]
w=n[3]-(s+v+n[2])
if(w==0 or s<0 or v<0 or w<0):
print('-1')
elif(w>n[3]):
print(-1)
else:
print(w)
|
You came to a brand-new aqua park. In this aqua park you are not sliding like in most of aqua parks, but falling.
There are N objects. Each object is non-horizontal and non-vertical segment. When you fall on the segment you start sliding on it and when you reach its lowest point you continue falling vertically. Then yo... | x,n=(int(i) for i in raw_input().split())
l=[]
for kkk in range(0,n):
x1,y1,x2,y2=(int(i) for i in raw_input().split())
if y1<=y2:
l.append([y1,y2,x1,x2])
else:
l.append([y2,y1,x2,x1])
l.sort(reverse=True)
index=0
while index<n:
if min(l[index][2],l[index][3])<=x<=max(l[index][2],l[index... |
After setting up the area. Chandu wanted all his toys to be stacked there in that area. So that all of them are accessible easily. Currently, He is having N stacks of toys each with height H_1,H_2...H_n (assuming all toys are of same height).Chandu did not like the configuration much and want to change the height of ea... | T = input()
def brokenInput():
A = map(int, raw_input().strip().split())
while len(A) < 3:
A += map(int, raw_input().strip().split())
return A
for _ in xrange(T):
N, X, Y = brokenInput()
effortRequired = 0
initList = []
finalList = []
stacks = {}
for __ in xrange(N):
initH, finalH = map(int, raw_input().... |
Given an array A of size N. Given Q operations, each operation contains an integer D. In each operation you have to divide all the elements of the array by D.
For example, for each operation with a given D, the new array A would be:
A[0] / D, A[1] / D, A[2] / D, ..... , A[N-1] / D
Finally, after processing all the o... | r = input()
A = map(int, raw_input().split())
s = 1
for i in range(input()):
s *= input()
for i in A:
print i/s, |
Chandan, our problem moderator, recently got a digital clock as a birthday present. A digital clock shows time in the format HH:MM:SS, where HH, MM, SS represents hours , minutes, and seconds respectively. It is a 24 hour clock and so the day starts at 00:00:00 hours while it ends at 23:59:59.
We all know how punctual... | import fractions
def factors(num):
ans = set()
for i in range(2,num+1):
if num%i == 0:
ans.add(i)
return ans
sets = []
for i in range(0,61):
sets.append(factors(i))
ans = [0]*86400
hrs = 0
mins = 0
secs = 0
k = 0
while hrs != 24:
while secs != 60:
while mins != 60:
count = 0
if hrs == 0:
count += ... |
Little Deepu loves positive things in life, positive girlfriends, positive marks. He's, in general a lover of positive things, so for obvious reasons he loves an array which contains positive elements.
Anyway, Little Deepu also thinks that not every value in his so called positive array deserves to be valued so high, ... | n=int(raw_input())
a=map(int,raw_input().split())
for i in xrange(n):
a[i]=[a[i],i]
a.sort()
temp=[]
def binary_search(low,high,x):
global a
if high>=low:
mid=low+(high-low)/2
#print mid,"mid"
if ((a[mid][0]-findpindex(mid))>x and (mid == low or (a[mid-1][0]-findpindex(mid-1))<=x)):
... |
Today is the 25th anniversary of Berland International School in Berland. On this auspicious Occasion, our friend Monk has been given the responsibility of preparing the Inventory for his school.
There are exactly N teachers and M students in the school. Each of these teachers teaches arbitary number of students. Ho... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
n,m=[int(i) for i in raw_input().split()]
l=[]
d=dict()
for i in range(n):
l.append(raw_input())
for i in range(m):
info=raw_input()
pos=info.find(' ')
a=info[:pos]
... |
Given an array A. Is there any subset of array A in which if we do AND of all elements of that subset then output should be in power of two (for example : 1,2,4,8,16 and so on ).
Input:
First line contains number of test cases T. Each test first line contains N size of array A and next line contains N space separ... | import math
T=int(raw_input())
while T>0:
l=int(raw_input())
n=list(raw_input().split())
flag=0
for i in xrange(0,l):
for j in xrange(i,l):
pro=int(n[i])
for m in xrange(j,l):
pro=pro&int(n[m])
if pro and (pro & (pro - 1))==0:
... |
Saksham is fond of perfection in everything. He is also fond of playing FIFA so he likes to have perfection in his shots while shooting for a goal. Consider there is a goalpost, it has two corners left corner and right corner. There is a line in the center of the goalpost. If the player is on the left of the line it is... | '''
# 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=input()
ma,i=0,0
while t>0:
t-=1
m,n=map(int,raw_input().split())
if m>ma:
ma=m
i=n
if i>0:
print"Left Corner"
elif i<0:
print"Right Corner"
else:
prin... |
You need to find if a number can be expressed as sum of two perfect powers. That is, given x find if there exists non negative integers a, b, m, n such that a^m + b^n = x.
Input
First line of the input contains number of test cases T. It is followed by T lines, each line contains a sinle number x.
Output
For each te... | a=[]
for i in range(2,1000):
for j in range(2,21):
p=i**j
if(p>1000000):
break
a.append(p)
a.append(1)
x=input();
for i in range(1,x+1):
y=input()
f=0
d=0
for f in range(0,len(a)):
if y-a[f] in a:
print "Yes"
d=2
break... |
An intergallactic war is on. Aliens are throwing fire-balls at our planet and this fire is so deadly that whichever nation it hits, it will wipe out not only that nation, but also spreads to any other nation which lies adjacent to it.
Given an NxM map which has N x M cells. Each cell may have a country or else it may... | def burnTheNations(point):
global unburnt
global mapOfWorld
if (mapOfWorld[point[0]][point[1]]) == 0:
return
mapOfWorld[point[0]][point[1]] = 0
unburnt -= 1
# calculate neighbors 'n' of attackPoint that are 1
neighbor = []
if point[0] > 1:
neighbor.append([point[0]-1, point[1]])
if point[1] > 1... |
Given are N integers A_1,\ldots,A_N.
We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.
Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).
Constraints
* 1 \leq K \leq N \leq 2\times 10^5
* |A_i| \leq 10^9
Input
Inp... | import operator
from functools import reduce
N, K = map(int, input().split())
A = list(map(int, input().split()))
MOD = 10 ** 9 + 7
positives = [a for a in A if a > 0]
negatives = [a for a in A if a < 0]
positive_cnt = len(positives)
negative_cnt = len(negatives)
zero_cnt = A.count(0)
if 2 * min(K // 2, negative_cnt... |
A Hitachi string is a concatenation of one or more copies of the string `hi`.
For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not.
Given a string S, determine whether S is a Hitachi string.
Constraints
* The length of S is between 1 and 10 (inclusive).
* S is a string consisting of lowerc... | import java.io.PrintStream;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception{
new Main(new Scanner(System.in), System.out, System.err).exec();
}
public final Scanner sc;
public final PrintStream out, err;
public Main(final Scanner sc, final PrintStream out, f... |
Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)
We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.
Whe... | import math
a,b,x = map(int,input().split())
v = a*a*b
if 2*x <= v:
ans = math.atan((a*b*b)/(2*x))
else:
ans = math.atan((2*(v-x)/(a*a))/a)
print(math.degrees(ans))
|
There are N squares arranged in a row, numbered 1, 2, ..., N from left to right. You are given a string S of length N consisting of `.` and `#`. If the i-th character of S is `#`, Square i contains a rock; if the i-th character of S is `.`, Square i is empty.
In the beginning, Snuke stands on Square A, and Fnuke stand... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Input... |
There is a grid with H rows and W columns, where each square is painted black or white.
You are given H strings S_1, S_2, ..., S_H, each of length W. If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is `#`; if that square is painted whi... | #include<bits/stdc++.h>
using namespace std;
int gox[4] = {1,-1,0,0};
int goy[4] = {0,0,1,-1};
typedef long long ll;
bool vis[410][410];
int n,m;
char a[410][410];
ll num1,num2;
void dfs(int x,int y,char f){
vis[x][y] = 1;
if(f=='#')
num1++;
else num2++;
for(int i=0;i<4;i++){
int nowx = ... |
You are given a string S of length 2N, containing N occurrences of `a` and N occurrences of `b`.
You will choose some of the characters in S. Here, for each i = 1,2,...,N, it is not allowed to choose exactly one of the following two: the i-th occurrence of `a` and the i-th occurrence of `b`. (That is, you can only cho... | #include<iostream>
#include<stack>
#include<vector>
using namespace std;
vector<string> str,damn;
vector<string> lis;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n,i,j,k,l,lst=0,numa=0,numb=0,ite,nowa=0,nowb=0;
string s,t,hix;
cin>>n>>s;
for(i=0;i<2*n;i++){
if(s[i]=='a'){
numa++;
}
else{
numb... |
AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K. Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square. Below is an example of a checked pattern of side 3:
cba927b2484f... | #include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=1005;
int map[MAXN][MAXN];
int n,k;
int main()
{
scanf("%d %d",&n,&k);
int mi=n,ma=0;
for(int i=1;i<=n;i++)
{
long long xx=0,yy=0;
char c;
bool t;
scanf("%I64d %I64d %c",&xx,&yy,&c);
xx%=2*k;
yy%=... |
In the city of Nevermore, there are 10^8 streets and 10^8 avenues, both numbered from 0 to 10^8-1. All streets run straight from west to east, and all avenues run straight from south to north. The distance between neighboring streets and between neighboring avenues is exactly 100 meters.
Every street intersects every ... | #include <bits/stdc++.h>
using namespace std;
const int N = 200100;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1);
int lis(int a[], int n){
vector <int> A(n, INF);
for(int i = 0; i < n; i++){
*lower_bound(A.begin(), A.end(), a[i]) = a[i];
}
return find(A.begin(), A.end(), INF) - A.begin();
}
int mai... |
Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest. In this game, an honest player always tells the truth, and an dishonest player always tell lies. You are given two characters a and b as the input. Each of them is either `H` or `D`, and carries the following information:
If a=`H`, AtCoDe... | #include<bits/stdc++.h>
using namespace std;
int main(){
char a,b;
cin>>skipws>>a>>b;
int c=(a=='H')^(b=='H');
cout<<(c?'D':'H')<<endl;
} |
There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.
Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:
* Move: ... | #include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
int main(){
int n,t; cin>>n>>t;
vector<int> a(n);
for(int i=0;i<n;i++) cin>>a[i];
int profit=0,sml=a[0],pattern=0;
for(int i=1;i<n;i++){
if(sml>a[i]){
sml=a[i];
}
else if(a[i]-sml>profit){
profit=a[i]-sml;
pattern=1;
... |
Create a program that reads poker hand data and outputs the role for each. However, this issue follows the rules below.
* Poker is a competition with 5 playing cards.
* No more than 5 cards with the same number.
* There is no joker.
* Suppose you only consider the following poker roles: (The higher the number, the hig... | import java.util.Scanner;
public class Main {
public static String sarch(int in[]){
int i;
//four
for(i=1;i<4;i++){
if(in[0]!=in[i]){
break;
}
}
if(i==4)
return "four card";
for(i=2;i<5;i++){
if(in[1]!=in[i]){
break;
}
}
if(i==5)
return "four card";
//full house
if(in[0]==... |
I bought food at the store to make a lunch box to eat at lunch. At the store, I only got an elongated bag to put food in, so I had to stack all the food vertically and put it in the bag. I want to pack the bag with the heavy ones down so that it won't fall over, but some foods are soft and will collapse if I put a heav... | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
struct food{
string n;
int w;
int s;
int used;
};
int main(){
int n;
while(cin >> n){
vector<food> vf;
if(n == 0 ) break;
for(int i = 0; i < n; i++){
food f;
cin >> f.n >> f.w >> f.s;
f.used = 0;
... |
You are working on the development of the unique operating system "Unsgune 15" and are struggling to design a scheduler that determines performance. A scheduler is a program that expresses the processes to be executed in units called tasks and determines the order in which they are executed. The scheduler manages tasks... | #define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include... |
problem
JOI, who has been suffering from his winter vacation homework every time, decided to do his homework systematically this time. Homework is a national language and math drill, with a national language drill on page A and a math drill on page B.
JOI can advance the Japanese drill up to C pages and the math dril... | a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
if b%d == 0:
x = b // d
else:
x = b // d +1
if c%e == 0:
y = c // e
else:
y = c // e +1
if x >= y:
print(a-x)
else:
print(a-y)
|
A text editor is a useful software tool that can help people in various situations including writing and programming. Your job in this problem is to construct an offline text editor, i.e., to write a program that first reads a given text and a sequence of editing commands and finally reports the text obtained by perfor... | #include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
string s;
int nextWordToFor(int cur)
{
if(cur==s.size()) return cur;
for(; cur<s.size(); cur++)
{
if(s[cur]!=' ') break;
}
for(; cur<s.size(); cur++)
{
if(s[cur]==' ') break;
}
return cur;
}
int nextWordTo... |
You are appointed director of a famous concert hall, to save it from bankruptcy. The hall is very popular, and receives many requests to use its two fine rooms, but unfortunately the previous director was not very efficient, and it has been losing money for many years. The two rooms are of the same size and arrangement... | #include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
int dp[400][400];
vector<pair<int,int> > v[400];
int main(){
int a;
while(scanf("%d",&a),a){
for(int i=0;i<400;i++)v[i].clear();
for(int i=0;i<a;i++){
int x,y,z;scanf("%d%d%d",&x,&y,&z);
x--;y--;
v[x].push_back(make_pair(y,z));
... |
Example
Input
4
B
W
WB
WB
Output
5 | #include <bits/stdc++.h>
using namespace std;
double value[45];
int size[45];
double get_value(string &pile){
bool b_can_move = 0, w_can_move = 0;
double b_max, w_min;
double last_value = 0;
for(int i=0;i<pile.length();i++){
double value;
if(pile[i]=='B'){
if(b_can_move){
... |
Deadlock Detection
In concurrent processing environments, a deadlock is an undesirable situation where two or more threads are mutually waiting for others to finish using some resources and cannot proceed further. Your task is to detect whether there is any possibility of deadlocks when multiple threads try to execute... | #include <bits/stdc++.h>
using namespace std;
vector<vector<int> > A;
typedef pair<int,int> P;
bool bfs(){
sort(A.begin(),A.end());
A.erase(unique(A.begin(),A.end()),A.end());
int n = A.size();
for(int i=0;i<n;i++)
for(int j=0,used[10]={};j<A[i].size();j++)if(used[A[i][j]]++) return 1;
queue<P> Q;
boo... |
Your friend recently came up with a card game called UT-Rummy.
The cards used in this game are numbered red, green, or blue and any number from 1 to 9. Each player in this game has 9 cards in his or her hand, chooses one from his or her hand, discards it, and draws one from the deck instead. In this way, the turn is a... | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstring>
using namespace std;
int main(){
int n;
int card[3][10];
cin>>n;
while(n--){
int a[10];
memset(card, 0, sizeof(card));
for(int i=0; i<9; ++i){
cin>>a[i];
}
for(int i=0; i<9; ++i){
char b;
... |
As many of you know, we have two major calendar systems used in Japan today. One of them is Gregorian calendar which is widely used across the world. It is also known as “Western calendar” in Japan.
The other calendar system is era-based calendar, or so-called “Japanese calendar.” This system comes from ancient Chines... | import java.util.Arrays;
import java.util.Scanner;
public class Main{
static Scanner s = new Scanner(System.in);
static class calendarSystem implements Comparable<calendarSystem>{
String EraName;
int EraBasedYear;
int WesternYear;
calendarSystem(String eraName, int eraBasedYear... |
Takahashi decided to go sightseeing in New York with Apple. Takahashi didn't have any particular hope for sightseeing, but due to Sachika-chan's enthusiastic invitation, he decided to go sightseeing in the "hosonogai place" as shown in the map below.
<image> Google Maps-(C) 2012 Google
This "horizontal place" is very... | #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>... |
One-day pass
Mr. D, a university student living in a certain country, is a big fan of Mr. A, a national guitarist, and is thinking of going to a live concert in the city center this summer. However, since Mr. D lives in a remote area, he was very worried about the cost of transportation. At that time, he learned of th... | #include <bits/stdc++.h> // {{{
#define ARG5(a, b, c, d, NAME, ...) NAME
#define REP(...) ARG5(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)
#define REP1(a) REP2(i, a)
#define REP2(i, a) REP3(i, 0, a)
#define REP3(i, a, b) REP4(i, a, b, 1)
#define REP4(i, a, b, s) for (int i = (a); i < (int)(b); i += (s))
#define ... |
C --Misawa's rooted tree
Problem Statement
You noticed that your best friend Misawa's birthday was near, and decided to give him a rooted binary tree as a gift. Here, the rooted binary tree has the following graph structure. (Figure 1)
* Each vertex has exactly one vertex called the parent of that vertex, which is c... | #include <bits/stdc++.h>
using namespace std;
pair<int,int> get_mid(string t) {
int mid_s = t.size();
int mid_e = 0;
for (int i = 1, c = 1; i < t.size(); i++) {
if (t[i] == ')') c--;
else if (t[i] == '(') c++;
else if (!c) {
mid_s = min(mid_s, i);
mid_e = ma... |
problem
AOR Ika got a water tank with a size of $ 1 $ in length and $ N $ in width. The aquarium is tall enough to hold water. The aquarium has $ N-1 $ partitions and is evenly spaced into $ N $ compartments. When water was poured here, the height of the water in each section became $ a_i $.
AOR Ika decided to remove... | //無心でDPします
#include <iostream>
#include <algorithm>
#include <cstdio>
#define rep(i, n) for (i = 0; i < n; i++)
#define repn(i, m, n) for (i = m; i < n; i++)
#define int long long
using namespace std;
int INF = 1e+12;
int n, m;
int a[500];
int ra[501];
double dp[501][501]; //dp[pos][cnt] = max
signed main() {
int i,... |
Problem
There is a grid of $ N \ times N $ cells. Initially all cells are white. Follow the steps below to increase the number of black squares.
Select one white cell from the cells that are even-numbered from the top and even-numbered from the left. The selected square turns black. Further, the adjacent white square... | #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
#define fi first
#define se second
#define MAX 2055
char s[MAX][MAX];
int n;
int dx1[]={0,0,1,-1};
int dy1[]={1,-1,0,0};
int dx2[]={1,-1};
int dy2[]={1,1};
int color[MAX][MAX];
int table[MAX][MAX];
int cnt[MAX][MAX];
bool used[2][MAX][MAX];
... |
Notes
Template in C
Constraints
2 ≤ the number of operands in the expression ≤ 100
1 ≤ the number of operators in the expression ≤ 99
-1 × 109 ≤ values in the stack ≤ 109
Input
An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.
You can assume that +... | class Stack:
def __init__(self):
self.values = []
def push(self,v):
self.values.append(v)
def pop(self):
if len(self.values) == 0:
raise
else:
v = self.values[len(self.values)-1]
del self.values[len(self.values)-1]
return v
s... |
Write a program which reads a list of student test scores and evaluates the performance for each student.
The test scores for a student include scores of the midterm examination m (out of 50), the final examination f (out of 50) and the makeup examination r (out of 100). If the student does not take the examination, t... | # coding: utf-8
while True:
m,f,r = map(int,input().split())
if m == f == r == -1:
break
if m == -1 or f == -1 or (m + f) < 30:
print("F")
elif (m + f) >= 80:
print("A")
elif (m + f) >= 65:
print("B")
elif (m + f) >= 50 or r >= 50:
print("C")
... |
Given a undirected graph find the number of connected components.
Input
First line of the input is 't'- number of test case. Followed by N, the number of vertices (Numbered 0 to N-1). Followed by 'e' number of edges. Followed by description of 'e' edges in the form 'a b' I.e. an edge exist between vertex a and b.
... | def dfs(start):
if visited[start]:return 1
stack=[start]
while (stack!=[]):
x = stack.pop()
visited[x]=color
for i in graph[x]:
if visited[i]:continue
stack.append(i)
return 1
def bfs(start):
if visited[start]:return 1
queue=[start]
while (queue!=[]):
x = queue.pop(0)
visited[x]=color
for i in ... |
Given a list of sentences, for each sentence, determine if it is a pangram or not.
pangrams are sentences constructed by using every letter of the alphabet at least once.
For example: How quickly daft jumping zebras vex
Input
The first line contains T, the number of test cases.
The following lines will contain... | def is_pangram(phrase):
alphabet = "abcdefghijklmnopqrstuvwxyz"
return not (set(alphabet) - set(phrase))
for i in range(input()):
print (str(is_pangram(raw_input().lower())).upper()) |
Problem Statement
Lira is a little girl form Bytenicut, a small and cozy village located in the country of Byteland.
As the village is located on a somewhat hidden and isolated area, little Lira is a bit lonely and she needs to invent new games that she can play for herself.
However, Lira is also very clever, so, she... | def area(triangle):
x1,y1,x2,y2,x3,y3=map(int,triangle)
return abs((x1*y2-x2*y1)+(x2*y3-x3*y2)+(x3*y1-x1*y3))
t=int(raw_input())
large=0
small=0
i=1
large_area=0
small_area=1000000000
while(i<=t):
triangle=raw_input().split()
s=area(triangle)
if(s<=small_area):
small_area=s
small=i
if(s>=large_area):
... |
Chef is fan of pairs and he likes all things that come in pairs. He even has a doll collection in which all dolls have paired.One day while going through his collection he found that there are odd number of dolls. Someone had stolen a doll!!!
Help chef find which type of doll is missing..
Input
The first line conta... | def main():
num=input()
ans=[]
p=[]
for t in xrange(num):
x=input()
#print p
if(x in p):
p.remove(x)
else:
p.append(x)
return p[0]
ts=input()
for t in xrange(ts):
print main() |
NOTE :This problem is just a test problem. The submissions to this problem will not be counted in the final ranklist for prize distribution. We apologize for the inconvenience caused.
Problem description
Given two integers A and B that are not necessarily in base-10, find the smallest possible A + B in base-10.
Fo... | import sys
def base(n):
max=0
while(n!=0):
if(n%10 > max):
max=n%10
n=n/10
return max+1
def convert(n,b):
i=0
sum=0
while(n!=0):
sum+=(n%10)*pow(b,i)
i=i+1
n=n/10
return sum
def main():
t=int(raw_input())
while(t!=0):
a,b=map(int,raw_input().split())
a=convert(a,base(a))
b=convert... |
Taru likes reading. Every month he gets a copy of the magazine "BIT". The magazine contains information about the latest advancements in technology. Taru
reads the book at night and writes the page number to which he has read on a piece of paper so that he can continue from there the next day. But sometimes
the pa... | t = int(raw_input())
for i in range(0,t):
list = []
sum = 0
n = int(raw_input())
sum = ((n)*(n+1))/2
if n%2 ==0:
n = n/2
else:
n = (n+1)/2
number_notprinted = raw_input()
list = number_notprinted.split(" ")
for j in range(1,len(list)):
sum-=int(list[j])
number_torn = int(raw_input())
number_left = n-... |
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.
There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st... | import math
import random
def get(dtype=int):
return dtype(raw_input())
def array(dtype=int):
return [dtype(num) for num in raw_input().split()]
def cmp(x, y):
if x[0] > y[0] or x[0] == y[0] and x[1] < y[1]:
return -1
if x[0] == y[0] and x[1] == y[1]:
return 0
return 1
def solv... |
There are two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route.
At each station one can find a sorted list of moments of time when a... | #include <bits/stdc++.h>
using namespace std;
const long long N = 2 * 1e5 + 10;
long long INF = 100000000;
long long n, t, a[N], x[N], b[N];
int main() {
cin >> n >> t;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {
cin >> x[i];
}
for (int i = 1; i <= n; i++) {
if (... |
This is an interactive problem.
In good old times dwarves tried to develop extrasensory abilities:
* Exactly n dwarves entered completely dark cave.
* Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves.
* Dwarves went out ... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const long long inf = 1e18;
long long modpow(long long a, long long e) {
if (e == 0) return 1;
long long x = modpow(a * a % mod, e >> 1);
return e & 1 ? x * a % mod : x;
}
int n, now = 1;
int l, r = 1e9, md, pos, tr;
string s, t;
int main() {
... |
Vasya likes to solve equations. Today he wants to solve (x~div~k) ⋅ (x mod k) = n, where div and mod stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, k and n are positive integer parameters, and x is a positive integer unknown. If there are several solu... | import java.util.*;
import java.io.*;
//import javafx.util.Pair;
public class Main implements Runnable
{
static class Pair implements Comparable <Pair>
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
public int compareTo(Pair p)
... |
Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gav... | #include <bits/stdc++.h>
using namespace std;
const int N = 25e4 + 10;
int n, m, k, par[N], high[N], mark[N];
vector<int> leaf, adj[N];
void make_par(int v = 0, int p = 0, int h = 0) {
mark[v] = 1;
par[v] = p;
high[v] = h;
for (int i : adj[v])
if (!mark[i]) make_par(i, v, h + 1);
}
void solve(int v) {
int... |
You have a long fence which consists of n sections. Unfortunately, it is not painted, so you decided to hire q painters to paint it. i-th painter will paint all sections x such that l_i ≤ x ≤ r_i.
Unfortunately, you are on a tight budget, so you may hire only q - 2 painters. Obviously, only painters you hire will do t... | import java.io.*;
import java.util.*;
public class Main {
static PrintStream out = System.out;
static void solve(InputStream stream) {
Scanner in = new Scanner(new BufferedInputStream(stream));
int n = in.nextInt();
int Q = in.nextInt();
int[] L = new int[Q + 1];
int[]... |
This problem is same as the next one, but has smaller constraints.
Aki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.
There are n planets in the Catniverse, numbered from 1 to n. At the beginning of the game, Aki chooses the planet where ... | #include <bits/stdc++.h>
long long n, k, m;
long long dp[100005][14][1 << 4];
signed main() {
scanf("%lld %lld %lld", &n, &k, &m);
dp[0][0][0] = 1;
for (long long i = 0; i < n; i++)
for (long long j = 0; j <= k; j++)
for (long long s = 0; s < (1 << m); s++) {
dp[i + 1][j][s >> 1] =
(... |
Given two integers n and x, construct an array that satisfies the following conditions:
* for any element a_i in the array, 1 ≤ a_i<2^n;
* there is no non-empty subsegment with [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) equal to 0 or x,
* its length l should be maximized.
A sequenc... | #include <bits/stdc++.h>
using namespace std;
bool ex[(1 << 18)];
int main() {
int n, x;
cin >> n >> x;
ex[0] = 1;
vector<int> v({0});
for (int i = 1; i < (1 << n); i++) {
if (ex[i ^ x]) continue;
v.push_back(i);
ex[i] = 1;
}
printf("%d\n", v.size() - 1);
for (int i = 1; i < v.size(); i++) p... |
A cubeword is a special type of a crossword. When building a cubeword, you start by choosing a positive integer a: the side length of the cube. Then, you build a big cube consisting of a × a × a unit cubes. This big cube has 12 edges. Then, you discard all unit cubes that do not touch the edges of the big cube. The fig... | #include <bits/stdc++.h>
using namespace std;
using nagai = long long;
const int N = 100100;
const int mod = 998244353;
int cnt = 0;
map<char, int> mp;
const int C = 64;
int c[C][C];
int ind(char ch) {
if (!mp.count(ch)) mp[ch] = cnt++;
return mp[ch];
}
void ad(int& x, int y) {
if ((x += y) >= mod) x -= mod;
}
in... |
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.
Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i... | #include <bits/stdc++.h>
using namespace std;
int N, band, p, mark[7005];
long long sol;
struct dos {
long long a, b;
} A[7005];
bool comp(const dos &h, const dos &k) { return h.a < k.a; }
queue<int> Q;
vector<int> G[7005], S;
void bfs(int nod) {
Q.push(nod);
mark[nod] = 1;
sol += A[nod].b;
band = 0;
while ... |
Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.
There are n people working for VoltModder, numbered from 1 to n. Each employee earns a different amount of money in the company — initia... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5 + 1;
static vector<vector<int>> vert(MAXN, vector<int>(0));
static int outdeg[MAXN];
static int indeg[MAXN];
int n, m;
long long ans = 0;
static void solveShit() {
int v;
scanf("%d", &v);
ans -= (long long)indeg[v] * (long long)outdeg[v];
f... |
Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell (0, 0) on an infinite grid.
You also have the sequence of instructions of this robot. It is written as the string s consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell (x, y) right now, he can move to... | n = int(input())
for i in range(n):
s = input()
l, r, u, d = 0, 0, 0, 0
for v in s:
if v == 'L':
l += 1
if v == 'R':
r += 1
if v == 'U':
u += 1
if v == 'D':
d += 1
if l == 0 or r == 0:
if u and d:
print(2)
print('UD')
else:
print(0)
elif u == 0 or d == 0:
if l and r:
print(2)
... |
You are given two strings s and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be deri... | import java.util.*;
import java.io.*;
public class ProbC {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
T... |
It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.
You are given two polynomials f(x) = a_0 + a_1x + ... + a_{n-1}x^{n-1} and g(x) = b_0 + b_1x ... | import sys
def input(): return sys.stdin.buffer.readline()[:-1]
n, m, p = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
i = j = 0
while a[i] % p == 0:
i += 1
while b[j] % p == 0:
j += 1
print(i + j)
|
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future.
<image>
Kaavi has a string T of length m and a... | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 5)
s = input()[:-1]
t = input()[:-1]
MOD = 998244353
r_lim = len(t)
n = len(s)
dp = [[0] * (n + 1) for i in range(n + 1)]
for length in range(1, n + 1):
for l in range(n + 1):
r = l + length
if r > n:
break
if ... |
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c... | #include <bits/stdc++.h>
using namespace std;
int main() {
char s[100007];
scanf("%s", &s);
int l = strlen(s), one = 0, zero = 0, x = 0;
for (int i = 0; i < l; i++)
if (s[i] == '0')
zero++;
else if (s[i] == '1')
one++;
else
x++;
int n = l;
if (l & 1) zero++, n = l + 1;
if (ze... |
Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite ga... | import java.io.*;
import java.util.*;
public class Main{
static int[][]memo;
static int inf=(int)1e9;
static char[]in;
static PrintWriter pw;
static int[][]changesNeeded;
static int dp(int i,int pal) {
if(i>=in.length) {
return 0;
}
if(memo[i][pal]!=-1)return memo[i][pal];
if(pal==0)return inf;
in... |
Little Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.
Input
The first line contains two non-negative integer numbe... | #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
int n, m, dp[501][501];
struct Point {
int x, y;
Point() {}
Point(int _x, int _y) { x = _x, y = _y; }
Point operator-(const Point &b) const { return Point(x - b.x, y - b.y); }
long long operator*(const Point &a) const {
return (long... |
As you all know, the plum harvesting season is on! Little Milutin had his plums planted in an orchard that can be represented as an n by m matrix. While he was harvesting, he wrote the heights of all trees in a matrix of dimensions n by m.
At night, when he has spare time, he likes to perform various statistics on his... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0;
bool flg = false;
char ch = getchar();
for (; !isdigit(ch); ch = getchar())
if (ch == '-') flg = true;
for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48);
return flg ? -x : x;
}
const int INF = 1e9 + 9;
int... |
We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times.
On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the r... | #include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int mod = 998244353;
int T;
int a[N], b[N], p[N];
bool vis[N];
int main() {
scanf("%d", &T);
while (T--) {
int n, k;
scanf("%d%d", &n, &k);
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
p[a[i]] = i;
vis[i] = 0;
... |
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".
You are given a sequence s of n c... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import java.... |
You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line.
You start on a position 0. There are n boxes, the i-th box is on a position a_i. All positions of the boxes are distinct. There are also m special positions, the j-th position... | import sys
input = sys.stdin.readline
from bisect import bisect_left
def solve(p, q):
n, m = len(p), len(q)
res = 0
idx = 0
t = [0] * m
li = []
for i in range(n):
while idx < m and q[idx] < p[i]:
idx += 1
if idx < m and p[i] == q[idx]:
res += 1
... |
The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.
There are n+1 checkpoints on the trail. They are numbered by 0, 1, ..., n. A runner must start at checkpoint 0 and finish at checkpoint n. No checkpoint... | def solve(B, n, m):
AugB = []
for i in range(n):
for j in range(m):
AugB.append((B[i][j], i, j))
AugB = sorted(AugB)
mShortestPaths = AugB[:m]
result = [[0] * m for i in range(n)]
takenLengthIndices = [set() for i in range(n)]
for k in range(m):
l, i, j = mShort... |
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaM... | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
from itertools import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase
from typing import overload
def vsInput():
sys.stdin = open('input.... |
<image>
Input
The input contains two integers a, b (1 ≤ a ≤ 10, 0 ≤ b ≤ 22·a - 1) separated by a single space.
Output
Output two integers separated by a single space.
Examples
Input
1 0
Output
0 0
Input
2 15
Output
3 0
Input
4 160
Output
12 12 | #include <bits/stdc++.h>
int a, n, x, y, pow2[55];
void go(int a, int n, int &x, int &y) {
if (a == 0) {
x = 0;
y = 0;
return;
}
int cnt;
cnt = pow2[2 * (a - 1)];
if (n < cnt) {
go(a - 1, n, y, x);
return;
}
cnt = cnt + pow2[2 * (a - 1)];
if (n < cnt) {
go(a - 1, n - pow2[2 * (a ... |
As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as <image>, where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.
A well-known hipster Andrew adores everything funky ... | import math
n = int(raw_input())
k = 1
ok = False
while (k * (k + 1) / 2) < n:
r = k * (k + 1) / 2
c = n - r
c *= -2
s = int((-1 + math.sqrt(1 - 4 * c)) / 2)
t = s * (s + 1) / 2
if t + r == n :
ok = True
break
k += 1
if ok:
print "YES"
else:
print "NO"
|
Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.
The hall also turned out hexagonal in its shape. The King walked along the perimeter of ... | '''
Created on 14.08.2012
@author: Sergei Zalivako
'''
a, b, c = raw_input().split()
a = int(a)
b = int(b)
c = int(c)
l = []
l.append(a)
l.append(b)
l.append(c)
l.sort()
sum = 7 + (l[-1] - 2) * 3 + (l[-2] - 2) * (l[-1] + 1) + (l[-3] - 2) * (l[-1] + l[-2] - 1)
print sum |
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Input
The first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-... | s = input()
k = []
for i in range(len(s)):
for j in range(i+1,len(s)+2):
x = s[i:j]
for t in range(i+1,len(s)):
if x == s[t:t+j-i]:
k += [j-i]
print(max(k) if k != [] else 0) |
There are two sequences of colorful stones. The color of each stone is one of red, green, or blue. You are given two strings s and t. The i-th (1-based) character of s represents the color of the i-th stone of the first sequence. Similarly, the i-th (1-based) character of t represents the color of the i-th stone of the... | #include <bits/stdc++.h>
using namespace std;
char a[1100000], b[1100000];
int cnt[10][10];
int main() {
int la, lb, i, j, k;
long long ans = 0;
scanf("%s%s", &a, &b);
la = strlen(a);
lb = strlen(b);
for (i = 0; i < la; i++) {
if (a[i] == 'R') a[i] = 0;
if (a[i] == 'G') a[i] = 1;
if (a[i] == 'B'... |
Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing n nodes and n - 1 edges. We will consider the tree nodes numbered by integers from 1 to n.
Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of group... | #include <bits/stdc++.h>
using namespace std;
unsigned long long n, sum, size[80010];
vector<unsigned long long> G[80010];
unsigned long long cal(unsigned long long x) { return x * (x - 1) / 2; }
void dfs(unsigned long long u, unsigned long long fa) {
size[u] = 1;
unsigned long long ans1 = 0, ans2 = 0;
for (unsig... |
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.
Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single Zoo... | #include <bits/stdc++.h>
using namespace std;
long long dp[310][310];
long long minv[310][310];
const long long INF = 1000000000000000000LL;
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = (0); i <= (n); i++)
for (int j = (0); j <= (n); j++) minv[i][j] = INF;
for (int i = (0); i <= (n); ... |
Vasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.
Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you t... | import java.util.*;
public class Main{
public static void main(String[]args){
Scanner cin=new Scanner(System.in);
int x=cin.nextInt(),y=cin.nextInt(),s=Math.abs(x)+Math.abs(y);
if(0>x){
System.out.print(-s+" 0 0 ");
if(0>y) System.out.print(-s);
else System.out.print(s);
}else{
System.out.print("0 ... |
A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn.
Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamW... |
Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.
The scales is in equilibrium ... | #include <bits/stdc++.h>
const int inf = 0xfffffff;
const long long INF = 1ll << 61;
using namespace std;
string s, cc;
string ans;
int aa, bb;
void init() {}
bool input() {
while (cin >> s) {
cin >> cc;
int mark = 0;
aa = 0;
bb = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '|') {
... |
You have matrix a of size n × n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column.
Matrix a meets the following two conditions:
* for any numbe... | #include <bits/stdc++.h>
using namespace std;
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
const int N = 2003;
int n;
int a[N][N];
int b[N][N];
bool c[N];
void dfs(int x, int a[][N]) {
c[x] = true;
for (int h = 1; h <= n; ++h) {
if (a[x][h] && !c[h]) dfs(h, a);
}
}
int main() {
scanf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.