input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n.
A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct.
There is only one thing Petya likes more than permutations: playing with little Masha... | #include <bits/stdc++.h>
using namespace std;
inline int in() {
int32_t x;
scanf("%d", &x);
return x;
}
inline string get() {
char ch[1001000];
scanf("%s", ch);
return ch;
}
const long long maxn = 1e6 + 10;
const long long base = 29;
const long long MAX_LG = 21;
const long long mod = 1e9 + 7;
const long lon... |
A root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node.
A root tree is binary if each node has at most two outgoing arcs.
When a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from u to... | #include <bits/stdc++.h>
using namespace std;
struct edge {
int to, flow, cap, rev;
double cost;
edge(int to, int flow, int cap, double cost, int rev)
: to(to), flow(flow), cap(cap), cost(cost), rev(rev) {}
};
class MinCostMaxFlow {
int n_;
vector<double> potentials_;
vector<pair<int, int>> path_;
v... |
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together a... | #include <bits/stdc++.h>
using namespace std;
struct DP {
pair<int, int> five, two;
bool invalid;
} dp[1001][1001];
long long arr[1001][1001], two[1001][1001], five[1001][1001];
int main() {
ios_base::sync_with_stdio(0);
int n;
cin >> n;
bool zero = false;
pair<int, int> idx_zero;
for (int i = 0; i < n;... |
Daniel is organizing a football tournament. He has come up with the following tournament format:
1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stage... | #include <bits/stdc++.h>
using namespace std;
inline long long tri(long long x) { return x * (x - 1) / 2; }
int main() {
unsigned long long n;
cin >> n;
vector<unsigned long long> teams;
for (int i = 0; i < 62; i++) {
unsigned long long tx = (1LL << i) - 1;
unsigned long long lo = 0, hi = (1LL << min(31... |
You are given an array a1, a2, ..., an and m sets S1, S2, ..., Sm of indices of elements of this array. Let's denote Sk = {Sk, i} (1 ≤ i ≤ |Sk|). In other words, Sk, i is some element from set Sk.
In this problem you have to answer q queries of the two types:
1. Find the sum of elements with indices from set Sk: <i... | #include <bits/stdc++.h>
using namespace std;
vector<int> adj[100009], bigs, smalls;
long long int a[100009], vals[100009], updates[100009];
int f[100009];
int store[320 + 10][100009], storeb[320 + 10][320 + 10];
int invb[100009], invs[100009];
int main() {
int n, m, q;
cin >> n >> m >> q;
for (int i = 1; i <= n;... |
There is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters.
<image>
Initially, all the vessels are empty. In some vessels water is poured. All the wa... | #include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")
int on_bit(int N, int pos) { return N = N | (1 << pos); }
int off_bit(int N, int pos) { return N = N & ~(1 << ... |
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.
For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) tw... | a=input()
n=int(0)
ii=int(0)
t=int(0)
e=int(0)
for i in range(len(a)):
if a[i] == "n":
n+=1
if a[i] == "i":
ii+=1
if a[i] == "e":
e+=1
if a[i] == "t":
t+=1
if n >3:
n=int(((n-3)/2))+1
else:
n=int(n/3)
print(min(n,int(e/3),ii,t)) |
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1... | import java.util.*;
public class ArtUnion {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int p[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
... |
Gena doesn't like geometry, so he asks you to solve this problem for him.
A rectangle with sides parallel to coordinate axes contains n dots. Let's consider some point of the plane. Let's count the distances from this point to the given n points. Let's sort these numbers in the non-decreasing order. We'll call the bea... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:512000000")
using namespace std;
template <class T>
inline T sqr(T x) {
return x * x;
}
template <class T>
inline string tostr(const T& x) {
stringstream ss;
ss << x;
return ss.str();
}
inline long long parse(const string& s) {
stringstream ss(s);
lon... |
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ... | import sys
sys.setrecursionlimit(10 ** 6)
def pyes_no(condition) :
if condition :
print ("YES")
else :
print ("NO")
def plist(a, s = ' ') :
print (s.join(map(str, a)))
def rint() :
return int(sys.stdin.readline())
def rints() :
return map(int, sys.stdin.readline().split())
def rfield(n, m = None... |
Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>.
Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].
Input
The only input line contains an integer n (1 ≤ n ≤ 105).
Output
In the first output line, print ... | #include <bits/stdc++.h>
using namespace std;
int mod;
bool prime(int n) {
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) return 0;
}
return 1;
}
int fastpower(int b, int p) {
int res = 1;
int v = b;
while (p) {
if (p & 1) res = (1ll * v * res) % mod;
v = (1ll * v * v) % mod;
p /= 2;
}... |
Fox Ciel is going to travel to New Foxland during this summer.
New Foxland has n attractions that are linked by m undirected roads. Two attractions are called adjacent if they are linked by a road. Fox Ciel has k days to visit this city and each day she will visit exactly one attraction.
There is one important rule i... | #include <bits/stdc++.h>
using namespace std;
const int N = 105;
const int P = 1000000009;
long long exp(long long a, long long x, long long p) {
long long ans = 1;
for (; x; x >>= 1) {
if (x & 1) ans = ans * a % p;
a = a * a % p;
}
return ans;
}
int n, m;
vector<int> ch[N];
vector<int> que[N];
int idx[... |
Tavas lives in Tavaspolis. Tavaspolis has n cities numbered from 1 to n connected by n - 1 bidirectional roads. There exists a path between any two cities. Also each road has a length.
<image>
Tavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like s = s1s2... sk, T(s) is it... | #include <bits/stdc++.h>
const int N = 100000 + 5;
int f[N];
int n, nq;
std::vector<int> edges[N];
int parent[N];
struct Node *nill;
struct Node {
Node *ch[2], *fa;
int lcnt, rcnt, color, sz;
int sum;
Node(int _color = 0, int _sz = 1) : color(_color), sz(_sz) {
ch[0] = ch[1] = fa = nill;
sum = f[color];... |
Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching ps... | #include <bits/stdc++.h>
const int maxn = 100005;
const long long MOD1 = 2000025871;
const long long MOD2 = 500171993;
const long long P1 = 1515313;
const long long P2 = 2281673;
using namespace std;
struct Prefix {
int len, index;
pair<int, int> hash_val;
Prefix() {}
Prefix(int l, int i, int h1, int h2) : len(... |
While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denot... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2000000;
const int mod = 1e9 + 7;
int n, k;
int get(int i, int j) { return (i - 1) * n + j; }
long long l;
int b[maxn], f[maxn], sum[maxn], a[maxn];
int ans = 0;
pair<int, int> c[maxn];
int main() {
scanf("%d %I64d %d", &n, &l, &k);
for (int i = 1; i <=... |
Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.
Nura can buy gadgets for n days. For each day you know the exchange rates of dol... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 200000 + 10;
long long n, m, k, s;
long long a[maxn], b[maxn];
long long Ma[maxn], Mb[maxn];
long long ida[maxn], idb[maxn];
long long t[maxn], c[maxn];
long long cost[maxn];
long long divide(long long a, long long b) {
long long ans = a / b;
if (... |
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The on... | n = input()
ans = 0
for i in range(1, n + 1):
ans += pow(2, i)
print ans |
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T — the minimal number of "likes" necessary for an item to be r... | #include <bits/stdc++.h>
using namespace std;
int main() {
int kitten, F, I, T;
string tmp;
cin >> F >> I >> T;
vector<vector<int> > M(F, vector<int>(I));
for (int f = 0; f < F; ++f) {
cin >> tmp;
for (int i = 0; i < I; ++i) {
M[f][i] = (tmp[i] == 'Y');
}
}
int ans = 0;
for (int i = 0;... |
There are n cities in Bearland, numbered 1 through n. Cities are arranged in one long row. The distance between cities i and j is equal to |i - j|.
Limak is a police officer. He lives in a city a. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he knows that ther... | from collections import Counter
n,a = map(int,raw_input().split())
p = map(int,raw_input().split())
a -=1
ans = 1 if p[a] == 1 else 0
for i in xrange(1,n):
l,r = a-i,a+i
if l >=0 and r >=n:
#only in left
ans += p[l]
elif r < n and l < 0:
ans += p[r]
elif (r < n and l >=0 ) and p[... |
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | n = int(input())
k = 0
l = 0
for i in range(n):
m,c = map(int,input().split())
if m > c:
k +=1
elif c > m:
l +=1
if k > l:
print("Mishka")
elif l > k:
print("Chris")
else:
print("Friendship is magic!^^")
|
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it... | function main() {
var n = Number(readline());
var str = readline();
var numL = 0;
var numR = 0;
for ( var i = 0;i < n;i++){
if(str[i] === "<"){
numL ++;
}else {
break;
}
}
for (var j = n-1;j>=0;j--){
if(str[j] === ">"){
... |
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
* there are exactly n pixels on the d... | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Scanner;
/**
*
* @author asus
*/
public class sizemonitor {
public static void main(String args[]) {
... |
Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions ... | #include <bits/stdc++.h>
using namespace std;
int main() {
unsigned long long a, b;
cin >> a >> b;
if (a < b || a % 2 != b % 2) {
cout << "-1\n";
return 0;
}
unsigned long long x = (a - b) / 2;
unsigned long long y = x + b;
if ((x & (a - x)) != x) {
cout << "-1\n";
return 0;
}
cout << ... |
A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.
Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe fro... | # Method 1a: Using a list comprehension
# a, b, c, d = [int(x) for x in input().split()]
# print(a*b*c*d)
# Method 1b: Using the map function
# a, b, c, d = map(int, input().split())
# print(a*b*c*d)
# Method 2a: List comprehension with stdin and stdout
# from sys import stdin, stdout
# a, b, c, d = [int(x) for x in... |
Those unwilling to return home from a long journey, will be affected by the oddity of the snail and lose their way. Mayoi, the oddity's carrier, wouldn't like this to happen, but there's nothing to do with this before a cure is figured out. For now, she would only like to know the enormous number of possibilities to be... | #include <bits/stdc++.h>
using namespace std;
static const int maxn = 50 + 5;
static const int mod = 1000000007;
int n, d[maxn];
long long f[2][maxn][maxn][maxn][maxn];
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &d[i]);
memset(f[0], 0, sizeof f[0]);
f[0][d[0] == 2][d[0] == 3][d[1] == ... |
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.
Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's defi... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 10;
int n, dps[MAXN], dpd[MAXN], ps[MAXN];
int mxs[(1 << 20)][21];
bool se[(1 << 20)][21];
string w[MAXN];
void setmxs(int ii, int sz, int val) {
if (!se[ii][sz])
mxs[ii][sz] = val, se[ii][sz] = 1;
else
mxs[ii][sz] = min(mxs[ii][sz], val);... |
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr... | s = input()
n = len(s)
if n==1 or n==2:
print(s)
else:
a = ['a','e','i','o','u']
q,w = '',''
if s[0] not in a:
q = s[0]
if s[1] not in a:
w = s[1]
res = s[:2]
for i in range(2,n):
e = s[i]
if e not in a:
if q!='' and w!='':
if q==w=... |
You are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines.
Multiset is a set where equal elements are allowed.
Multiset is called symmetric, if there is a point P on t... | #include <bits/stdc++.h>
using namespace std;
const int N = 2005, M = N * N;
const double z = 1e-8;
int n, ans, m, sum;
double dis[N];
bool bz[N];
struct P {
double x, y;
P() {}
P(double _x, double _y) {
x = _x;
y = _y;
}
} A[N], B[N], H, tmp, Now, zilch;
struct Data {
P w;
double z;
int p, q;
} a... |
Given an integer N, find two permutations:
1. Permutation p of numbers from 1 to N such that pi ≠ i and pi & i = 0 for all i = 1, 2, ..., N.
2. Permutation q of numbers from 1 to N such that qi ≠ i and qi & i ≠ 0 for all i = 1, 2, ..., N.
& is the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_... | #include <bits/stdc++.h>
using namespace std;
int n;
int res[100010];
int cal(int x) {
int tmp = 0;
for (int i = 0; i <= 20; i++)
if ((x >> i) & 1) tmp++;
return tmp;
}
int main() {
cin >> n;
if (n % 2 == 1)
cout << "NO" << endl;
else {
cout << "YES" << endl;
int tn = n;
for (int i = 21;... |
Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.
Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 7;
const int N = 5e3 + 10;
int main() {
int n;
cin >> n;
vector<int> v(n);
map<int, int> mc;
for (auto &x : v) {
cin >> x;
mc[x]++;
}
sort(v.begin(), v.end());
if (v.back() - v.front() < 2) {
cout << n << endl;
for... |
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... | import sys
n, m = map(int, input().split())
a = list(map(int, input().split()))
k = list(map(int, input().split()))
c = 0
s = sum(k)
if m==1:
if a.count(1)==k[0] or k[0] in a:
print("YES")
else:
print("NO")
sys.exit(0)
for i in range(n):
if i+s-1<=n-1:
k0 = [0]*m
for j in a[i:i+s]:
k0[j-1]+=1
... |
You have m = n·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.
Let volume vj of barrel j be equal to the length of the minimal stave in it.
<image>
You want to asse... | import java.io.*;
import java.util.*;
public class Main {
InputReader scn;
PrintWriter out;
String INPUT = "4 2 1\r\n" + "2 2 1 2 3 2 2 3";
void solve() {
int n = scn.nextInt(), k = scn.nextInt(), l = scn.nextInt();
int[] arr = scn.nextArray(n * k);
arr = shuffle(arr);
Arrays.sort(arr);
int x = 0;
f... |
Those of you who are familiar with the TV Show Community and it's 'lovable' character, Abed, who likes to travel around dimensions, parallel universes, and various other parallel time lines, would know that Abed needs your help. And if you aren't familiar, help the kid, anyway.
Now Abed has been told by Britta that sh... | t=input()
while t:
n,m=map(int,raw_input().split())
x1,y1=map(int,raw_input().split())
x2,y2=map(int,raw_input().split())
p=input()
r=abs(x1-x2)
c=abs(y1-y2)
h=min(r,n-r)
v=min(c,m-c)
ans = (h+v)*p
print ans
if ans>1000:
print 'Let go of the group.'
else:
print 'You saved the group.'
t=t-1 |
Exams are over !! Everyone is now in the mood to play the multiplayer game Counter-Strike 1.6. 12 players decide to play Counter-Strike 1.6, each one playing from his own room via LAN on his own laptop. The 12
players (6 on 6) : Counter Terrorists vs Terrorists are playing on the map de_dust 2 .
They decide to play ... | from collections import *
from heapq import *
from bisect import *
from math import *
from itertools import *
inf=float('inf')
if __name__=="__main__":
tcase=int(raw_input())
while tcase>0:
tcase-=1
p,a,b,c,d=map(int,raw_input().split())
if abs(a+b)%2==abs(c+d)%2:
t=0
if a==c and b==d:
t=0
elif a... |
Hansa did not have enough money to pay the bill of the party. Now she loves cupcakes (and can also eat any amount of it apparently), so she came up with a cupcake challenge. She challenges t people individually every time for the challenge. The task is as follows:
Given 3 baskets filled with known amount of cupcakes ... | t=input()
while t:
a,b,c=map(int,raw_input().split())
x=a^b^c;
if(x!=0):
print "NO BILL"
else:
print "BILL"
t-=1 |
Raju loves playing with maths.He is very fond of factorials.Now he is interested in knowing the last five digits n!(nth number factorial).
As he is not very good at programming , so he needs your help.
Your task is to print the last five digits of n!.
If number of digits is less than 5 then print the answer with leadi... | def fact(n):
if n==0:
return 1
return n*fact(n-1)
t=int(raw_input())
for i in range(t):
n=int(raw_input())
str1=""
k=fact(n)
fa=str(k)
if len(fa)==1:
str1='0000'+str1+fa
elif len(fa)==2:
str1='000'+str1+fa
elif len(fa)==3:
str1='00'+str1+fa
elif len(fa)==4:
str1='0'+str1+fa
else:
i=0
while (i<... |
You are lost in a dense jungle and it is getting dark. There is at least one path that leads you to the city on the other side but you cannot see anything until you are right in front of it as the trees and bushes obscure the path.
Devise an algorithm that is guaranteed to find the way out. Your goal is to go out of... | from collections import deque
import fileinput, copy
class Node:
def __init__(self, p, v, t):
self.pos = p
self.value = v
self.node_type = t
def __eq__(self, other):
return self.pos == other.pos
def addToQ(adj_pos, adj_node_value, Q, marked_list):
if (adj_pos[0] > -1 and adj_p... |
In India, there are many railway stations. There's no way you could avoid one. So, the protagonist in our problem is given N railway stations and M direct two way connections for these railway stations. Let us say that we connect railway station u and v directly - that is to say, you can go from u to v directly without... | N, K = [int(i) for i in raw_input().split()]
temp = raw_input().split()
nodes = dict((temp[i],i) for i in range(len(temp)))
graph = dict((i,[]) for i in range(len(temp)))
for i in range(K):
a, b, c = raw_input().split()
c = int(c)
a = nodes[a]
b = nodes[b]
graph[a].append((b,c))
graph[b].append((a,c))
dist = {}... |
You have been given a String S. You need to find and print whether this string is a palindrome or not. If yes, print "YES" (without quotes), else print "NO" (without quotes).
Input Format
The first and only line of input contains the String S. The String shall consist of lowercase English alphabets only.
Output Form... | a=raw_input();
b=a[::-1]
if a==b:
print 'YES'
else:
print 'NO' |
Rhezo likes numbers of the form A^B. But computing A^B, for any 2 numbers A and B is a hard task for him. He would like you to help him out in this.
Input:
First line of input contains a single integer A. Second line contains the integer B.
Output:
Help Rhezo find A^B. As this number can be large, print it modulo 10^... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def power(b, p,md):
if p == 0:
return 1;
elif p%2 == 0:
res = power(b, p/2,md)
return (res*res)%md
else:
res = power(b, p/2,md)
return (... |
Suppose n1, n2, . . . . , nk are positive integers that are pairwise coprime. Then, for any given sequence of integers a1, a2, . . . . , ak, there exists an integer x solving the following system of simultaneous congruences.
x = a1 mod(n1)
x = a2 mod(n2)
.
.
.
x = ak mod(nk)
Furthermore, all solutions x of this... | import functools
import sys
def chinese_remainder(n, a, k):
sum = 0
prod = reduce(lambda a, b: a*b, n)
#prod = 1
#for b in range(k):
# prod=prod*n[b]
for n_i, a_i in zip(n, a):
p = prod // n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = ... |
Given a number find the number of trailing zeroes in its factorial.
Input Format
A single integer - N
Output Format
Print a single integer which is the number of trailing zeroes.
Input Constraints
1 ≤ N ≤ 1000
Problem Setter: Practo Tech Team
SAMPLE INPUT
10
SAMPLE OUTPUT
2
Explanation
10! = 3628800 has 2 ze... | import math
i = input()
if i >= 1 and i <=1000:
f = math.factorial(i)
l = len(str(f))
l1 = [f % (10**k) for k in range(1,l+1) if f % (10**k) == 0]
print len(l1)
else:
print "invalid input" |
Takahashi loves takoyaki - a ball-shaped snack.
With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.
How long does it take to make N takoyaki?
Constraints
* 1 \leq N,X,T \leq 1000
* All values in input are integers.
Input
Input i... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int X = sc.nextInt();
int T = sc.nextInt();
int num = N / X;
if(N % X != 0) ++ num;
System.out.println(num * T);
}
} |
A company has N members, who are assigned ID numbers 1, ..., N.
Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.
When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.
You are given the information ... | N=int(input())
A=list(map(int,input().split()))
b=[0]*N
for c in A:
b[c-1]+=1
for i in b:
print(i) |
Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.
Given is a string S. Find the minimum number of hugs needed to make S palindromic.
Constraints
* S is a string consisting of lowercase English ... | #include <iostream>
#include <string>
using namespace std;
int main(){
string S;
cin>>S;
int len,ans;
ans=0;
len=S.length();
for(int i=0;i<len;i++){
if(S[i]!=S[len-1-i]){ans++;}
}
cout<<ans/2;
} |
You are given a sequence with N integers: A = \\{ A_1, A_2, \cdots, A_N \\}. For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:
* If A_i and A_j (i < j) are painted with the same color, A_i < A_j.
Find the minimum number of col... |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long[] a = new long[n];
... |
You are given a string S as input. This represents a valid date in the year 2019 in the `yyyy/mm/dd` format. (For example, April 30, 2019 is represented as `2019/04/30`.)
Write a program that prints `Heisei` if the date represented by S is not later than April 30, 2019, and prints `TBD` otherwise.
Constraints
* S is... | #include<stdio.h>
int main(){char s[11];scanf("%s",s);printf(s[5]-48||s[6]>52?"TBD":"Heisei");} |
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some ... | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#define SF scanf
#define PF printf
#define MAXN 200010
using namespace std;
typedef long long ll;
int n,m;
int cnt[MAXN][2];
char s[MAXN];
bool del[MAXN];
vector<int> a[MAXN];
void dfs(int x){
del[x]=1;
for(int i=0;i<a[x].size();i... |
On a two-dimensional plane, there are N red points and N blue points. The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).
A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, an... | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
pair<int,int> a[n],b[n];
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
a[i]=make_pair(x,y);
}
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
b[i]=make_pair(y,x);
}
sort(a,a+n);
reverse... |
Three men, A, B and C, are eating sushi together. Initially, there are N pieces of sushi, numbered 1 through N. Here, N is a multiple of 3.
Each of the three has likes and dislikes in sushi. A's preference is represented by (a_1,\ ...,\ a_N), a permutation of integers from 1 to N. For each i (1 \leq i \leq N), A's i-t... | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <bitset>
#include <utility>
#include <assert.h>
using namespace std;
#define rank rankk
#define mp ... |
There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Initially, each edge is painted blue. Takahashi will convert this blue tree into a red tree, by performing the following operation N-1 times:
* Select a simple path that consists of only blue edges, and remo... | #include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#define rep(a,b,c) for (int a=b;a<=c;a++)
#define per(a,b,c) for (int a=b;a>=c;a--)
#define go(u) for (int o=ft[u],v;v=E[o].t;o=E[o].n)
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> par;
const int ... |
A 3×3 grid with a integer written in each square, is called a magic square if and only if the integers in each row, the integers in each column, and the integers in each diagonal (from the top left corner to the bottom right corner, and from the top right corner to the bottom left corner), all add up to the same sum.
... | a=int(raw_input())
b=int(raw_input())
c=int(raw_input())
x=[[0]*3 for _ in xrange(3)]
x[0][0]=a;x[0][1]=b;x[1][1]=c
for i in xrange(1000+1):
x[0][2]=i
msum=a+b+i
x[2][1]=msum-x[0][1]-x[1][1]
x[2][2]=msum-x[0][0]-x[1][1]
if msum-x[2][1]-x[2][2]==msum-x[1][1]-x[0][2]:
x[2][0]=msum-x[2][1]-x[2]... |
Snuke got a present from his mother on his birthday. The present was a pair of two sequences a and b, consisting of positive integers. They satisfied all of the following properties:
* The sum of all elements of a is N.
* The sum of all elements of b is N.
* Any string of length N that satisfies the following two cond... | import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n=sc.nextInt();
int m=sc.nextInt();
int[]a=new int[m],del=new int[m];
int e=0... |
Taro is not good at hide-and-seek. As soon as you hide, you will find it, and it will be difficult to find the hidden child. My father, who couldn't see it, made an ultra-high performance location search system. You can use it to know exactly where your friends are, including your own. Once you become a demon, you can ... | #include <iostream>
#include <vector>
#include <complex>
#include <cmath>
#include <algorithm>
using namespace std;
typedef complex<double> P;
const double EPS = 1e-9;
const double PI = acos(-1);
bool in_range(double a, double x, double b) {
return a-EPS <= x && x <= b+EPS;
}
inline double dot(const P& a, const... |
The following sorting operation is repeated for the stacked blocks as shown in Fig. A.
1. Stack all the bottom blocks (white blocks in Figure a) on the right edge (the remaining blocks will automatically drop one step down, as shown in Figure b).
2. If there is a gap between the blocks, pack it to the left to eliminat... | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
bool check(vector<int> ret)
{
bool flag = true;
REP(i,1,ret.size()+1)
{
if(i != ret[i-1])
{
flag = false;
break;... |
problem
There are n islands in JOI, and each island is numbered from 1 to n. Currently, the JOI country is developing a route network connecting each island.
You work at a ticket center that handles ship tickets. There are many people in JOI who want to travel between islands by boat, as cheaply as possible, and they... | #include<stdio.h>
#define OK 128
const int INF = 1<<25;
int di(const int d[OK][OK],int n,int s,int f){
int i,j,dist[OK],done[OK];
for(i=1;i<=n;i++){
dist[i]=INF;
done[i]=0;
}
dist[s]=0;
for(;;){
int e=-1;
for(i=1;i<=n;i++) if(done[i]==0 && (e==-1 || dist[i] < dist[e])) e=i;
if(e==-1) break;
d... |
Saying that it is not surprising that people want to know about their love, she has checked up his address, name, age, phone number, hometown, medical history, political party and even his sleeping position, every piece of his personal information. The word "privacy" is not in her dictionary. A person like her is calle... | #include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
using namespace std;
struct Button {
int sx, sy, ex, ey;
string to;
bool isHit(int x, int y) {
return ( sx <= x && x <= ex &&
sy <= y && y <= ey );
}
};
struct Page {
vector<Button> buttons;
string click(... |
Legend has it that, after being defeated in Waterloo, Napoleon Bonaparte, in retrospect of his days of glory, talked to himself "Able was I ere I saw Elba." Although, it is quite doubtful that he should have said this in English, this phrase is widely known as a typical palindrome.
A palindrome is a symmetric characte... | #include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<cstdio>
#include<sstream>
#include<iomanip>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loop(i,0,a)
#define pb push_back
#defi... |
There are a number of rectangles on the x-y plane. The four sides of the rectangles are parallel to either the x-axis or the y-axis, and all of the rectangles reside within a range specified later. There are no other constraints on the coordinates of the rectangles.
The plane is partitioned into regions surrounded by ... | //include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <... |
Problem
There is an arithmetic progression A with the number of terms N, the first term a, and the tolerance d. Since M statements that update the sequence are given in the following format, find the value of the K item when the sequence A is updated M times in the given order.
* The i-th statement is represented by ... | n = int(input())
a, d = map(int, input().split())
mem = {}
def get_mem(num):
if num in mem:return mem[num]
else:return num
m = int(input())
for _ in range(m):
x, y, z = map(int, input().split())
if x == 0:
ny, nz = get_mem(y), get_mem(z)
mem[y] = nz
mem[z] = ny
if x == 1:
nz = get_mem(... |
Have you ever heard of Moduic Squares? They are like 3 × 3 Magic Squares, but each of them has one extra cell called a moduic cell. Hence a Moduic Square has the following form.
<image>
Figure 1: A Moduic Square
Each of cells labeled from A to J contains one number from 1 to 10, where no two cells contain the same n... | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <c... |
English text is not available in this practice contest.
At one point, a nobleman fell in love with a brave princess in a poor country and applied for marriage. The princess has given certain conditions to the aristocrats. The condition was to bring in a large number of jewels called "immortal jewels". Immortal gems ar... | #include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
using namespace std;
const double EPS = 1e-10;
const double INF = 1e+10;
const double PI = acos(-1);
int sig(double r) { return (r < -EPS) ? -1 : (r > +EPS) ? +1 : 0; }
inline double ABS(double a){return max(a,-a);}
struct Pt {
double x, y;
Pt() ... |
Example
Input
mmemewwemeww
Output
Cat | #include <iostream>
#include <string>
using namespace std;
typedef string::const_iterator Cursor;
bool cat(Cursor& c,Cursor& e){
if(*c == 'm'){
c++;
cat(c,e);
if(*c == 'e'){
c++;
cat(c,e);
if(*c == 'w'){
c++;
return true;
... |
Problem Statement
You are given a connected undirected graph which has even numbers of nodes. A connected graph is a graph in which all nodes are connected directly or indirectly by edges.
Your task is to find a spanning tree whose median value of edges' costs is minimum. A spanning tree of a graph means that a tree ... | #include <bits/stdc++.h>
using namespace std;
#define all(c) (c).begin(),(c).end()
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--)
#define REP(i,m,n) for(int i=(int)(m);i<(int)(n);i++)
#define rep(i,n) REP(i,0,n)
#define iter(c) __typeof((c).begin())
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
#def... |
Example
Input
5 3
1 5
3 4
5 3
7 2
9 1
Output
5 | #include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <vector>
#include <valarray>
#include <array>
#include <queue>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <complex>
#include <random>
using namespace ... |
problem
In Ikatta, the SNS used by AOR Ika-chan, posts are called tweets.
And in squid, there is a concern that visibility will deteriorate if there are many replies to tweets, so when a tweet meets any of the following rules, the tweet will be displayed on the screen. ing.
* Rule 1. No reply to any tweet
* Rule 2. ... | #include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>
#include<sstream>
#include<iomanip>
#include<assert.h>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loo... |
Problem Statement
Your company is developing a video game. In this game, players can exchange items. This trading follows the rule set by the developers. The rule is defined as the following format: "Players can exchange one item $A_i$ and $x_i$ item $B_i$". Note that the trading can be done in both directions. Items ... | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> P;
LL extgcd(LL a,LL b,LL&x,LL&y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
LL q=a/b;
LL g=extgcd(b,a-q*b,x,y);
LL z=x-q*y;
x=y;
y=z;
return g;
}
vector<pair<int,P>> G[1<<17];
st... |
Problem statement
I have a grid of $ H $ rows and $ W $ columns. Hereafter, the cells in the $ i $ row and $ j $ column on the grid are written as $ (i, j) $ cells.
Each cell in the grid has a number between $ 1 $ and $ 6 $, or the letter `#` in $ 1 $ each. However, `#` is always written in the cell of $ (i, j) $ whe... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) (x).begin(),(x).end()
const int mod=1000000007,MAX=105,INF=1<<30;
struct data{
int h;
int w;
int d;
int f;
int r;
};
bool can[MAX][MAX][7][7][7];
vector<data> G[MAX][MAX][7][7][7];
int S[MAX][MAX];
int H,W;
void D... |
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s... | #include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
typedef pair<int,int>P;
vector<int>E[100000];
int s[100000],t[100000];
int ord[100000],low[100000],k;
bool used[100000];
vector<P>V;
void dfs(int v,int p){
used[v]=true;
low[v]=ord[v]=k++;
for(auto u:E[v]){
if(!used[u]){
dfs(... |
Mr. Yagami is a scientist in the Bhabha Atomic Research Centre. They are
conducting a lab experiment on nuclear fission. In nuclear fission, one atom
breaks into more than one atom of the same type.
Initially, there are N atoms in the lab. Starting from now (t=0), after each
second, every atom will break into ... | import math
t=input("")
while(t):
inp=raw_input("")
inp=inp.split()
n=int(inp[0]);k=int(inp[1]);m=int(inp[2])
m=m/n;
if(m>0):
print int(math.log(m,k))
else:
print 0
t=t-1 |
Today is Chef's birthday. His mom gifted him a truly lovable gift, a permutation of first N positive integers.
She placed the permutation on a very long table in front of Chef and left it for him to play with it. But as there was a lot of people coming and wishing him. It was interfering with his game which made him ve... | A = []
def series(n):
return int(( n * (n + 1) ) / 2)
t = input()
while t > 0:
n,k = list(map(int,raw_input().split()))
if k != 0:
A = list(map(int,raw_input().split()))
A.append(n + 1)
A.sort()
s = 0
i = 0
if k == 0:
s = series(n)
else:
for i in range(0,k + 1... |
Write a program, which takes an integer N and if the number is less than 10 then display "What an obedient servant you are!" otherwise print "-1".
Input
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.
Output
Output the given string or -1 depend... | t=int(raw_input())
while t:
t-=1
n=int(raw_input())
if n<10:
print "What an obedient servant you are!"
else:
print "-1" |
Little Elephant likes lemonade.
When Little Elephant visits any room, he finds the bottle of the lemonade in that room that contains the greatest number of litres of lemonade and drinks it all.
There are n rooms (numbered from 0 to n-1), each contains Ci bottles. Each bottle has a volume (in litres). The first room v... | t = int(raw_input())
for q in xrange(t):
s = raw_input().split();
n = int(s[0])
m = int(s[1])
rooms = map(int,raw_input().split());
arr = [];
count = 0;
for p in xrange(n):
a = map(int,raw_input().split());
a = a[1:];
a.sort();
arr.append(a);
for i in xrange(m):
a = 0;
try:
a = arr[rooms[i]].pop(... |
Problem Description:
Mr. Y’s favourite number is the number 2. Such is his passion that he begins to hate all other digits. Whenever faced with a number he tries to convert it to sum of powers of 2 where the power is non-zero positive integer. If he is successful he calls the number magical. You have to help Mr. Y in c... | a = input()
for x in range(a):
n = input()
if n == 0:
print 'No'
elif n % 2 == 0:
print 'Yes'
else:
print 'No' |
Little Elephant is playing a game with arrays. He is given an array A0, A1, ..., AN−1 of N integers. And then Q queries are given, each containing an integer K. He has to tell how many subarrays satisfy the condition: the function foo returns K when it is applied to the subarray.
In this problem, a subarray is defined ... | N = int(raw_input())
A = map(int, raw_input().split(" "))
min_list = []
for i in xrange(N):
for j in xrange(i,N):
min_list.append(min(A[i:j+1]))
for _ in xrange(int(raw_input())):
K = int(raw_input())
print min_list.count(K) |
You are given n integers a_1, a_2, …, a_n. Each of a_i has between 3 and 5 divisors. Consider a = ∏ a_i — the product of all input integers. Find the number of divisors of a. As this number may be very large, print it modulo prime number 998244353.
Input
The first line contains a single integer n (1 ≤ n ≤ 500) — the ... | //package ;
import java.io.*;
import java.util.*;
public class D
{
public static long gcd(long a,long b)
{
if(b==0)
return a;
return gcd(b, a%b);
}
public static long fun(long x,int deg)
{
long lo=1;
long hi=(long)(deg==2?2e9:1.5e6);
while(lo<=hi)
{
long mid=(hi+lo)/2;
long tmp=1;
for(int... |
Arkady and his friends love playing checkers on an n × n field. The rows and the columns of the field are enumerated from 1 to n.
The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set o... | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
public class B {
void submit() {
int n = nextInt();
int mod = nextInt();
int[] a = new int[mod];
for (int i = 0; i < mod; i++) {
int delta = i == 0 ? 0 : mod - i;
int cnt = Math.floorDiv(n + delta, mod);
if (cnt ... |
Vasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove.
A matching in the graph is a subset of its edges such that there is ... | #include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
int v = 0, f = 1;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-')
f = -1;
else
v = (c & 15);
while (isdigit(c = getchar())) v = (v << 1) + (v << 3) + (c & 15);
x = v * f;
}
inline void read(lo... |
Andrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.
Andrey noticed that snowflakes and candy canes always stand af... | inp=raw_input()
inpk=input()
# inpk=12
ns=0
ny=0
nss=[]
nyy=[]
for i,k in enumerate(inp):
if k=="?":
ns+=1
nss.append(i)
if k=="*":
ny+=1
nyy.append(i)
# print nss,nyy
# print ns,ny
s=""
flag=1
if not (inpk>=len(inp)-2*ns-2*ny):
print "Impossible"
flag=0
elif ny==0:
i... |
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:
You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.
Input
The first line contains an int... | import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class B111 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int last[] = new int[100001];
Arrays.fill(last, 0);
f... |
You are planning to build housing on a street. There are n spots available on the street on which you can build a house. The spots are labeled from 1 to n from left to right. In each spot, you can build a house with an integer height between 0 and h.
In each spot, if a house has height a, you can gain a^2 dollars from... | #include <bits/stdc++.h>
using namespace std;
int l[51], r[51], a[51], c[51], dp[51][51][51];
void inline FilterRestrictions(int i, int j, int h, vector<int> &v) {
vector<int> u;
for (int x : v) {
if (r[x] < i || j < l[x] || a[x] >= h) {
continue;
}
u.push_back(x);
}
v = u;
u.clear();
sort... |
So we got bored and decided to take our own guess at how would "Inception" production go if the budget for the film had been terribly low.
The first scene we remembered was the one that features the whole city bending onto itself:
<image>
It feels like it will require high CGI expenses, doesn't it? Luckily, we came ... | #include <bits/stdc++.h>
using namespace std;
const int INF = 1523456789;
const long double PI = acos(-1);
const int MAX = 7000 * (2e5) + 10;
int get_limit_for(long double angle) {
assert(angle != 0);
long double temp = sin(angle / 2);
temp = 1 / temp;
temp = temp * temp;
temp = temp - 1;
assert(temp != 0);... |
Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings a and b. It is known that |b| ≤ |a|, that is, the length of b is at most the length of a.
The Cossack considers every substring of length |b| in string a. Let's call this substring c. He matches the corresp... | import java.util.Scanner;
import java.util.Vector;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Comparator;
public class C{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
StringBuilder a = new StringBuilder().append(in.next());
... |
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine th... | #include <bits/stdc++.h>
using namespace std;
long long MOD = 1e9 + 7;
long long g, h, l;
const long long N = 10005, inf = 1e9 + 5;
long long ans = 0;
long long add(long long a, long long b);
long long mul(long long a, long long b);
long long binpo(long long a, long long b);
int main() {
ios_base::sync_with_stdio(fal... |
Petya recently found a game "Choose a Square". In this game, there are n points numbered from 1 to n on an infinite field. The i-th point has coordinates (x_i, y_i) and cost c_i.
You have to choose a square such that its sides are parallel to coordinate axes, the lower left and upper right corners belong to the line y... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
template <class T>
inline bool setmin(T &a, T b) {
if (a > b) return a = b, 1;
return 0;
}
templat... |
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r... | #include <bits/stdc++.h>
const int MOD = 1e9 + 7;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
long long n, m;
std::cin >> n >> m;
if (n > m) std::swap(n, m);
std::vector<long long> dpm(m + 1, 0);
dpm[1] = 2;
dpm[2] = 4;
for (int i = 3; i <= m; ++i) dpm[i] = (dpm[i - 2] + dpm[... |
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n ⋅ n!.
Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the... | n = int(input())
f_n = n
cnt = 0
for k in range(n-1, 0, -1):
cnt += f_n
f_n *= k
if f_n >= 998244353:
f_n %= 998244353
print((n*f_n-cnt)%998244353) |
Try guessing the statement from this picture <http://tiny.cc/ogyoiz>.
You are given two integers A and B, calculate the number of pairs (a, b) such that 1 ≤ a ≤ A, 1 ≤ b ≤ B, and the equation a ⋅ b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11)... | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import static java.lang.System.*;
public class B
{
public static void main(String[]args){
InputReader sc = new InputReader(System.in);
PrintWriter pw =new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
... |
<image>
Input
The input contains two integers row, col (0 ≤ row, col ≤ 63), separated by a single space.
Output
Output "IN" or "OUT".
Examples
Input
0 0
Output
OUT
Input
27 0
Output
IN
Input
0 27
Output
OUT
Input
27 27
Output
IN | s = [
"0000000000000000000000000010101111110100000000000000000000000000",
"0000000000000000000000101110101010010111110000000000000000000000",
"0000000000000000000011101000100011010000100100000000000000000000",
"0000000000000000011110101011111000011110101110100000000000000000",
"00000000000000001100000010100000111100001... |
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively).
It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visite... | num_lines = int(input())
for _ in range(num_lines):
d = input()
c = 0
points = set()
start_point = (0, 0)
for s in d:
if s == 'N':
end_point = (start_point[0] + 1, start_point[1])
if s == 'S':
end_point = (start_point[0] - 1, start_point[1])
if s == ... |
This is the easy version of the problem. The difference between versions is the constraints on n and a_i. You can make hacks only if all versions of the problem are solved.
First, Aoi came up with the following idea for the competitive programming problem:
Yuzu is a girl who collecting candies. Originally, she has x ... | import sys
input = sys.stdin.readline
n,p=map(int,input().split())
A=sorted(map(int,input().split()))
MAX=A[-1]
start=max(A[0],MAX-(n-1))
S=[]
ind=0
for c in range(start,MAX+1):
while ind<n and A[ind]<=c:
ind+=1
S.append(ind)
#print(S)
SS=[S[i]-i for i in range(len(S))]
MAX=10**9
MIN=0
for i in ran... |
Boboniu has a directed graph with n vertices and m edges.
The out-degree of each vertex is at most k.
Each edge has an integer weight between 1 and m. No two edges have equal weights.
Boboniu likes to walk on the graph with some specific rules, which is represented by a tuple (c_1,c_2,…,c_k). If he now stands on a v... | #include <bits/stdc++.h>
using namespace std;
const long long NN = 2e5 + 5;
long long n, m, k, D1, D2, D3, D4, D5, has;
vector<pair<long long, long long> > v[NN];
long long d1[10][10];
long long d2[10][10];
long long d3[10][10];
long long d4[10][10];
long long d5[10][10];
long long p3[NN];
long long p4[NN];
long long p... |
You are given an array a consisting of n integers. We denote the subarray a[l..r] as the array [a_l, a_{l + 1}, ..., a_r] (1 ≤ l ≤ r ≤ n).
A subarray is considered good if every integer that occurs in this subarray occurs there exactly thrice. For example, the array [1, 2, 2, 2, 1, 1, 2, 2, 2] has three good subarrays... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops,-ffloat-store")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
using namespace std;
const int maxn = 5e5 + 5;
int n, pr[maxn], id[maxn];
long long a[maxn];
map<long long, int> cnt;
vector<int> pos[maxn];
long long Rand(long lo... |
You are given a multiset S. Over all pairs of subsets A and B, such that:
* B ⊂ A;
* |B| = |A| - 1;
* greatest common divisor of all elements in A is equal to one;
find the sum of ∑_{x ∈ A}{x} ⋅ ∑_{x ∈ B}{x}, modulo 998 244 353.
Input
The first line contains one integer m (1 ≤ m ≤ 10^5): the number of di... | #include <bits/stdc++.h>
using namespace std;
const long long maxn = 1e5 + 5;
const long long mod = 998244353;
long long num[maxn];
long long dp[maxn];
long long mu[maxn];
bool isnp[maxn];
vector<long long> primes;
void init(long long n) {
memset(isnp, false, sizeof(isnp));
primes.clear();
mu[1] = 1;
for (long ... |
Mike received an array a of length n as a birthday present and decided to test how pretty it is.
An array would pass the i-th prettiness test if there is a way to get an array with a sum of elements totaling s_i, using some number (possibly zero) of slicing operations.
<image>
An array slicing operation is conducted... | #include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<math.h>
#include<map>
typedef long long int ll;
using namespace std;
#define maxn 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
const int mm=2e5+100;
ll d[mm],sum[mm];
map<ll,ll> name;
void dfs(ll l,ll r)
{
... |
There are n cities and m bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph is not guaranteed to be connected. Each road has it's own parameter w. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go f... | import sys, io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
read = lambda: map(int, input().split())
from heapq import heappush, heappop
inf = 1e10
n, m = read()
e = {}
for _ in range(m):
v, u, w = read()
v -= 1
u -= 1
if v not in e:
e[v] = []
if u not in e:
e[u]... |
Imagine a board with n pins put into it, the i-th pin is located at (x_i, y_i). For simplicity, we will restrict the problem to the case where the pins are placed in vertices of a convex polygon.
Then, take a non-stretchable string of length l, and put it around all the pins. Place a pencil inside the string and draw ... | #include <bits/stdc++.h>
using namespace std;
const double pi14 = atan(1);
const double pi2 = pi14 * 8;
struct point {
double x, y;
point operator-(const point & p) const{
return {x - p.x, y - p.y};}
double crossP(const point &p) const{
return x * p.y - y * p.x;}
double crossP(const poi... |
Polycarp is playing a new computer game. This game has n stones in a row. The stone on the position i has integer power a_i. The powers of all stones are distinct.
Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone... | t=int(input())
while t!=0:
t-=1
n=int(input())-1
a=list(map(int,input().split()))
le=min(a.index(max(a)),a.index(min(a)))
ri=max(a.index(max(a)),a.index(min(a)))
mid=ri-le-1
ri=n-ri
print(sum([le,ri,mid])-max(le,ri,mid)+2) |
Life is not easy for the perfectly common variable named Vasya. Wherever it goes, it is either assigned a value, or simply ignored, or is being used!
Vasya's life goes in states of a program. In each state, Vasya can either be used (for example, to calculate the value of another variable), or be assigned a value, or i... | #include <bits/stdc++.h>
using namespace std;
int n, m, a[100011];
vector<int> head[100011], bot[100011];
bool chk[100011], kt[100011];
void input() {
int i, u, v;
scanf("%d", &n);
scanf("%d", &m);
for (i = 1; i <= n; i++) scanf("%d", &a[i]);
for (i = 1; i <= m; i++) {
scanf("%d", &u);
scanf("%d", &v)... |
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: <ima... | #include <bits/stdc++.h>
using namespace std;
int main() {
long double s;
cin >> s;
long double a, b, c;
cin >> a >> b >> c;
if (a == 0 && b == 0 && c == 0) {
cout << 0 << " " << 0 << " " << 0;
return 0;
}
long double n1 = s * a, n2 = s * b, n3 = s * c, d1 = a + b + c,
d2 = a + b + c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.