input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.
He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected d... | #include <bits/stdc++.h>
using namespace std;
int n, m;
long long u;
long long a[1000];
long long d[1000];
long long minn = -1e17;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) {
scanf("%lld", &a[i]);
d[i] = minn;
}
for (int i = n; i >= 0; --i) {
for (int j = n; j >= 0; --j) {
... |
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | n = int(raw_input())
s = ""
t = 1
while n > 3:
s += "2 "
n -= 2
t += 1
s += str(n)
print t
print s |
Bearland is a big square on the plane. It contains all points with coordinates not exceeding 106 by the absolute value.
There are n houses in Bearland. The i-th of them is located at the point (xi, yi). The n points are distinct, but some subsets of them may be collinear.
Bear Limak lives in the first house. He wants... | #include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 7;
const long double eps = 1e-7;
int t, n, q, k, s, op, x[N], y[N], xa[N], ya[N];
struct node {
long double x, y;
} e[N], f[N];
struct vec {
long double a, b, c, d;
} w[N], g[N], h[N];
struct vat {
int x, y;
} gt[N];
inline int read() {
int num =... |
Zane once had a good sequence a consisting of n integers a1, a2, ..., an — but he has lost it.
A sequence is said to be good if and only if all of its integers are non-negative and do not exceed 109 in value.
<image>
However, Zane remembers having played around with his sequence by applying m operations to it.
Ther... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
template <class T, class U>
inline void Max(T &a, U b) {
if (a < b) a = b;
}
template <class T, class U>
inline void Min(T &a, U b) {
if (a > b) a = b;
}
inline void add(int &a, int b) {
a += b;
if (a >= 10000000... |
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the... | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int M = 1e5 + 3;
const int N = 4;
const int mo = 1e9 + 7;
const LL inf = 1e18 + 1;
map<int, LL> mp;
LL a[M];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
mp[x]++;
}
int cnt = 0;
... |
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.
The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, an... | '''input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1
'''
r, d = map(int, input().split())
n = int(input())
c = 0
for _ in range(n):
x, y, r1 = map(int, input().split())
s = (x**2 + y**2)**0.5
if r-d <= s-r1 and s+r1 <= r:
c += 1
print(c)
|
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(Sy... |
There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with e... | #include <bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7, n, a[505][505], f[505][505], g[505][505];
int main() {
scanf("%lld", &n);
for (register int i = 1; i <= n; i++) {
for (register int j = 1; j <= n; j++) {
scanf("%lld", &a[i][j]);
}
}
for (register int i = 1; i <= n; i++) {
... |
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a per... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const long long LL_INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1);
const double ERR = 1e-8;
const int MAXN = 1e7;
int a[2000], n;
int main(int argc, char const *argv[]) {
scanf("%d", &n);
for (int i = 1; i... |
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
os << '{';
string sep;
for (const auto &x : v) os << sep << x, sep = ", ";
return os << '}';
}
template <typename A, typename B>
ostream &operator<<(ostream &os, const pair<A, B> &p) {
re... |
Petya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance ... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline T bigmod(T p, T e, T M) {
long long int ret = 1;
for (; e > 0; e >>= 1) {
if (e & 1) ret = (ret * p) % M;
p = (p * p) % M;
}
return (T)ret;
}
template <class T>
inline T gcd(T a, T b) {
if (b == 0) return a;
return gcd(b, a % b)... |
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | import math
x,y=map(lambda x:math.log(int(x))/int(x),input().split())
print('<=>'[(x>=y)+(x>y)]) |
There are N (labelled 1 to N) kingdoms in a country. Our king Alexander is living in the kingdom S. We are given R distances, these distances are between two kingdoms and the distance between any two kingdom may or may not be unique.
Now Alexander wants to visit each kingdom in minimum distance possible starting from ... | def killdoubles(l):
i=0
a=l[i]
ll=[a]
while i<len(l):
if a!=l[i]:
a=l[i]
ll.append(a)
i+=1
return ll
def argminnonmarque(l,m):
mini=min([l[i] for i in range(len(l)) if not(m[i])])
for i in range(len(l)):
if ((l[i]==mini) & (not(m[i]))):
... |
In McD's Burger, n hungry burger fans are ordering burgers. The ith order is placed by the ith fan at ti time and it takes di time to procees. What is the order in which the fans will get their burgers?
Input Format
On the first line you will get n, the number of orders. Then n lines will follow. On the (i+1)th line,... | a=[]
T=input()
for i in xrange(T):
c,d=map(int,raw_input().split())
a.append((c+d,i))
a.sort()
for i in a:
print i[1]+1, |
Problem :
Bajirao is on a date with his girlfriend Avni. It is a romantic night and they are
playing a game of words.
The rule of this game is that if Bajirao says a word such that no adjacent letters occurring in the word are same then he gets a kiss from her otherwise he gets a slap.
Input :
The first line consi... | t=input()
for i in range(t):
a=raw_input()
c=0
for i in range(0,len(a)-1):
if a[i]==a[i+1]:
c=1
if c==1:
print "SLAP"
else:
print "KISS" |
Game of numbers is a game where you are given two integers (X and Y), and you have to print the number of special numbers between X and Y both inclusive.
The property of a special numbers is as follows:
A special number is not divisible by any number of the form ZZ* where (Z\; >\; 1).
Input:
T, the number of ... | import math
def count(x, y):
z = [1] * ( y - x + 1)
for i in range(2, int(math.sqrt(y)) + 1):
step = i ** 2
if x % step == 0: j = x
else: j = x + step - (x%step)
while(j <= y):
z[j - x] = 0
j += step
return z.count(1)
def get():
t = int... |
Kejal have N points, with coordinates (1, 0), (2, 0), ..., (N, 0). Every point has a color, point with coordinate (i, 0) has color C[i].
Kejal have painted arcs between every pair of points with same color. Formally Kejal painted arc between points (i, 0) and (j, 0) if C[i] = C[j] and i != j, such arc has color C[i]. ... | rr = raw_input
N = int(rr())
A = map(int, rr().split())
from collections import defaultdict as ddic
G = ddic(int)
for i in A:
G[i] += 1
#G is total count of everything
ans = 0
for i in xrange(N):
cur = ddic(int)
Ai = A[i]
for j in xrange(i+1,N):
if Ai==A[j]:
for k,v in cur.iteritems():
if k>Ai: ans += cur[... |
You have just purchased a new mobile phone and you want to call all of your relatives to brag about your new phone. You have N relatives. You will talk to i^th relative for exactly Ti minutes. Each minute costs you 1 dollar . However, your relatives are generous. Hence after the conversation, they will add a recharge o... | n = int(raw_input())
lists = []
while n > 0:
n = n-1
lists.append(map(int,raw_input().split(" ")))
# lists.sort(lambda k : k[1]/k[0])
list2 = []
list3 = []
for x in lists:
# print x[0],x[1]
if x[1]/x[0] > 0:
list2.append(x)
else:
list3.append(x)
list2.sort(key=lambda k: k[0])
list3.sort(key = lambda k : k[1], ... |
Panda has started learning about subsets. His professor gave him a simple task. Given a list of numbers, Panda has to choose the subset which gives the maximum product. However, the professor asked Panda only to submit the maximum product obtained by taking exactly two numbers from the list. Please help Panda in findi... | '''
# 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!'
n=int(raw_input())
l=[int(i) for i in raw_input().split(" ")]
l.sort()
x=l[::-1]
if x[0]>0 and x[1]>0:
print x[0]*x[1]
else:
print l[0]*l[1] |
Bosky needs your help in completing his maths homework today. He has to solve some questions as homework from a book named Jungly Mathematics. He knows that Jungly Mathematics contains certain quadratic equations which have imaginary roots. He is not yet introduced to the concept of imaginary roots and is only concerne... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def can_solve(equation):
a = equation[0]
b = equation[1]
c = equation[2]
if b * b < 4 * a * c:
return False
else:
return True
if __name__ == '__main__':
cases = int(raw_i... |
Your algorithm is so good at predicting the market that you now know what the share price of Mahindra & Mahindra. (M&M) will be for the next N days.
Each day, you can either buy one share of M&M, sell any number of shares of M&M that you own, or not make any transaction at all. What is the maximum profit you can obtai... | def calcprofit(stockvalues):
prof=0
m=0
for i in range(len(stockvalues)-1,-1,-1):
ai=stockvalues[i]
if m<=ai:
m=ai
prof+=m-ai
return (prof)
for iti in xrange(input()):
n=input()
l=map(int, raw_input().split())
print calcprofit(l) |
There are N people in a group. The personality of each person is denoted by A[i] from the set A, where A[i] denotes the personality of the ith person.
Your task is to find the total persons of different personalities.
INPUT:
First line contains the total number of test cases T, for each test cases, first line deno... | a = input()
for i in xrange(a) :
d = input();
b = [int(i) for i in raw_input().strip().split()]
c = {}
for i in xrange(d) :
c[b[i]]=i;
print len(c) |
You are given N real values A_1, A_2, \ldots, A_N. Compute the number of pairs of indices (i, j) such that i < j and the product A_i \cdot A_j is integer.
Constraints
* 2 \leq N \leq 200\,000
* 0 < A_i < 10^4
* A_i is given with at most 9 digits after the decimal.
Input
Input is given from Standard Input in the fol... | #include<bits/stdc++.h>
using namespace std;
int cnt[65][65],cnt2,cnt5;
long long ans,tmp;
int main(){
double x;int n;
cin>>n;
for(int i=1;i<=n;++i){
cin>>x;
tmp=llround(x*1e9);
//cout<<tmp<<endl;
cnt2=cnt5=0;
while(tmp%2==0) ++cnt2,tmp/=2;
while(tmp%5==0) ++cnt5,tmp/=5;
for(int j=0;j<=64;++j)
for(i... |
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All valu... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long n = scan.nextLong();
long k = scan.nextLong();
long res = n % k;
System.out.println(Math.min(Math.abs(res-k),res));
}
} |
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ... | N = int(input())
S = input()
print(''.join(chr((ord(c) - ord('A') + N) % 26 + ord('A')) for c in S))
|
There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and... | #include<bits/stdc++.h>
#define LL long long
#define MEM(x,y) memset(x,y,sizeof(x))
#define MOD(x) ((x)%mod)
#define mod 1000000007
#define pb push_back
#define STREAM_FAST ios::sync_with_stdio(false)
using namespace std;
const int maxn = 1e5 + 7;
int head[maxn];
struct node{int v, next, c, w;}e[maxn << 1];
LL ans[maxn... |
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster a... | #include<iostream>
using namespace std;
int main(){
int n,a,b,c,i=1;
cin >> n;
cin >> a;
do{
cin >> b;
if(a<b){c=b;b=a;a=c;}
while(a%b){
c=b;b=a%b;a=c;
}
a=b;i++;
}while(i<n);
cout << a;
return 0;
} |
Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable. For each i=2,3,...,2K, find the following value modulo 998244353:
* The number of combinations of N sides shown by the dice such that the sum of no two different sides is i.
Note that the dice are ... | #include<iostream>
#include<algorithm>
using namespace std;
typedef long long Int;
#define MOD 998244353LL;
Int cmemo[4000][4000];
Int C(Int x, Int y){
if(x < y)return 0;
Int &res = cmemo[x][y];
if(res != -1)return res;
if(y == 0 || x == y)return res = 1;
return res = (C(x-1, y) + C(x-1, y-1)) % MOD;
}
Int cnt... |
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Constraints
* 1\leq N \leq 10^{16}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the maximum possible sum of the digits (in base 10) of a positive integer not... |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.run();
}
Scanner sc = new Scanner(System.in);
void run() {
long n = sc.nextLong();
System.out.println(solve(n));
}
long solve(long n){
long x = n;
int r = 0;
long d1 = 1;
... |
There are N lines in the xy-plane. The i-th line is represented by A_ix+B_iy=C_i. Any two lines among the N+2 lines, the above N lines plus the x-axis and y-axis, cross each other at exactly one point.
For each pair 1 \leq i < j \leq N, there is a car at the cross point of the i-th and j-th lines. Even where three or ... | #include <bits/stdc++.h>
using namespace std;
#define times(n, i) uptil(0, n, i)
#define rtimes(n, i) downto((n) - 1, 0, i)
#define upto(f, t, i) for(int i##_to_ = (t), i = (f); i <= i##_to_; i++)
#define uptil(f, t, i) for(int i##_to_ = (t), i = (f); i < i##_to_; i++)
#define downto(f, t, i) for(int i... |
Alice lives on a line. Today, she will travel to some place in a mysterious vehicle. Initially, the distance between Alice and her destination is D. When she input a number x to the vehicle, it will travel in the direction of the destination by a distance of x if this move would shorten the distance between the vehicle... | #include <bits/stdc++.h>
#define yabs(x) ((x<0)?(-(x)):(x))
using namespace std;
const int N=5e5+10,Inf=1e9+10;
int n,D,Q,a[N],now[N],suf[N];
void Init()
{
scanf("%d%d",&n,&D);
for (int i=1;i<=n;++i) scanf("%d",&a[i]);
}
void Solve()
{
now[0]=D;
for (int i=1;i<=n;++i) now[i]=min(now[i-1],yabs(now[i-1]-a[i]));
... |
Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i.
He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subse... | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZER... |
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Input
Input consists of several da... | import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext())
{
int n = sc.nextInt();
int ans =0;
boolean a[] = new boolean [n+1];
Arrays.fill(a, true);
a[0]=a[1]=false;
for (int p=2; ... |
I decided to create a program that displays a "round and round pattern". The "round and round pattern" is as follows.
* If the length of one side is n, it is displayed as a character string with n rows and n columns.
* A spiral pattern that rotates clockwise with the lower left corner as the base point.
* The part wit... | #include "bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
enum{UP,RIGHT,DOWN,LEFT};
int dy[]={-1,0,1,0};
int dx[]={0,1,0,-1};
int n;
bool adja(bool data[100][100],int y,int x,int dir){
int left=(dir+3)%4,right=(dir+1)%4;
if( x+dx[left ]>=0 && y+dy[left ]>=0 && x+dx[left ]<n && y+dy... |
Jou and Yae are a good couple. Jou is collecting prizes for capsule toy vending machines (Gachapon), and even when they go out together, when they find Gachapon, they seem to get so hot that they try it several times. Yae was just looking at Jou, who looked happy, but decided to give him a Gachapon prize for his upcomi... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
while(cin >> n, n){
int cnt = 0;
bool ok = false;
for(int i=0;i<n;i++){
int k;
cin >> k;
if(k>0) cnt++;
if(k>1) ok = true;
}
if(ok){
cout << cnt+... |
problem
JOI Pizza sells pizza home delivery along the d-meter-long ring road that runs through the city center.
JOI Pizza has n stores S1, ..., Sn on the loop line. The head office is S1. The distance from S1 to Si when moving the loop line clockwise is set to di meters. D2 , ..., dn is an integer greater than or equ... | #include<bits/stdc++.h>
#define rep(i,n)for(ll i=0;i<n;i++)
using namespace std;
typedef long long ll;
ll a[200000];
int main() {
ll d, n, m;
while (scanf("%lld", &d), d) {
scanf("%lld%lld", &n, &m);
rep(i, n - 1)scanf("%lld", &a[i]);
a[n - 1] = 0; a[n] = d;
sort(a, a + n + 1);
a[n + 1] = a[n - 1] - d;
... |
Turtle Shi-ta and turtle Be-ko decided to divide a chocolate. The shape of the chocolate is rectangle. The corners of the chocolate are put on (0,0), (w,0), (w,h) and (0,h). The chocolate has lines for cutting. They cut the chocolate only along some of these lines.
The lines are expressed as follows. There are m poi... | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <queue>
using namespace std;
#define SZ(v) ((int)(v).size())
const int maxint = -1u>>1;
const int maxn = 30000 + 100;
const double eps = 1e-8;
typedef long long lint... |
A professor of anthropology was interested in people living in isolated islands and their history. He collected their family trees to conduct some anthropological experiment. For the experiment, he needed to process the family trees with a computer. For that purpose he translated them into text files. The following is ... | #include <iostream>
#include <string>
#include <vector>
using namespace std;
#define REP(i,n) for(int i=0; i<n; ++i)
class Tree
{
public:
string name;
Tree* parent;
vector<Tree*> child;
Tree()
:parent(NULL)
{}
~Tree()
{
REP(i,child.size()) delete child[i];
}
};
Tree* tree;
Tree* find(Tree* t, string ... |
Example
Input
4 2 1 1
1 1 1 2
2 2 2 1
2 2 1 2
1 1 2 1
9 N
Output
1 1
2 2 | // tsukasa_diary's programing contest code template
#include <bits/stdc++.h>
using namespace std;
// define
#define for_(i,a,b) for(int i=a;i<b;++i)
#define for_rev(i,a,b) for(int i=a;i>=b;--i)
#define allof(a) a.begin(),a.end()
#define minit(a,b) memset(a,b,sizeof(a))
#define size_of(a) (int)a.size()
// typedef
typede... |
Problem
There are N villages. Each village is numbered from 1 to N. Due to the recent merger boom, several villages have been merged. Two or more merged villages will become one new city, and villages that are not merged with any village will remain villages.
You will be given multiple pieces of information that two ... | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class Main{
int N,M;
int[] union,rank;
boolean[] used;
public boolean same(int x,int y){
return find(x) == find(y);
}
public int find(int x){
if(union... |
After spending long long time, you had gotten tired of computer programming. Instead you were inter- ested in electronic construction. As your first work, you built a simple calculator. It can handle positive integers of up to four decimal digits, and perform addition, subtraction and multiplication of numbers. You did... | #include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
using namespace std;
int main()
{
int r1, r2;
char r3;
string str, fm;
bool f;
while(cin>>fm){
r1 = r2 = 0;
r3 = ' ';
f = true;
str = "";
for(int i = 0; f && i < fm.size(); ++i){
if(isdigit(fm[i])){
str +=... |
In 20XX, an efficient material transfer method was established for distant places, and human beings' advance into space was accelerated more and more. This transfer method was innovative in that, in principle, larger substances could be transferred when trying to transfer the substance farther. The details of the trans... | /*
* AOJ 2214: Warp Hall
* ?¢??????????(1,1)?????°??????(m,n)???????¬??????????????????°?????????????????°????´???????????????´??\??°???????????????????´????????????????????°??§??????????
* ?±????????????°DP
* ???????????????????´?i(ai,bi)??°(ci,di)???(1,1)??°(ai,bi)???????????°???di??????????????\????´????????????... |
There is a grid of size W × H surrounded by walls. Some cells in the grid are occupied by slimes. The slimes want to unite with each other and become a "King Slime".
In each move, a slime can move to east, west, south and north direction until it enters a cell occupied by another slime or hit the surrounding wall. If ... | #include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<b;i++)
template<int um> class UF { // from kmjp
public:
vector<int> par;
UF() { par = vector<int>(um, 0); rep(i, 0, um) par[i] = i; }
int operator[](int x) { return par[x] == x ? x : par[x] = operator[](par[x]); }
void operator()(int x, ... |
C - Iyasugigappa
Problem Statement
Three animals Frog, Kappa (Water Imp) and Weasel are playing a card game.
In this game, players make use of three kinds of items: a guillotine, twelve noble cards and six action cards. Some integer value is written on the face of each noble card and each action card. Before stating... | #include <bits/stdc++.h>
using namespace std;
constexpr int INF = 1e9;
using vi = vector<int>;
using pii = pair<int, int>;
using state = tuple<vi, int, int>;
using result = array<int, 3>;
map<state, result> memo;
map<state, result> memo2;
map<state, state> next_st;
map<state, int> get_score;
int card[3][2];
array<... |
ABC Gene
There is a gene sequence represented by the string `ABC`. You can rewrite this gene sequence by performing the following operations several times.
* Choose one of the letters `A`,` B`, `C`. Let this be x. Replace all x in the gene sequence with `ABC` at the same time.
Given a string S consisting only of `... | #include <bits/stdc++.h>
#define REP(i,n,N) for(int i=n;i<N;i++)
#define p(S) cout<<(S)<<endl
#define ck(a,b) (0<=(a)&&(a)<b)
using namespace std;
string abcgene(string anss){
queue<string> q;
q.push(anss);
string c[3]={"A","B","C"};
map<string,bool> m;
m[anss]=true;
while(!q.empty()){
string s=q.front();
q.... |
Chokudai loves eating so much. However, his doctor Akensho told him that he was overweight, so he finally decided to lose his weight.
Chokudai made a slimming plan of a $D$-day cycle. It is represented by $D$ integers $w_0, ..., w_{D-1}$. His weight is $S$ on the 0-th day of the plan and he aims to reduce it to $T$ ($... | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> mp;
ll inf = 1e9;
int main(){
ll s,t,d;
cin>>s>>t>>d;
ll aim = s-t;
vector<ll> w(d);
for(ll i=0;i<d;i++)cin>>w[i];
ll sumw = w[0];
vector<ll> dp(d,0);
dp[0] = w[0];
for(ll i=1;i<d;i++)sumw +... |
H: Colorful Tree
Story
Yamiuchi (assassination) is a traditional event that is held annually in JAG summer camp. Every team displays a decorated tree in the dark and all teams' trees are compared from the point of view of their colorfulness. In this competition, it is allowed to cut the other teams’ tree to reduce it... | #include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}
template <typena... |
Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:
\begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*}
Constraints
... | #include<iostream>
using namespace std;
int main(){
const int MAX=46;
long long f[MAX]={1,1};
for(int i=2;i<MAX;i++)f[i]=f[i-1]+f[i-2];
int n;
cin>>n;
cout<<f[n]<<endl;
return 0;
}
|
Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).
Input
Four real numbers x1, y1, x2 and y2 are given in a line.
Output
Print the distance in real number. The output should not contain an absolute error greater than 10-4.
Example
Input
0 0 1 1
Output
1.41421356 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
double xx = x2 - x1;
double yy = y2 - y1;
double xxyy = xx * x... |
Brachiosaurus is trying to become a detective by writing words in codes. It manipulates each word in a sentence by putting the letter 'z' after each vowel, followed by that very vowel.
Eg- "belina" translates into "bezelizinaza" and "zazhiba" translates into "zazazhizibaza". A team of secret agents want to decode the ... | # imports
import sys
import StringIO
class Problem(object):
def __init__(self, reader):
self.reader = reader
def run(self):
vowels = frozenset(["a", "e", "i", "o", "u"])
last_vowel_block = -1
# decode the message, by replacing the vowel pattterns
... |
While Tom Cruise(Cage) fighting in the movie "Edge of Tomorrow", he finds himself in a modern lab, where he needs to kill the brain of a mutant species Omega.
The DNA of the Omega is made up of characters of A, T, G and C like ours. He has certain enzymes which will cut and remove certain parts of this DNA.
The mutant ... | import sys
t=input()
str1=raw_input()
for _ in range(t):
ss=raw_input()
str1=str1.replace(ss, "")
if(len(str1)==0):
print '0'
else:
print str1 |
The success of IEEE code-quest depends on number of times the factor is present in a given string.Help core members to find them
Factor of string is defined as a substring.In this case it's '01'.
Input
First line of input contains an integer T, denoting the number of test cases. Then follows description of T cases.Ea... | '''
Coded by Abhishek The Hacktivist
'''
test = int(raw_input())
for i in range(test):
count = 0
num = str(raw_input().split())
for j in range(len(num)):
if (num[j] == '0') and (num[j+1] == '1'):
count += 1
print count |
One day maths teacher gave the following task for the students, only upon completion students will be taken out for a school fun trip.
First you are a given a list of n numbers and q queries. For each query you are given two indices x and y , you have to report the between the maximum number and minimum number whose in... | dic={}
n, q = map(int, raw_input().split())
li = map(int, raw_input().split())
for i in xrange(q):
l, r = map(int, raw_input().split())
tli=li[l:r+1]
s=str(l) + '+' + str(r)
if s not in dic:
dic[s] = max(tli) - min(tli)
print dic[s] |
Sometimes mysteries happen. Chef found a directed graph with N vertices and M edges in his kitchen!
The evening was boring and chef has nothing else to do, so to entertain himself, Chef thought about a question "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to... | from sys import stdin
from heapq import heappush, heappop
def v_con(M, graph, N):
while M > 0:
a, b = map(int, stdin.readline().split())
graph[a][b] = 0
if not graph[b].has_key(a):
if a == 1 and b == N:
graph[b][a] = 1
elif a != 1:
graph[b][a] = 1
M = M - 1
return graph
def relax(G, u, v, D):
... |
Little kids, Jack and Evan like playing their favorite game Glass-and-Stone. Today they want to play something new and came across Twitter on their father's laptop.
They saw it for the first time but were already getting bored to see a bunch of sentences having at most 140 characters each. The only thing they liked to... | # your code goes here
n,k=map(int,raw_input().split())
a=[0 for i in range(n)]
cou=0
for i in range(k):
t=raw_input().split()
if len(t)==1:
for j in range(n):
a[j]=0
cou=0
else:
x=int(t[1])-1
a[x]^=1
if a[x]==0:
cou-=1
else:
cou+=1
print cou |
This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered ... | #include <bits/stdc++.h>
using namespace std;
int n;
map<int, int> mp;
int Get(int x) {
if (mp.count(x)) return mp[x];
printf("? %d\n", x);
fflush(stdout);
int y;
scanf("%d", &y);
return mp[x] = y;
}
void Print(int x) {
printf("! %d\n", x);
exit(0);
}
int main() {
scanf("%d", &n);
if (n % 4) Print(-... |
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people c... | #include <bits/stdc++.h>
using namespace std;
const int INF = 100010;
int n, m;
int a[INF];
int ss;
int maxn = 0;
int ans;
int main() {
cin >> n >> m;
ss = m;
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i] >= maxn) maxn = a[i];
}
sort(a, a + n);
for (int i = 0; i < n; i++) {
if (a[i] != max... |
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly k candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends i... | //package CodeForces.Round516_div2;
import java.util.Scanner;
/**
* @Author: tianchengjiang
* @Date:2018/10/22
*/
public class problemF {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
while (scanner.hasNext()) {
long n = scanner.nextLo... |
n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two ... | #include <bits/stdc++.h>
using namespace std;
inline long long mod(long long n, long long m) {
long long ret = n % m;
if (ret < 0) ret += m;
return ret;
}
long long gcd(long long a, long long b) { return (b == 0 ? a : gcd(b, a % b)); }
long long exp(long long a, long long b, long long m) {
if (b == 0) return 1;... |
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever ... | import java.util.*;
import java.lang.*;
import java.io.*;
public class MAIN {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
... |
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
public class Main {
private static class ArrayEntry {
int v;
int c;... |
You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D ≥ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is... | n = int(input())
L = [int(i) for i in input().split()]
F = []
mi = 101
ma = 0
for i in L:
if i not in F:
F.append(i)
if len(F) > 3:
print(-1)
else:
F.sort()
if len(F) == 3:
D = F[1] - F[0]
if F[2] - F[1] == D:
print(D)
else:
print(-1)
elif len(... |
You are given array a_1, a_2, ..., a_n. You need to split it into k subsegments (so every element is included in exactly one subsegment).
The weight of a subsegment a_l, a_{l+1}, ..., a_r is equal to (r - l + 1) ⋅ max_{l ≤ i ≤ r}(a_i). The weight of a partition is a total weight of all its segments.
Find the partitio... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct dreapta {
ll a, b;
ll operator()(ll x) { return a * x + b; }
};
bool useless(dreapta a, dreapta b, dreapta c) {
assert(a.a >= b.a && b.a >= c.a);
return (double)(b.b - a.b) / (a.a - b.a) > (double)(c.b - b.b) / (b.a - c.a);
}
class mergi... |
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming.
Fortunately, Adilbek can spend time witho... | #include <bits/stdc++.h>
using namespace std;
const long long N = 200010, Mod = 1000000007;
long long n, T, M, res, ans;
long long a[N], inv[N], fac[N];
long long Inv[N], pow_2[N];
inline long long read() {
long long x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = get... |
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | def line():
return map(int, input().split())
def num():
return int(input())
from collections import OrderedDict as od
n,k = line()
ids = list(line())
screen = od()
for id in ids:
if id not in screen:
if len(screen)==k:
screen.popitem(last=False)
screen[id]=None
print(len(scree... |
There are four stones on an infinite line in integer coordinates a_1, a_2, a_3, a_4. The goal is to have the stones in coordinates b_1, b_2, b_3, b_4. The order of the stones does not matter, that is, a stone from any position a_i can end up in at any position b_j, provided there is a required number of stones in each ... | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > v1, v2, v3;
long long a[5], b[5], d;
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
void op(long long *a, vector<pair<long long, long long> > &mov, long long p1,
long long p2) {
mov.push_back(make_pai... |
This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string s consisting of n lowercase Latin letters.
You have to color all its characters the minimum numb... | // Working program using Reader Class
import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStre... |
How many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of n lines each containing m ... | #include <bits/stdc++.h>
using namespace std;
const int N = 510;
char data[N][N];
int n, m, k;
bool a[N][N];
int s[N][N];
int go[5][2] = {0, 0, -1, 0, 0, 1, 1, 0, 0, -1};
bool judge(int x, int y) {
for (int i = 0; i < 5; i++)
if (data[x + go[i][0]][y + go[i][1]] != '1') return 0;
return 1;
}
long long cal(int x... |
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, …, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<long long> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
long long maxi = arr[n - 1], mini = arr[n - 1];
int x = 0;
for (int i = n - 2; i >= 0; i--) {
x = max((l... |
You are given four positive integers n, m, a, b (1 ≤ b ≤ n ≤ 50; 1 ≤ a ≤ m ≤ 50). Find any such rectangular matrix of size n × m that satisfies all of the following conditions:
* each row of the matrix contains exactly a ones;
* each column of the matrix contains exactly b ones;
* all other elements are zeros.... | for q in range(int(input())):
n, m, a, b = map(int, input().split())
if n*a != m*b:
print('NO')
continue
print('YES')
t = '1'*a+'0'*(m-a)
for i in range(n):
print(t)
t = t[m-a:]+t[:m-a] |
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | #include <bits/stdc++.h>
using namespace std;
string a, b;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
cin >> a;
cin >> b;
int k = 0;
for (int i = 0; i < n; i++)
if (a[i] != b[i]) k++;
k *= 3;
cout << k;
for (int i = 0; i < n; i++)
if (a[i] != b[i])... |
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point ... | for _ in range(int(input())):
n, k = map(int, input().split())
if n<k:print(k-n)
elif n%2 == k%2: print(0)
else: print(1) |
John has Q closed intervals of consecutive 2K-bit numbers [l_i, r_i] and one 16-bit value v_i for each interval. (0 ≤ i < Q)
John wants to implement a function F that maps 2K-bit numbers to 16-bit numbers in such a way that inputs from each interval are mapped to that interval's value. In other words: $$$F(x) = v_i, \... | #include <bits/stdc++.h>
using namespace std;
class segtree {
public:
struct node {
int val = 0;
int put = 0;
void apply(int l, int r, int v) {
val |= v;
put |= v;
}
};
node unite(const node &a, const node &b) const {
node res;
res.val = a.val | b.val;
return res;
}
in... |
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, r... |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
p... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet... | #include <bits/stdc++.h>
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a > b ? b : a; }
int main() {
int i;
int a4, a7, a47, a74;
scanf("%d %d %d %d", &a4, &a7, &a47, &a74);
if (fabs(a47 - a74) > 1) {
printf("-1\n");
return 0;
}
if (a47 != a74) {
if (min(a4, a7) ... |
There are n squares drawn from left to right on the floor. The i-th square has three integers p_i,a_i,b_i, written on it. The sequence p_1,p_2,...,p_n forms a permutation.
Each round you will start from the leftmost square 1 and jump to the right. If you are now on the i-th square, you can do one of the following two ... | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define int long long
#define ull unsigned long long
#define fi first
#define se second
#define mpr make_pair
#define dingyi int mid = l + ... |
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now.... | import java.util.*;
import java.awt.image.BandedSampleModel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.Scanner;
public class B {
static void sort(int[] A){
int n = A.length;
Random rnd = new Random(... |
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... | #include<bits/stdc++.h>
using namespace std;
template<typename T,typename T1>T amax(T &a,T1 b){if(b>a)a=b;return a;}
template<typename T,typename T1>T amin(T &a,T1 b){if(b<a)a=b;return a;}
#define ll long long int
#define ld long double
#define INF (int)1e9+4
#d... |
The Trinitarian kingdom has exactly n = 3k cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side.
Some cities are connected by bridges built between them. Each bridge conn... | #include <bits/stdc++.h>
using namespace std;
namespace ufs {
int fa[100005];
void makeset(int n) {
for (int i = 1; i <= n; i++) fa[i] = i;
}
int findset(int u) {
if (fa[u] == u) return fa[u];
return fa[u] = findset(fa[u]);
}
void unionset(int a, int b) {
int u = findset(a);
int v = findset(b);
fa[u] = v;
}... |
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when div... | #include <bits/stdc++.h>
long long mo, ans[1000], res[1000];
long long mul(long long a, long long b) {
return b == 0 ? 0 : ((mul(a, b >> 16) << 16) + a * (b & (1 << 16) - 1)) % mo;
}
void mul(long long f[2][2], long long g[2][2]) {
long long a[2][2];
a[0][0] = (mul(f[0][0], g[0][0]) + mul(f[0][1], g[1][0])) % mo;... |
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations — each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The m... | #include <bits/stdc++.h>
const int MOD = 1E9 + 7;
const int N = 3000000 + 5;
const int dx[] = {-1, 1, 0, 0, -1, -1, 1, 1};
const int dy[] = {0, 0, -1, 1, -1, 1, -1, 1};
using namespace std;
int tot, f[N], X[N], Y[N], a[N], len, seq[N];
int n, m;
int father[N];
char str[N], c;
int get(int x) {
int l = 1;
seq[1] = x;... |
You have a sequence of n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). You want to remove some integers in such a way that the resulting sequence of integers satisfies the following three conditions:
1. the resulting sequence is not empty;
2. the exclusive or (xor operation) of all the integers in the resulting... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
register long long s = 0, f = 0;
register char ch = getchar();
while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
while (isdigit(ch)) s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
return f ? -s : s;
}
long long n, m, p, check;
... |
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can a... | import java.util.*;
public class C163 {
class Line{
public ArrayList<Integer> l = new ArrayList<Integer>();
public int yuan;
public Line() {
l = new ArrayList<Integer>();
}
}
class Lie{
public int min;
public int shu;
public int yuan;
public Lie(int min, int shu, int yuan) {
super(... |
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their ro... | #include <bits/stdc++.h>
using namespace std;
const int N = 55;
int n, m;
int a[N];
double dp[N][N][N];
long long C[N][N];
double qmod(double a, long long b) {
double res = 1;
while (b) {
if (b & 1) res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
int main() {
for (int i = 0; i < int(N); i++) {
... |
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the... | #include <bits/stdc++.h>
inline int getInt() {
int s;
scanf("%d", &s);
return s;
}
using namespace std;
int main() {
const int n = getInt();
const long long k = getInt();
vector<long long> a(n);
for (int i = 0; i < (int)(n); i++) a[i] = getInt();
int cnt = 1;
long long d = 0;
for (int i = 1; i < n; ... |
A divisor tree is a rooted tree that meets the following conditions:
* Each vertex of the tree contains a positive integer number.
* The numbers written in the leaves of the tree are prime numbers.
* For any inner vertex, the number within it is equal to the product of the numbers written in its children.
... | #include <bits/stdc++.h>
using namespace std;
int n;
long long a[8];
int factors[8];
int primeCnt;
int solve(int cur, vector<long long> &tree, int rootNum, int rootSum) {
if (cur == n) return n + (rootNum > 1) + rootSum - primeCnt;
int ret = 1 << 28;
for (int i = 0; i < (int)(tree.size()); i++) {
if (tree[i] ... |
Levko has an array that consists of integers: a1, a2, ... , an. But he doesn’t like this array at all.
Levko thinks that the beauty of the array a directly depends on value c(a), which can be calculated by the formula:
<image> The less value c(a) is, the more beautiful the array is.
It’s time to change the world an... | #include <bits/stdc++.h>
using namespace std;
long long power(long long a, long long b, long long m) {
long long x = 1 % m;
a %= m;
while (b) {
if ((1 & b)) x = x * a % m;
a = a * a % m;
b >>= 1;
}
return x;
}
int a[2005];
int n, k;
long long dp[2005];
long long solve(long long x) {
for (int i =... |
Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of n 3-words. A 3-word is a sequence of exactly 3 lowercase letters of the first 24 letters of the English alphabet (a to x). She decided that some of the letters are vowels, and... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 10010;
const int N = 24;
int inv = (1 << N) - 1;
int F[(1 << N) + 10];
int ara[MAX];
int howManyZeroPairs(int n, int ara[]) {
memset(F, 0, sizeof(F));
for (int i = 0; i < n; i++) F[ara[i]]++;
;
for (int i = 0; i < N; ++i)
for (int mask = 0; mask ... |
Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.
For example, the correct field to play looks ... | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
PrintWriter out;
private String next() throws Exception{
if (str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
... |
One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found n test tubes with mercury numbered from 1 to n and decided to conduct an experiment.
The experiment consists of q steps. On each step, one of the following actions occurs:
1. Diana pours all the c... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:67108864")
using namespace std;
inline long long FastMax(long long x, long long y) {
return (((y - x) >> (32 - 1)) & (x ^ y)) ^ y;
}
inline long long FastMin(long long x, long long y) {
return (((y - x) >> (32 - 1)) & (x ^ y)) ^ x;
}
long long N, Q;
long long... |
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an → an, a1, a2, ..., an - 1.
Help Twi... | def us_num(nums):
where = None
for idx, (a, na) in enumerate(zip(nums[:-1], nums[1:])):
if a > na:
if where is None:
where = idx
else:
return -1
if where is None:
return 0
elif nums[-1] > nums[0]:
return -1
return len(nums) - 1 - where
n = int(input())
nums = list(map(... |
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally... | #include <bits/stdc++.h>
using namespace std;
string s;
string p;
int a[2005];
int A[2005];
int ans[2005];
int dp[2005][2005];
int main() {
cin >> s >> p;
memset(a, -1, sizeof(a));
a[0] = 0;
for (int i = 0; i < s.size(); i++) {
for (int j = p.size() - 1; j >= 0; j--) {
if (s[i] == p[j]) a[j + 1] = a[j... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | x=int(input())
y=x-2
if y%2==0 and y!=0:
print("YES")
else :
print("NO") |
Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations:
* adding any bracket in any position (in the beginning, the end, or between any two existing brackets);
* cyclic shift — mov... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 5;
char s[N];
int tp[N], rak[N], sa[N], tax[N], sl, m, cnt[N], lg[N], f[N][20], rr[N];
void radixSort() {
for (int i = 1; i <= m; i++) tax[i] = 0;
for (int i = 1; i <= sl; i++) tax[rak[i]]++;
for (int i = 1; i <= m; i++) tax[i] += tax[i - 1];
for... |
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
Input
The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.
Output
Print "YES" (without the quot... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
if ((s.contains("AB") && s.replaceFirst("AB", ".").contains("BA")) || s.contains("BA") && s.replaceFirst("BA", ".").contains("AB"))
System.out.println("YES"... |
You are given a sequence of numbers a1, a2, ..., an, and a number m.
Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.
Input
The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and ... | n,x=map(int,input().split())
a=set()
for i in input().split():
i=int(i)
b=set()
for j in a: b.add((i+j)%x)
a|=b
a.add(i%x)
if 0 in a:
print("YES")
break
else:
print("NO") |
Rooted tree is a connected graph without any simple cycles with one vertex selected as a root. In this problem the vertex number 1 will always serve as a root.
Lowest common ancestor of two vertices u and v is the farthest from the root vertex that lies on both the path from u to the root and on path from v to the roo... | #include <bits/stdc++.h>
using namespace std;
long long n, m, q;
long long dp[15][1 << 15];
pair<long long, long long> con[15];
pair<pair<long long, long long>, long long> lca[105];
void myinit() {
cin >> n >> m >> q;
for (long long i = 1; i <= m; i++) {
long long u, v;
cin >> u >> v;
u--, v--;
con[... |
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.
In one operation professor can swap some element from the array a and some element f... | #include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cerr << name << ": " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');
cerr.write... |
Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.
More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a g... | #include <bits/stdc++.h>
using namespace std;
int b[1100000];
int main() {
int n, q, odd, even, p1, p2;
while (scanf("%d %d", &n, &q) != EOF) {
memset(b, 0, sizeof(b));
odd = 0, even = 1;
while (q--) {
int x, y;
scanf("%d", &x);
if (x == 1) {
scanf("%d", &y);
odd = (odd... |
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But h... | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class PetyaAndJava {
void run() {
try {
BufferedReader bfd = new BufferedReader(new InputStreamReader(
System.in));
String[] types = { "byte", "short", "int", "l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.