input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Your dear son Arnie is addicted to a puzzle named Connect Line Segments.
In this puzzle, you are given several line segments placed on a two-dimensional area. You are allowed to add some new line segments each connecting the end points of two existing line segments. The objective is to form a single polyline, by conne... | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <complex>
#include <vector>
#include <cmath>
using namespace std;
#define MAXN (17)
#define INF (1<<29)
#define X real()
#define Y imag()
typedef complex<double> P;
template<class T>
inline T Sq(T x) { return x*x; }
inline double getDist(P,... |
Problem D: Legendary Sword
* This problem contains a lot of two ingredients in the kitchen. Please be careful about heartburn.
The Demon King, who has finally revived, is about to invade the human world to wrap the world in darkness again.
The Demon King decided to destroy the legendary sword first before launching ... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
#define rep(i, n) for(int i=0; i<(int)(n); i++)
#define mp make_pair
#define INF (1<<28)
inline void cmin(int &a, int b) { if(a>b) a = b; }
typedef pair<int, int>... |
FizzBuzz is a game in which integers of 1 or more are spoken in order according to the following rules.
* "Fizz" when divisible by 3
* "Buzz" when divisible by 5
* "FizzBuzz" when divisible by both 3 and 5
* At other times, that number
An example of the progress of the game is shown below.
1, 2, Fizz, 4, Buzz,... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int ll
inline ll toInt(string s) {ll v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
template<class T> inline T sqr(T x) {return x*x;}
typedef vector<in... |
Problem Statement
You want to compete in ICPC (Internet Contest of Point Collection). In this contest, we move around in $N$ websites, numbered $1$ through $N$, within a time limit and collect points as many as possible. We can start and end on any website.
There are $M$ links between the websites, and we can move be... | #include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int p[110];
int q[110];
int r[110];
vector<int>g[110];
int g2[110][110];
int UF[110];
int FIND(int a){
if(UF[a]<0)return a;
return UF[a]=FIND(UF[a]);
}
void UNION(int a,int b){
a=FIND(a);b=FIND(b);if(a==b)return;UF[a]+=UF[b];... |
Problem statement
There are rectangles with vertical and horizontal lengths of h and w, and square squares with a side length of 1 are spread inside. If the upper left cell is (0,0) and the cell to the right of j below (0,0) is represented as (i, j), (i, j) is i + j. If is even, it is painted red, and if it is odd, it... | #include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
for(int i=0;i<n;i++){
long long x,y;
cin >> x >> y;
if(x==y)cout << 1 << " " << 0 << endl;
else if(x%2==0||y%2==0)cout << 1 << " " << 1 << endl;
else {
if(x>y)swap(x,y);
if(y%x==0){
y/=x;
x/=x;
}
... |
B: Pivots
problem
Given a permutation of length N, a_1, a_2, ..., a_N, which is a permutation of integers from 1 to N. Also, Q queries are given in order for this permutation. In the i-th query, you have to do the following:
* The value q_i (1 \ leq q_i \ leq N) is given. In the permutation \\ {a_1, a_2, ..., a_N \\... | #include<bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int main(){
int n,q;
cin >> n >> q;
int a[n+1];
for(int i=0;i<n;i++){
cin >> a[i];
}
int pos[n+1], push_i = n, begin_i = 0;
for(int i=0;i<n;i++) pos[a[i]] = i;
int query;
for(int i=0;i<q;i++){
... |
Problem
There are $ n $ bombs on a two-dimensional plane. Each bomb is numbered from 1 to $ n $, and the $ i $ th bomb is located at coordinates $ (x_i, y_i) $.
It is known that all bombs have the same Manhattan distance from the origin.
When the $ i $ th bomb explodes, the bombs that are within $ r_i $ in Manhattan f... | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <numeric>
#include <random>
#include <vector>
#include <array>
#include <bitset>
#include <queue>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map... |
Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:
Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 ... | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct cards
{
int num = 0;
char mrk = 'D';
int idx = 0;
};
int partition(vector<cards>& ary, int p, int r) {
cards x, sw;
int i = 0;
x = ary[r];
i = p - 1;
for (int j = p;j < r;j++) {
if (ary[j].num <= x.nu... |
Given two non-negative decimal integers $a$ and $b$, calculate their AND (logical conjunction), OR (logical disjunction) and XOR (exclusive disjunction) and print them in binary representation of 32 bits.
Constraints
* $0 \leq a, b \leq 2^{32} - 1$
Input
The input is given in the following format.
$a \; b$
Outp... | #include <cstdio>
#include <utility>
#include <bitset>
#include <iostream>
using namespace std;
#define gcu getchar_unlocked
#define pcu putchar_unlocked
#define _T template <typename T>
#define _HT template <typename H, typename... T>
#define _il inline
#define _in _il int in
#define _sc _il bool scan
_T T in(int c){... |
You are given an array of N integers a1, a2, ..., aN and an integer K. Find the number of such unordered pairs {i, j} that
i ≠ j
|ai + aj - K| is minimal possible
Output the minimal possible value of |ai + aj - K| (where i ≠ j) and the number of such pairs for the given array and the integer K.
Input
The first lin... | def test(s,r):
sum=s[1]
k=0
if r[0]+r[1]-sum>0:
i=r[0]+r[1]-sum
else:
i=sum-r[0]-r[1]
for x in range(len(r)):
for y in r[x+1:]:
if r[x]+y-sum>=0:
if r[x]+y-sum<i:
i=r[x]+y-sum
k=1
elif r[x]+y-... |
Recently, chef Ciel often hears about lucky numbers.
Everybody knows that lucky numbers are positive integers
whose decimal representation contains only the lucky digits 4 and 7.
For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Ciel decides to make Ciel numbers.
As you know, Ciel likes the digi... | import sys
def main():
n=int(raw_input())
res=0
for i in range(n):
t=raw_input().split()
t=int(t[-1])
v=t
#print(t)
b=0
v8=v5=v3=0
while t!=0:
r=t%10
t=int(t/10)
#print(r,t)
if r == 8:
v8+=1
elif r==5:
v5+=1
elif r==3:
v3+=1
else:
b=1
break
#print(v,v8,v5,v3)... |
An exam consists of N questions. The marks of the N questions are m1, m2, m3, .. mN respectively.
Jam is giving the exam and he wants to maximise his number of marks.
However he takes some time to solve each question. The time taken by him to solve the questions are t1, t2, t3, .. tN respectively.
The exams lasts for a... | N=int(raw_input())
T=int(raw_input())
m=map(int,raw_input().split())
t=map(int,raw_input().split())
dp = [[0]*(2) for i in range(T+1)]
for i in range(N):
for x in xrange(T,t[i]-1,-1):
dp[x][0]=max(dp[x][0],dp[x-t[i]][0]+m[i])
dp[x][1]=max(dp[x][1],dp[x-t[i]][1]+m[i],dp[x-t[i]][0]+2*m[i])
print dp[T][1] |
For a non-negative integer N, define S(N) as the sum of the odd digits of N
plus twice the sum of the even digits of N.
For example, S(5)=5, S(456)=2*4+5+2*6=25, and S(314159)=3+1+2*4+1+5+9=27.
Define D(N) as the last digit of S(N).
So D(5)=5, D(456)=5, and D(314159)=7.
Given 2 non-negative integers A and B, compute th... | def func(x):
sum=0
if x==0 or x==1:
return 0
sum+= (x/10)*45
for z in range(x-(x%10),x):
sum1=0
while(z):
r=z%10
if(r%2==0):
sum1+= 2*r
else:
sum1+=r
z=z/10
sum+= sum1%10
return sum ... |
You are given an unweighted, undirected graph. Write a program to check if it's a tree topology.
Input
The first line of the input file contains two integers N and M --- number of nodes and number of edges in the graph (0 < N ≤ 10000, 0 ≤ M ≤ 20000). Next M lines contain M edges of that graph --- Each line contains ... | s=raw_input().split()
m,n=int(s[0]),int(s[1])
if m-n==1:
print 'YES'
else:
print 'NO' |
Statement
Given a directed graph G with N vertices and M edges. For each vertex u, you must assign positive integer F(u) such that:
For each edge e from a to b, F(b) > F(a)
The maximum value m = max( F(u) ) is minimized
Output the maximum value m. If no such assignment is possible output "IMPOSSIBLE" (quotes ... | t=input()
for _ in range(t):
k=map(int,raw_input().split(" "))
v=[0]*(k[0]+1)
m,s=0,1
for i in range(k[1]):
p=map(int,raw_input().split(" "))
a,b=p[0],p[1]
if s:
if v[a] == 0: v[a] = 1
if v[b] == 0: v[b] = v[a]+1
if v[b] < v[a]: s=0
if m < v[b]: m=v[b]
if s == 0:
print 'IMPOSSIBLE'
else:
pr... |
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can pe... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = s.nextInt();
Arrays.sort(a);
int i = 0, j = 0;
while(j < n) {
if(a[j] > a[i])
i++;
j++;
}... |
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w× h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ... | w, h, k = input().split()
w = int(w)
h = int(h)
k = int(k)
s = 0
for i in range(k):
k = 2*w + 2*h - 4 - 16*i
s = s + k
print(s)
|
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha).
The house has a staircase and an elevator. If Masha u... | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
void solve (FastScanner in, PrintWriter out) {
int start = in.nextInt(), goal = in.nextInt(), elev = in.nextInt();
int stairTime = in.nextInt(), elevTime = in.nextInt(), doorTime = in.nextInt();
int stair = Math.abs(start-goal)... |
You are given a string s consisting of n lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String s = s_1 s_2 ... s_n is lexicograp... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.io.Closeable;
import... |
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ... |
n = str(input())
alist = input().split(' ')
for i in alist:
if i[0] == n[0]:
print('YES')
exit(0)
elif i[-1] == n[-1]:
print('YES')
exit(0)
print('NO') |
Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i.
She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.
Your task is to find the number of such candies i (let's call these candies goo... | N , vals= int(input()),list(map(int, input().split()))
odds, evens = 0,0
for i in range(N):
if i % 2 == 0:
odds += vals[i]
else:
evens += vals[i]
odds, evens, num_good = evens, odds-vals[0],0
if odds == evens:
num_good+=1
for i in range(1,N):
if i % 2 == 1:
odds = odds - vals[i] + vals[i-1]
else:
... |
You are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t.
Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For exa... | def divide_2(a, m):
r = 0
q = []
for x in a:
cur = r * m + x
q.append(cur // 2)
r = cur % 2
return q
def add(s, t, m):
r = 0
a = []
for x, y in zip(s[::-1], t[::-1]):
cur = r+x+y
a.append(cur % m )
r = cur // m
if r != 0... |
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n... | def divisors(num):
"""
約数全列挙
"""
divisors = []
for i in range(1, int(num ** 0.5) + 1):
if num % i == 0:
divisors.append(i)
if i != num // i:
divisors.append(num // i)
return divisors
T = int(input())
for t in range(T):
N = int(input())
d... |
The Cybermen have again outwitted the Daleks! Unfortunately, this time the Daleks decided to abandon these tasks altogether, which means the Doctor has to deal with them.
The Doctor can handle the Daleks on his own, but Heidi now has to make sure that the Cybermen are kept busy with this next task.
There are k rings ... | #include <bits/stdc++.h>
using namespace std;
int k, n;
const double ep = 1e-8;
const double pi = 3.14159265358979323846264338327950288L;
struct pnt {
double x, y;
pnt(double x = 0, double y = 0) : x(x), y(y) {}
pnt operator+(const pnt &b) { return pnt(x + b.x, y + b.y); }
pnt operator-(const pnt &b) { return p... |
You are given a uppercase Latin letters 'A' and b letters 'B'.
The period of the string is the smallest such positive integer k that s_i = s_{i~mod~k} (0-indexed) for each i. Note that this implies that k won't always divide a+b = |s|.
For example, the period of string "ABAABAA" is 3, the period of "AAAA" is 1, and t... | #include <bits/stdc++.h>
using namespace std;
namespace Primary {
int a, b;
long long ans = 0;
void main() {
scanf("%d%d", &a, &b);
for (int L = 1, R; L <= a + b; L = R + 1) {
int p = (a + b) / L;
R = (a + b) / p;
if (a < p || b < p) continue;
int l_a = (a - 1) / (p + 1) + 1, l_b = (b - 1) / (p + 1)... |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of n digits without leading zeroes. He represented it as an array of d... | import sys
input=sys.stdin.readline
from math import *
n,m=map(int,input().split())
s=list(input().rstrip())
for i in range(n-1):
if m==0:
break
if i>0:
if s[i-1]=='4' and s[i]=='4' and s[i+1]=='7' and i%2==1:
if m%2==1:
s[i]='7'
break
if s[i]=='4' a... |
There are n chips arranged in a circle, numbered from 1 to n.
Initially each chip has black or white color. Then k iterations occur. During each iteration the chips change their colors according to the following rules. For each chip i, three chips are considered: chip i itself and two its neighbours. If the number of... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
int n, k;
char s[N];
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> k;
for (int i = 0; i < n; ++i) {
cin >> s[i];
}
vector<int> arr;
for (int i = 0; i < n; ++i) {
if (s[i] == s[(i -... |
This is the easy version of this problem. The only difference is the limit of n - the length of the input string. In this version, 1 ≤ n ≤ 2000. The hard version of this challenge is not offered in the round for the second division.
Let's define a correct bracket sequence and its depth as follow:
* An empty string... | import java.util.*;
import java.io.*;
public class F {
final static long M = 998244353;
public static void main(String[] args) throws IOException {
FastScanner input = new FastScanner(System.in);
PrintWriter output = new PrintWriter(System.out);
String brackets = input.next();
... |
Given an array a, consisting of n integers, find:
$$$max_{1 ≤ i < j ≤ n} LCM(a_i,a_j),$$$
where LCM(x, y) is the smallest positive integer that is divisible by both x and y. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
Input
The first line contains an integer n (2 ≤ n ≤ 10^5) — the number of element... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int read() {
int s = 0;
char c = getchar(), lc = '+';
while (c < '0' || '9' < c) lc = c, c = getchar();
while ('0' <= c && c <= '9') s = s * 10 + c - '0', c = getchar();
return lc == '-' ? -s : s;
}
void write(long long x) {
if (x < 0) put... |
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a=sorted(a)
b=sorted(b)
print(*a)
print(*b) |
Drazil likes heap very much. So he created a problem with heap:
There is a max heap with a height h implemented on the array. The details of this heap are the following:
This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed f... | //package com.company;
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
public static class Task {
public class ValueWithIndex {
int val, index;
public ValueWithIndex(int v, int i) {
this.val = v;
this.index = i;
... |
Please notice the unusual memory limit of this problem.
Orac likes games. Recently he came up with the new game, "Game of Life".
You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white.
For each iteration of the game (the initial iteration is 0), the color of... | #include <bits/stdc++.h>
using namespace std;
void desperate_optimization(int precision) {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(precision);
}
const int N = 1e3;
const int MAXN = N * N + 5;
int dist[N + 5][N + 5];
bool gru... |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | n = int(input())
arr = list(map(int, input().split()))
brr = arr[:]
t = 0
for i in range(n):
t = arr[i] - 1
brr[t] = i + 1
print(*brr) |
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | for _ in range(int(input())):
n = int(input())
s = list(map(int,input().split()))
#a,b = map(int,input().split())
k = set(s)
if len(list(k)) == 1:
print(n)
else:
print(1)
|
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion i... | #include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N;
scanf("%d", &N);
vector<int> A(N);
for (int i = 0; i < N; ++i) scanf("%d", &A[i]);
int res = 0;
long long score = 0;
vector<vector<int>> div(1, A);
for (int d = 30; d >= 0; --d) {
vector<ve... |
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | import sys
try:
import os
f = open('input.txt', 'r')
sys.stdin = f
except FileNotFoundError:
None
from math import sqrt, ceil
input=lambda: sys.stdin.readline().strip()
o=int(input())
for _ in range(o):
n=int(input())
A=list(map(int,input().split()))
dou=-1 ;las=-1
for i in range(n):
... |
You are given two positive integer sequences a_1, …, a_n and b_1, …, b_m. For each j = 1, …, m find the greatest common divisor of a_1 + b_j, …, a_n + b_j.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^{18}).
The third line co... | from math import gcd
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in b:
ans = a[0]+i
if(len(a)>=2):
ans = gcd(a[0]+i,a[1]+i)
if(len(a)>2):
ans = gcd(ans, a[(len(a)-1)//4]+i)
ans = gcd(ans, a[(len(a)-1)//2]+i)
... |
You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.
<image>
Space can be represented as the XY plane. You are starting at point (0, 0), and Planetforces is locate... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
//FastScanner fs = new FastScanner ();
Scanner scanner = new Scanner (System.in);
... |
Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.
A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for... | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef complex<double> point;
typedef long double ld;
#define pb push_back
#define pii pair < ll , ll >
#define F first
#define S second
//#define endl '\n'
#define int long long
#define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)... |
When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n.
The goal of Little Alawn's puzzle is to make sure no numbers on the same column or ... | /***********************************************
# Filename: 1534_C.cpp
# author: Dios
# created: 2021-06-14 01:35:43
***********************************************/
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
const int maxn=400005;
const int mod=1e9+7;
int T,n;
ll ans;
int p... |
Polycarpus has t safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them.
Polycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote a ... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000 + 10;
int check[MAXN] = {};
int prime[MAXN], ptot;
vector<int> cnt[5][MAXN];
int len;
int mp[5][5];
void init(int N) {
ptot = 0;
for (int i = 2; i <= N; i++) {
if (!check[i]) {
prime[++ptot] = i;
int p = i;
for (int j = 1; j... |
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked ... | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Question181A {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Character[][] arr=new Character[... |
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length — the first one from string a, the second one from string b. The choi... | #include <bits/stdc++.h>
using namespace std;
const double PI = 3.1415926535897932384626433832795;
const double EPS = 1e-9;
const int INF = (1 << 31) - 1;
const long long LLINF = (1LL << 63) - 1;
typedef const vector<vector<int> >& GraphRef;
typedef const vector<vector<pair<int, int> > >& WeightedGraphRef;
char buf[1 <... |
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.
Overall the galaxy has n... | #include <bits/stdc++.h>
inline int getInt() {
int s;
scanf("%d", &s);
return s;
}
using namespace std;
int main() {
const int n = getInt();
const int m = getInt();
vector<set<int> > o(n);
vector<vector<pair<int, int> > > v(n);
for (int i = 0; i < (int)(m); i++) {
const int a = getInt() - 1;
con... |
Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer a. There's only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer b. Petya decided to turn his number a into the number b consecutively performing t... | import java.util.*;
public class f {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
long a = input.nextLong(), b = input.nextLong();
int k = input.nextInt();
int lcm = 1;
for(int i = 2; i<=k; i++) lcm = lcm(lcm, i);
int[] dp = new int[2*lcm];
int start = (in... |
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
* d1 is the distance between the 1-st and the 2-nd station;
* d2 is the distance between the 2-nd and the 3-rd station;
...
* dn - 1 is the distance between the n - 1-th and the n-th station;
... | import sys
f = sys.stdin#open('1.txt')
n = int(f.readline())
a = f.readline().strip('\n').split()
a = [int(x) for x in a]
x,y = f.readline().strip('\n').split()
x,y=int(x),int(y)
x,y=min(x,y), max(x,y)
total = sum(a)
s = sum(a[x-1:y-1])
print min(s, total-s)
|
The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to cho... | #include <bits/stdc++.h>
const double EPS = 1e-6;
const int dx[] = {0, 0, -1, +1};
const int dy[] = {-1, +1, 0, 0};
double x[3], y[3], r[3], ox, oy, a[3];
double f(double ox, double oy) {
for (int i = 0; i < 3; ++i) {
a[i] =
sqrt(((x[i] - ox) * (x[i] - ox)) + ((y[i] - oy) * (y[i] - oy))) / r[i];
}
dou... |
Piegirl has found a monster and a book about monsters and pies. When she is reading the book, she found out that there are n types of monsters, each with an ID between 1 and n. If you feed a pie to a monster, the monster will split into some number of monsters (possibly zero), and at least one colorful diamond. Monster... | #include <bits/stdc++.h>
using namespace std;
const int N = 100010;
const int INF = 0x3f3f3f3f;
const int iinf = 1 << 30;
const long long linf = 2e18;
const int mod = 1000000007;
const int TOO_BIG = 314000000;
const double eps = 1e-7;
void douout(double x) { printf("%lf\n", x + 0.0000000001); }
template <class T>
void ... |
You've got a table of size n × m. We'll consider the table rows numbered from top to bottom 1 through n, and the columns numbered from left to right 1 through m. Then we'll denote the cell in row x and column y as (x, y).
Initially cell (1, 1) contains two similar turtles. Both turtles want to get to cell (n, m). Some... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
const int maxn = 3010;
int n, m;
char c[maxn][maxn];
int dp[maxn][maxn];
int f[3][3];
int Get_DP(int qx, int qy, int zx, int zy) {
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (c[i][j] ... |
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!
The President of Berland was forced to leave only k of the currently existing n subway stations.
The subway stations are located on a straight lin... | #include <bits/stdc++.h>
using namespace std;
pair<long long, int> dist[400000];
long long sum[400000];
long long ans[400000];
int main() {
int n, k;
cin >> n;
for (int i = 1; i <= n; i++) {
long long t;
cin >> t;
dist[i] = pair<long long, int>(t, i);
}
cin >> k;
sort(dist + 1, dist + 1 + n);
... |
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:
* Aij = Aji, for all i, j (1 ≤ i, j ≤ n);
* Bij = - Bji, for all i, j... | #include <bits/stdc++.h>
using namespace std;
bool sortinrevp(const pair<long long, long long> &a,
const pair<long long, long long> &b) {
return (a.first > b.first);
}
bool sortinrev(const long long &a, const long long &b) { return (a > b); }
void solve() {
long long n;
cin >> n;
long long c[n][... |
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!
A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.
There are n booking requests received by now. Each request is characterized by two numbers: ci and p... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class BookingSystem {
static int bina... |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | s=raw_input()
dic={}
for i in s:
if i!=',' and i!='{' and i!='}' and i!=' ':
dic[i]=1;
print len(dic) |
Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | n=int(input())
z=list(map(int,input().split()))
##y=[]
##for i in z :
## y.append(i)
##y.reverse()
##kevin=y.index(1)
count=0
for i in range(n) :
if z[i]==1 :
count+=1
if i+1!=n :
if z[i+1]==0 :
count+=1
else :
counti=1
if ... |
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of sw... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i, A[100000], j, mini, C[100000], min = 1000000000, c = 0;
cin >> n;
for (i = 0; i < n; i++) {
cin >> A[i];
}
for (i = 0; i < n; i++) {
min = 1000000000;
for (j = i + 1; j < n; j++) {
if (A[j] < min) {
min = A[j];
... |
Fox Ciel just designed a puzzle game called "Polygon"! It is played using triangulations of a regular n-edge polygon. The goal is to transform one triangulation to another by some tricky rules.
<image>
Triangulation of an n-edge poylgon is a set of n - 3 diagonals satisfying the condition that no two diagonals share ... | #include <bits/stdc++.h>
using namespace std;
const int MN = 1011;
int n;
bool c[MN][MN];
vector<pair<int, int> > res;
void go(int u, int v, bool first) {
if (u + 1 == v) return;
for (int x = (u + 1), _b = (v - 1); x <= _b; x++)
if (c[u][x] && c[x][v]) {
res.push_back((!first) ? make_pair(1, x) : make_pai... |
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case ... | inp=input()
fl=False
for i in range(len(inp)):
for j in range(i,len(inp)+1):
if inp[:i]+inp[j:]=='CODEFORCES':
fl=True
if fl:
print('Yes')
else:
print('No')
|
A Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure.
As part of this task, we assume that the social network is... | #include <bits/stdc++.h>
using namespace std;
const int N = 30005, M = N << 2;
int n, cnt[N], x[M], y[M], z[M];
bool vis[M], block[M];
vector<int> q, f[N];
void work(int t) {
for (int i : f[t])
if (y[i] == z[i])
if (cnt[y[i]] + 2 - (x[i] == y[i]) < 10)
q.push_back(i), block[i] = 0;
else
... |
Recently Duff has been a soldier in the army. Malek is her commander.
Their country, Andarz Gu has n cities (numbered from 1 to n) and n - 1 bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.
There are also m people living in Andarz Gu (numbered from 1 to m... | import java.io.*;
import java.util.*;
public final class duff_in_the_army
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int n,m,q,LN=21,time... |
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning t... | #include <bits/stdc++.h>
using namespace std;
int N, M, lg;
vector<pair<long long, pair<int, int> > > edge, edge1;
vector<pair<long long, pair<int, int> > > mst;
vector<vector<pair<int, long long> > > adj;
vector<vector<int> > p;
vector<vector<long long> > maxi;
vector<int> dep;
int log(int x) {
int cnt = 0;
while ... |
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel... | import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
Scanner in;
PrintWriter out;
void solve() {
long n = in.nextLong();
long ans = n + (n-1)*n/2;
out.println(ans*6 + 1);
}
void run() {
in = new Scanner(System.in);
... |
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it'... | n,c = map(int,input().split())
p=input().split()
t=input().split()
sl=0
sr=0
ti=0
for i in range(n):
ti+=int(t[i])
if int(p[i])-c*ti>=0:
sl+=int(p[i])-c*ti
ti=0
for i in range(n):
ti+=int(t[n-i-1])
if int(p[n-i-1])-c*ti>=0:
sr+=int(p[n-i-1])-c*ti
if sl == sr:
print('Tie')
elif sl>sr:... |
This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.
Integer x > 1 is called prime if it has exactly two distinct ... | #include <bits/stdc++.h>
using namespace std;
bool prime(int x) {
int cnt = 0;
for (int i = 1; i <= x; i++)
if (x % i == 0) cnt++;
return (cnt <= 2);
}
void fl() { fflush(stdout); }
int kul[] = {4, 9, 25, 49};
char odg[5];
int main() {
int prosti = 1;
for (int i = 0; i < 4; i++) {
printf("%d\n", kul[i... |
Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.
Here are some interesting facts about XXX:
1. XXX consists of n cities, k of whose (just imagine!) are capital cities.
2. All of cities ... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
... |
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats... | #include <bits/stdc++.h>
using namespace std;
int main() {
unsigned long long m, y, n, z;
char b;
cin >> n >> b;
unsigned long long t = n % 4;
if (t == 1 || t == 2) {
z = n / 2;
y = n - 1;
}
if (t == 3 || t == 0) {
z = n / 2 - 1;
y = n - 3;
;
}
m = z * 6 + y;
if (b == 'a') m += 4... |
The process of mammoth's genome decoding in Berland comes to its end!
One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is... | debug = False
n = int( raw_input() )
s = map( str, raw_input() )
cnts = [ 0 for i in range( 5 ) ]
chrs = [ 'A', 'C', 'G', 'T', '?' ]
mpch = { 'A': 0, 'C': 1, 'G': 2, 'T': 3, '?': 4 }
for ts in s:
for ch in chrs:
if ts == ch:
cnts[mpch[ch]] += 1
mx = -1
for i in range( 4 ):
mx = max( mx, ... |
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
Input
The first line of input contains one integer number N (1 ≤ N ≤ 100 000) — the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≤ X, Y ≤ 10... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
long long x[n];
long long y[n];
long long sumx = 0;
long long sumy = 0;
long long sumx2 = 0;
long long sumy2 = 0;
for (int i = 0; i < n; i++) {
cin >> x[i] >> y[i];
sumx += x[i];
sumy += y[i];
sumx2 += x[... |
Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area.
Formally, the carrot can be viewed as an isosceles triangl... | import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class B {
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
... |
On the way to school, Karen became fixated on the puzzle game on her phone!
<image>
The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or col... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6;
int maap[110][110];
struct node {
int w;
int flag;
} ans[maxn];
int main() {
int i, j;
int flag = 0;
int num = 1;
int x, y;
scanf("%d%d", &x, &y);
int n, m;
n = x, m = y;
if (x < y)
flag = 0;
else
flag = 1;
for (i = 0; i... |
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wan... | import operator
class pa():
def __init__(self,b,i):
self.b = b
self.i = i
n = int(input())
a = list(map(int,input().strip().split(' ')))
b = list(map(int,input().strip().split(' ')))
a.sort()
m = []
for i in range(n):
tp = pa(b[i],i)
m.append(tp)
m.sort(key=operator.attrgetter('b'))
c = [0]*n
for i in ran... |
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for whi... | #include <bits/stdc++.h>
using namespace std;
signed main() {
int n;
cin >> n;
vector<string> v(n);
map<string, int> matc;
for (int i = 0; i < n; i++) {
cin >> v[i];
set<string> subss;
for (int j = 0; j < 9; j++) {
for (int k = 0; k + j < 9; k++) {
subss.insert(v[i].substr(k, j + 1))... |
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi... | n=list(input())
m=len(n)
e=0
s=1
if n.count('1')==0:
s=0
for i in range(0,m):
if n[i]=='1':
e=i
break
k=n[e:]
if s==1:
if k.count('0')>=6:
print('yes')
else:
print('no')
else:
print('no')
|
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them ... | //package round74;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Div2A {
Scanner in;
PrintWriter out;
String INPUT = "";
void solve()
{
int[] c = new int[3];
for(int i = 0;i < 3;i++)c[i] = ni();
int t = 30;
int f = 0;
for(int i = 0;i < 3;i++){
if(c[i] <... |
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch... | from collections import Counter
tree = []
class Node:
def __init__(self, num=None):
self.length = 0 if num is None else tree[num-1].length + 1
def main():
n = int(input())
global tree
tree = [Node()]
for x in input().split():
tree.append(Node(int(x)))
print(sum([value & 1 ... |
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of th... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int v[maxn], color[maxn], used[maxn], cnt[maxn];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> v[i];
for (int i = 1; i <= m; i++) cin >> color[i];
int sat = 0, sum = 0;
for (int i = 1; i <= m; i++) {
sum ... |
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right.
Obviously, there is not enough sand o... | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
work();
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return a==0?b:b>=a?gcd(b%... |
Abhinav and Manav both being one of the best coders of SVNIT went onto participate in ACM ICPC Regional Contest. Apparently Manav’s team the 3Horsemen stood ahead of Abhinav’s team akatsuki11 in the contest though both solved the same number of questions .Manav is Abhinav’s greatest rival and Abhinav being adamant abou... | a = [0,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000]
def max():
tval=input()
for t in xrange(tval):
l,r = map(int,raw_input().split())
len_r = len(str(r))
if l <= a[len_r]/2 and r >= a[len_r]/2:
v = a[len_r]/2
tt = str(v)
mir = []
for j in xra... |
The hero of this story is a toddler named BooBoo. Inspired by the legendary competitive coder Gena, BooBoo has also started preparing to race to the top of the ranks.
BooBoo is going to practice N different problems in the exact given order over the next M days. For each problem, he writes down the amount of time q_i ... | t,n = map(int,raw_input().split())
a = map(int,raw_input().split())
z = sum(a)
high = z
low = int(z/t)
while low<high:
mid = int((low+high)/2)
count = 1
flag = 0
num = mid
for x in a:
if x>num:
if x>mid:
low=mid+1
flag = 1
break
... |
We have a S cm long stick.It can be broken only at certain
positions.Sarah wants to calculate the number of GOOD Pairs.
It satisfies the following conditions
A good pair consists of 2 distinct positions where the stick can be
broken.
When the stick is broken at these two positions there should be at
least one st... | from bisect import bisect_left
for _ in xrange(input()):
s,n,l=map(int,raw_input().split())
a=map(int,raw_input().split())
a.sort()
ans=0
for i in xrange(n):
if a[i]>l:
ans+=n-i-1
else:
aa=[]
tmp=bisect_left(a,s-l)-1
if i+1<=tmp:
aa.append([i+1,bisect_left(a,s-l)-1])
#ans+=tmp-1-i
tmp=b... |
find the sum of the even fibonacci numbers till the given number(it is the value not index).
INPUT:
T test cases
next T lines consists of a number n.
OUTPUT:
Output the sum value.
0<t<10
2<n<10^20
Example:
if n=10
the numbers which are less than 10 are 2 and 8 in fibonacci.
sum = 2+8=10
SAMPLE INPUT
2
10
100
SAMPLE... | aa = int(raw_input())
outt=[]
for x in range(aa):
b= int(raw_input())
if b==0 or b==1:
outt.append(0)
else:
l=[0,1]
while(l[-1]<=b):
l.append(l[-1]+l[-2])
s=[j for j in l if j<=b if j%2==0]
outt.append(sum(s))
for k in outt:
print k |
You are given three numbers. Is there a way to replace variables A, B and C with these numbers so the equality A + B = C is correct?
Input:
There are three numbers X1, X2 and X3 (1 ≤ Xi ≤ 10^100), each on a separate line of input.
Output:
Output either "YES", if there is a way to substitute variables A, B and C wit... | a=int(input())
b=int(input())
c=int(input())
if (a+b==c or a+c==b or b+c==a or 2*a==c or 2*a==b or 2*b==a or 2*b==c or 2*c==a or 2*c==b):
print('YES')
else:
print('NO') |
See Russian Translation
After a long term relationship, Anandi and Jagdish decided to marry. Anandi being a studious girl decided to complete her studies first. What next, she comes to ABC Public School. Her classes haven't even started yet and Jagdish becomes restless, comes to her college and asks her to complete he... | a = raw_input('')
a = int(a)
l = []
for cnt in range(a):
b = raw_input('')
b = int(b)
c = b**0.5
c = int(c)
d = c**2
if d == b:
l.append(2*c-1)
elif b<=d+c:
l.append(2*c)
else:
l.append(2*c+1)
for cnt in l:
print(cnt) |
A String is called Palindrome if it reads the same backwards as well as forwards. For example, the String aba can be read the same backwards as well as forwards.
Now, a Permutation of a String S is some String K where S and K contain the same set of characters, however, these characters need not necessarily have the ... | from sys import stdin
a = stdin.readline().strip()
di = {}
od = 0
for i in a:
di[i] = di.get(i,0) + 1
for i in di:
if di[i]%2:
od+=1
ans = 'NO'
if od < 2:
ans = 'YES'
print ans |
Rhezo is the new manager of Specialist Cinema Hall. A new movie is being released this Friday and Rhezo wants people in the hall to be seated according to some rules. His rules are weird and he likes that no 2 people in a row sit together/adjacent. He also wants that there are at least 2 people in each row.
The hall ... | #import time
#time1=time.time()
MOD=1000000007
# rowlen i, people j, f(i,j)=0 if j<(i+1)/2 else i if j==1 else f(i-1,j)+f(i-2,j-1)
combs={3:{2:1},4:{2:3},5:{2:6,3:1},6:{2:10,3:4},7:{2:15,3:10,4:1},
8:{2:21,3:20,4:5}, 9:{2:28,3:35,4:15,5:1}, 10:{2:36,3:56,4:35,5:6}}
#combs=[[0,0,1,0,0,0],[0,0,3,0,0,0],[0,0,6,1,... |
You are given a rectangular grid with n rows and m columns. The rows are numbered 1 to n, from bottom to top, and the columns are numbered 1 to m, from left to right.
You are also given k special fields in the form (row, column). For each i, where 0 ≤ i ≤ k, count the number of different paths from (1, 1) to (n, m)... | N, M, K = map(int, raw_input().split())
special = [[False for j in xrange(M)] for i in xrange(N)]
for k in xrange(K) :
a, b = map(int, raw_input().split())
special[a - 1][b - 1] = True
dp = [[[0 for k in xrange(K + 1)] for j in xrange(M)] for i in xrange(N)]
for k in xrange(K + 1):
specialCount = 0
... |
A Sky bag to lock accepts only the Prime number (all combination of prime numbers are allowed) except ignoring the leading zero's (0's). If there is prime number like '003' or '103' both of them are considered as the valid codes to unlock the Sky bag, but these are the 3 digit numbers.
In a sky bag, the numbered are i... | invalids = [1, 4, 6, 8, 9]
for _ in range(input()):
nod, ins = map(int, raw_input().split())
ans = 0
while ins > 0:
mods = ins % 10
if mods in invalids:
if mods == 9:
ans += 2
else:
ans += 1
ins /= 10
print ans |
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.
Determine whether N is a multiple of 9.
Constraints
* 0 \leq N < 10^{200000}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If N is a multi... | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String number = input.next();
long sum = 0;
for (int i = 0; i < number.length(); i++){
sum += Character.getNumericValue(number.charAt(i));
}
if(sum%9==0){
System.out.println("Yes");... |
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N.
We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7).
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq K \leq N+1
* All values in input are integers.
Input
Input is given from S... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual soluti... |
There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.
Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony say... | #include<bits/stdc++.h>
using namespace std;
#define int long long
pair<int,int> b[55][55];
signed main(){
int n;
cin >> n;
int a[n+1];
for(int i= 0;i<n;i++){
cin >> a[i];
for(int j = 1;j<=a[i];j++){
cin >> b[i][j].first >> b[i][j].second ;
b[i][j].first--;
}
}
int ans = ... |
Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|.
Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.
Constraints
* All values in input are integers.
* 1 \leq n \leq 50
* 0 \leq k \leq n^2
Input
Input is given from... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) REP(i, 0, n)
#define ALL(v) v.begin(), v.end()
#define MSG(a) cout << #a << " " << a << endl;
#define REP(i, x, n) for (int i = x; i < n; i++)
#define OP(m) cout << m << endl;
int mod = 1000000007;
#define mul(a, b) ((a % mod) * (b % mod)) % mod
long l... |
Takahashi received otoshidama (New Year's money gifts) from N of his relatives.
You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either `JPY` or `BTC`, and x_i and u_i represent the content of the otoshidama from the i-th relative.
For example, if x_1 = `10000` a... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double money = 0.;
for (int i = 0; i < n; i++) {
String str = sc.next();
if(sc.next().equals("JPY")) {
money += Integer.parseInt(str);
} else {
mon... |
You are given an integer N.
Construct any one N-by-N matrix a that satisfies the conditions below. It can be proved that a solution always exists under the constraints of this problem.
* 1 \leq a_{i,j} \leq 10^{15}
* a_{i,j} are pairwise distinct integers.
* There exists a positive integer m such that the following h... | #include<bits/stdc++.h>
#define title "title"
#define ll long long
#define ull unsigned ll
#define fix(x) fixed<<setprecision(x)
#define pii pair<ll,ll>
#define vll vector<ll>
#define pb push_back
using namespace std;
void Freopen(){
freopen(title".in","r",stdin);
freopen(title".out","w",stdout);
}
ll read(){
ll g=0... |
You have an integer sequence of length N: a_1, a_2, ..., a_N.
You repeatedly perform the following operation until the length of the sequence becomes 1:
* First, choose an element of the sequence.
* If that element is at either end of the sequence, delete the element.
* If that element is not at either end of the seq... | def examC():
ans = 0
print(ans)
return
def examD():
ans = 0
print(ans)
return
def examE():
N = I()
A = LI()
ans = -inf
S = [0]*(N+1)
fr = [-1]*N
best = -1
for i,a in enumerate(A):
S[i] = a
for j in range(i):
if ((i-j)%2==0):
... |
You are given three integers, A, B and C.
Among them, two are the same, but the remaining one is different from the rest.
For example, when A=5,B=7,C=5, A and C are the same, but B is different.
Find the one that is different from the rest among the given three integers.
Constraints
* -100 \leq A,B,C \leq 100
* A, B ... | #include<iostream>
using namespace std;
int main(){
int a,b,c,d;
cin>>a>>b>>c;
if(a==b){
d=c;
}
else if(a==c){
d=b;
}
else if(b==c){
d=a;
}
cout<<d;
} |
Takahashi loves sorting.
He has a permutation (p_1,p_2,...,p_N) of the integers from 1 through N. Now, he will repeat the following operation until the permutation becomes (1,2,...,N):
* First, we will define high and low elements in the permutation, as follows. The i-th element in the permutation is high if the maxi... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, from, to) for (int i = from; i < (to); ++i)
#define trav(a, x) for (auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
struct Node {
Node *l = 0, *r = 0;
... |
Takahashi is drawing a segment on grid paper.
From a certain square, a square that is x squares to the right and y squares above, is denoted as square (x, y).
When Takahashi draws a segment connecting the lower left corner of square (A, B) and the lower left corner of square (C, D), find the number of the squares cro... | #include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(), (x).end()
typedef long long ll;
typedef long double ld;
const int INF = 1e9;
const ld EPS = 1e-8;
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
int main(){
int A, B, C, D;
cin >>... |
Snuke is having another barbeque party.
This time, he will make one serving of Skewer Meal.
He has a stock of N Skewer Meal Packs. The i-th Skewer Meal Pack contains one skewer, A_i pieces of beef and B_i pieces of green pepper. All skewers in these packs are different and distinguishable, while all pieces of beef an... | #include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
const ll MOD=1e9+7;
ll n,a[200005],b[200005],f[4005][4005],c[4005][4005],ans;
ll quick_pow(ll x,ll a)
{
ll ans=1;
while(a)
{
if(a&1)ans=ans*x%MOD;
x=x*x%MOD;
a>>=1;
}
return ans;
}
int main()
{
scanf("%lld",&n);... |
There are trains with 26 cars or less. Each vehicle has an identification code from lowercase a to z. No vehicle has the same symbol. However, the order in which the vehicles are connected is arbitrary. The conductor patrols the train. The conductor patrolls back and forth in the train, so he may pass through the same ... | #include <stdio.h>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <fstream>
#include <sstream>
#include <math.h>
#include <queue>
#include <stack>
#include <math.h>
using namespace std;
int main(){
int n;
while(cin>>n){
string input;
for(int roop=0; roo... |
Consider a 32-bit real type with 7 bits from the right as the decimal part, the following 24 bits as the integer part, and the leftmost 1 bit as the sign part as shown below (b1, ..., b32). Represents 0 or 1).
<image>
To translate this format into a decimal representation that is easy for humans to understand, inter... | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#define int long long
using namespace std;
class Solver {
};
signed main() {
int q;
cin >> q;
vector<string> qs(q);
for (int i = 0; i < q; i++) {
cin >> qs[i];
}
vector<int> smalls({ 5000000,2500000,1250000,625000,312500,156250,7... |
problem
Play by arranging white and black stones on the table. First, place the stones on the left edge of the table. Then place the stones in the second place from the left. Repeat this n times to arrange n stones in a horizontal row. However, when placing a new i-th go stone, replace the go stone on the table accord... | import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
enum Go {
W, B;
static Go of(String s) {
return ("0".equals(s)) ? W : B;
};
};
public static void main(String[] arg) {
Scanner in = new Scanner(System.in);
for (int n; (n = in.nextInt()) != 0;) {
Dequ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.