input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
You are given a square matrix M and a positive integer N. You will have to compute M raised to the power N. (that is, M multiplied with itself N times.)
Input
First line of input is T ( number of test-cases) .
First line of each test-case contains two integer M , N where M is size of square array that you have to ex... | def matrix_mult(A, B , m):
C = [[0 for x in range(m)] for x in range(m)]
for i in range(m):
for j in range(m):
for k in range(m):
C[i][k] = (C[i][k] + A[i][j] * B[j][k]) % 1000000007
return C
def fast_exponentiation(A, m,n):
if n == 1:
return A
else:
if n % 2 == 0:
A1 = fast_e... |
Sachin wants to give a love letter to his girlfriend on valentines day. He
is having a circular piece of paper of radius "r".
He wants to use rectangular piece of paper for letter writing whose length and breadth are integers. In how many ways can he do that.
NOTE : Rectangle of a * b and b * a are considered as di... | print 424 |
Given an array of N elements, check if it is possible to obtain a sum of S, by choosing some (or none) elements of the array and adding them.
Input:
First line of the input contains number of test cases T. Each test case has three lines.
First line has N, the number of elements in array.
Second line contains N space s... | import math
def yesno(result, arr):
sums = [0]
for n in arr:
new_sums = []
for sum in sums:
new_sum = sum + n
if new_sum == result:
return "YES"
else:
new_sums.append(new_sum)
sums += new_sums
return "NO"
... |
You are situated in an N dimensional grid at position (x1,x2,...,xN). The dimensions of the grid are (D1,D2,...DN). In one step, you can walk one step ahead or behind in any one of the N dimensions. (So there are always 2×N possible different moves). In how many ways can you take M steps such that you do not leave the ... | MOD = 1000000007
def solve(n, m, x, d):
mat = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(n):
mat1 = [[0 for j in range(m + 1)] for k in range(d[i] + 1)]
D = d[i]
for j in range(1, D + 1):
mat1[j][0] = 1
for j in range(1, m + 1):
for k in range(1, D + 1):
mat1[k][j] = 0
if k... |
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.
The N players will arrive at the place one by one in some order. To ma... | n,*a=map(int,open(0).read().split())
a.sort()
a=a[::-1]
ans=0
for i in range(1,n):
ans+=a[i//2]
print(ans) |
For a non-negative integer K, we define a fractal of level K as follows:
* A fractal of level 0 is a grid with just one white square.
* When K > 0, a fractal of level K is a 3^K \times 3^K grid. If we divide this grid into nine 3^{K-1} \times 3^{K-1} subgrids:
* The central subgrid consists of only black squares.
* Ea... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#ifdef tabr
#include "library/debug.cpp"
#else
#define debug(...)
#endif
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int q;
cin >> q;
vector<ll> p(31, 1);
for (int i = 0; i < 30; i++) {
p[i + 1] = p[i] * 3;
... |
Takahashi is standing on a multiplication table with infinitely many rows and columns.
The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).
In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).
Given an integer N, find the minimum number of moves needed to reach a ... | N = int(input())
n = 1
last = 0
while n**2 <= N:
if N%n == 0 :
last = n
n += 1
print(last + N//last - 2) |
There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.
The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.
Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 woul... | #include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < n; ++i)
using namespace std;
typedef long long ll;
int mod;
struct mint {
ll x;
mint(ll x=0):x(x%mod){}
mint& operator+=(const mint a) {
(x += a.x) %= mod;
return *this;
}
mint& operator-=(const mint a) {
(x += mod-a.x) %= mod;
ret... |
You have written N problems to hold programming contests. The i-th problem will have a score of P_i points if used in a contest.
With these problems, you would like to hold as many contests as possible under the following condition:
* A contest has three problems. The first problem has a score not greater than A poin... | n=int(input())
a,b=map(int, input().split())
*p,=map(int, input().split())
mn,md,mx=0,0,0
for pi in p:
if pi<=a:
mn+=1
elif pi<=b:
md+=1
else:
mx+=1
print(min(mn,md,mx))
|
Let us consider a grid of squares with 10^9 rows and N columns. Let (i, j) be the square at the i-th column (1 \leq i \leq N) from the left and j-th row (1 \leq j \leq 10^9) from the bottom.
Snuke has cut out some part of the grid so that, for each i = 1, 2, ..., N, the bottom-most h_i squares are remaining in the i-t... | #include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 110;
const int base = 1e9+7;
int n,a[maxn];
ll f[maxn][maxn];
map<int,int> cnt;
vector<int> h;
ll pw(int a,int n) {
if (n==0) return 1ll;
if (n==1) return a;
ll tmp = pw(a,n/2);
tmp = (tmp*tmp)%base;
if (n%2==0) ... |
AtCoDeer the deer is going on a trip in a two-dimensional plane. In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i.
If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1... | #include<bits/stdc++.h>
using namespace std;
int n,a,b,c;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d%d%d",&a,&b,&c);
b=max(b,-b),c=max(c,-c);
if((b+c)%2!=a%2)
{
cout<<"No\n";
return 0;
}
if(b+c>a)
{
cout<<"No\n";
return 0;
}
}
cout<<"Yes\n";
return 0;
} |
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain?
Constraints
* 1 \leq |A| \leq 200... | #include<cstdio>
#include<cstring>
#define maxn 200005
#define D 26
#define LL long long
int n,cnt[D];
char s[maxn];
int main()
{
scanf("%s",s+1);
n=strlen(s+1);
for(int i=1;i<=n;i++) cnt[s[i]-'a']++;
LL ans=1ll*n*(n-1)/2;
for(int i=0;i<D;i++) ans-=1ll*cnt[i]*(cnt[i]-1)/2;
printf("%lld\n",ans+1);
} |
You are given N items.
The value of the i-th item (1 \leq i \leq N) is v_i.
Your have to select at least A and at most B of these items.
Under this condition, find the maximum possible arithmetic mean of the values of selected items.
Additionally, find the number of ways to select items so that the mean of the values o... | import java.io.*;
import java.util.*;
import java.math.BigDecimal;
public class Main {
public static long combination(int n, int r) {
r = Math.min(r, n - r);
if (r == 1) {
return n;
}
long sum = 1;
for (int i = 1; i <= r; i++) {
sum = sum * (n -... |
Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones b... | s=input()
a=s[0]
c=0
for i in range(1,len(s)):
if s[i]!=a:
c+=1
a=s[i]
print(c) |
Seen from above, there is a grid-like square shaped like Figure 1. The presence or absence of "walls" on each side of this grid is represented by a sequence of 0s and 1s. Create a program that stands at point A, puts your right hand on the wall, keeps walking in the direction of the arrow, and outputs the route to retu... | #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
const ld eps = 1e-9;
// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c+... |
Blackjack is a type of card game played in casinos, where the game is played using cards with numbers from 1 to 13. The score of each card is decided as follows.
* 1 is 1 point or 11 points
* From 2 to 9, the score is as written.
* 10 points from 10 to 13
There are several participants in this game, including paren... | #include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
#define rep(i,n) for(int i=0; i<n; i++)
void split( vector<int>& vi, string in ) {
int i=0;
while( i < in.length() ) {
int x = 0;
while( i < in.length() && in[i]!=' ' ) {
x *= 10;
... |
Have you ever had an infinite loop when you ran a hard-working program? It would be convenient to be able to determine in advance whether a program will stop executing without having to execute it.
Unfortunately, it is not possible to make such a decision for any program in the programming language you normally use. H... | #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
const ld eps = 1e-9;
struct sentence {
int type;
int a;
int b;
int c;
};
map<int, int>line_mp;
map<string, int>name_mp;
bool memo[51][(1 << 20)];
int getid(vector<int... |
JOI is playing with a nail in the board. As shown in the figure below, JOI stabbed nails in the shape of an equilateral triangle with N sides. A nails are lined up in the ath line (1 ≤ a ≤ N) from the top. The bth nail (1 ≤ b ≤ a) from the left is represented by (a, b).
<image>
Figure 1: Arrangement of nails (when N =... | n,m = map(int,input().split())
t = [[0]*(n+2) for i in range(n+2)]
for i in range(m):
a,b,x = map(int,input().split())
a -= 1
b -= 1
t[a][b] += 1
t[a][b+1] -= 1
t[a+x+1][b] -= 1
t[a+x+1][b+x+2] += 1
t[a+x+2][b+1] += 1
t[a+x+2][b+x+2] -= 1
for i in range(n+2):
for j in range... |
Polygons are the most fundamental objects in geometric processing. Complex figures are often represented and handled as polygons with many short sides. If you are interested in the processing of geometric data, you'd better try some programming exercises about basic operations on polygons.
Your job in this problem is ... | #include <cstdio>
int n,x[50],y[50];
int main(){
for(int c=1;;c++){
float a=0;
scanf("%d",&n); if(!n) break;
for(int i=0; i<n; i++)
scanf("%d %d",&x[i],&y[i]);
for(int i=0; i<n; i++)
a += 0.5*(x[i]*y[(i+1)%n]-y[i]*x[(i+1)%n]);
a *= a>0?1:-1;
printf("%d %.1f\n",c,a);
}
} |
Let’s play a card game called Gap.
You have 28 cards labeled with two-digit numbers. The first digit (from 1 to 4) represents the suit of the card, and the second digit (from 1 to 7) represents the value of the card.
First, you shuffle the cards and lay them face up on the table in four rows of seven cards, leaving a... | #include <cstdio>
#include <queue>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;
struct Board {
char state[4][8];
Board(){}
};
bool operator< (const Board& lhs, const Board& rhs) {
return memcmp(&lhs, &rhs, sizeof(Board)) < 0;
}
int board[4][8];
void init() {
memset(board, 0, sizeo... |
Example
Input
4 4
0 0
6 0
6 6
0 6
Output
35.759506 | #include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<complex>
#include<cassert>
#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b)) < EPS)
#define COUNTER_CLOCKWISE 1
#... |
500-yen Saving
"500-yen Saving" is one of Japanese famous methods to save money. The method is quite simple; whenever you receive a 500-yen coin in your change of shopping, put the coin to your 500-yen saving box. Typically, you will find more than one million yen in your saving box in ten years.
Some Japanese people... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vector<int>>;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
const ld eps = 1e-9;
const ll MOD = 1000000007;
const int INF = 1000000000;
const ll LIN... |
Let S be the sum of divisors of an integer N excluding the number itself. When N = S, N is called a perfect number, when N> S, N is called a defendant number, and when N <S, N is called an abundant number. Create a program that determines whether a given integer is a perfect number, a missing number, or an abundant num... | import java.util.Scanner;
public class Main
{
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext())
{
int n=sc.nextInt();
if(n==0)
return;
if(n==1)
{
System.out.println("deficient number");
continue;
}
int sum=1;
for(int i=2;i*i<... |
Rabbits and cats are competing. The rules are as follows.
First, each of the two animals wrote n2 integers on a piece of paper in a square with n rows and n columns, and drew one card at a time. Shuffle two cards and draw them one by one alternately. Each time a card is drawn, the two will mark it if the same number a... | #include<iostream>
#include<vector>
#include<algorithm>
#include<tuple>
using namespace std;
int main() {
int n, u, v, m;
cin >> n >> u >> v >> m;
bool draw = true;
int val;
vector<pair<int,int>> usagi(1000001), neko(1000001);
vector<int> usanum,nekonum;
for(int i=0 ; i<n ; i++){
f... |
Taro came to a square to look for treasure. There are many treasures buried in this square, but Taro has the latest machines, so he knows everything about where the treasures are buried. Since the square is very wide Taro decided to look for the treasure to decide the area, but the treasure is what treasure does not kn... | #include <bits/stdc++.h>
using namespace std;
#define for_(i,a,b) for(int i=(a);i<(b);++i)
#define allof(a) (a).begin(),(a).end()
void uniqueVector(vector< int >& vec) {
sort(allof(vec));
vec.erase(unique(allof(vec)), vec.end());
}
void solve(
int n, int m,
const vector< int >& tx, const vector< int >& ty
) {
... |
Broken crypto generator
JAG (Japanese Alumni Group) is a mysterious organization composed of many programmers, and in order to enter the building where the headquarters of this organization is located, it is necessary to solve the ciphertext generated by a certain machine every time. This ciphertext consists of the sy... | import java.util.*;
import java.math.*;
class Main{
public static void main(String[] args){
Solve s = new Solve();
s.solve();
}
}
class Solve{
Solve(){}
Scanner in = new Scanner(System.in);
void solve(){
while(in.hasNext()){
String s = in.next();
if(s.equals(".")) return;
System.out.println(cal... |
B-Mansion and courier
Problem Statement
Taro lives alone in a mansion. Taro, who loves studying, intends to study in his study in the house today. Taro can't concentrate outside the study, so he always studies in the study.
However, on this day, $ N $ of courier service to Taro arrived. $ i $ ($ 1 \ leq i \ leq N $)... | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int N = sc.nextInt();
int M = sc.nextInt();
int T = sc.nextInt();
int[] a = new int[N];
for(int i = 0; i < N; i++) {
a[i] = sc.nextI... |
problem
Given a sequence $ a_i $ of length $ N $. Output all integers $ K (1 \ le K \ le N) $ that satisfy the following conditions.
Condition: Well sorted $ a_1, \ cdots, a_K $ matches $ a_ {N-K + 1}, \ cdots, a_N $.
Example
Input
8
5 2 4 9 4 9 2 5
Output
1 2 4 6 7 8 | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define pb emplace_back
#define INF (1e9+1)
int main(){
int n;
cin>>n;
vector<int> a(n);
rep(i,n)cin>>a[i];
multis... |
Problem
Given two sequences of length $ N $, $ A $ and $ B $. First, the $ i $ item in the sequence $ A $ is $ a_i $, and the $ i $ item in the sequence $ B $ is $ b_i $.
Since a total of $ Q $ of statements of the following format are given, create a program that processes in the given order.
Each statement is repr... | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define pb push_back
struct MinSegTree{
int n;
vector<int> dat;
MinSegTree(){}
MinSegTree(int _n){
n = 1;
while(n<_n) n*=2;
dat = vector<int>(2*n-1,INT_MAX);
}
void update(i... |
Shell Sort
Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.
1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g... | def insertionSort(a, n, g):
global cnt
for i in range(g, n):
v = a[i]
j = i - g
while j >= 0 and a[j] > v:
a[j+g] = a[j]
j = j - g
cnt = cnt + 1
a[j+g] = v
def shellSort(a, n):
global cnt
global G
global m
cnt = 0
G = [1]
... |
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$.
A column vector with m elements is represented by the following equation.
\\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\]
A $n \times m$ matrix with $m$ column ve... | #include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
int a[100][100], b[100];
int main() {
int n, m; cin >> n >> m;
rep(i, n)rep(j, m)cin >> a[i][j];
rep(i, m)cin >> b[i];
rep(i, n) {
int sum = 0;
rep(j, m)sum += a[i][j] * b[j];
cout << sum << endl;
}
} |
Chef's encounters with sweets continue with this problem! This time, he wants to distribute chocolates to his N students sitting on a long bench. The students are ordered according to the scores they got from the last exam.
Chef wants to give more chocolates to the higher-scoring students. He also has a few more restr... | t=input()
while t!=0:
n,c=raw_input().split(' ')
n=int(n)
c=int(c)
s=0
flag=0
d=1
first=0
last=0
while d<=2:
first=(2*c-n*(n-1)*d)/(2*n)
if first<1:
flag=0
break
last=first+(n-1)*d
s=n*(first + last)/2
... |
Arush was not always poor at Mathematics but his recent performances had not been that good and he had lost his confidence. Now his elder brother was determined to bring back his confidence back in Mathematics.
So he made a tricky question and made sure that Arush would be able to do solve it. The factorial of a non-ne... | t=input()
for x in range(t):
l=input()
r=raw_input()
s=''
for i in range(l):
# if i==0 or i==1:
# continue
if r[i]=='2' or r[i]=='3' or r[i]=='5' or r[i]=='7':
s=s+r[i]
elif r[i]=='4':
s=s+'322'
elif r[i]=='6':
s+='35'
elif r[i]=='8':
s+='2227'
elif r[i]=='9':
s+='7332'
s=sorted(s)
k='... |
A tutorial for this problem is now available on our blog. Click here to read it.
You are asked to calculate factorials of some small positive integers.
Input
An integer t, 1 ≤ t ≤ 100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1 ≤ n ≤ 100.
Output
For each integer n ... | t=input()
while t > 0:
m=1
x=input()
for i in range(x):
m=m * x
x=x-1
print m
t=t-1 |
Problem Statement
Little Elephant from Zoo of Lviv likes bamboo very much. He currently has n stems of bamboo, Hi - height of i-th stem of bamboo (0-based numeration).
Today inspector Andrii from World Bamboo Association is visiting the plantation. He doesn't like current situation. He wants the height of i-th stem t... | for _ in xrange(int(raw_input())):
n = int(raw_input())
l1 = map(int, raw_input().split())
l2 = map(int, raw_input().split())
s1 = sum(l1)
s2 = sum(l2)
if n == 1:
if s2 > s1:
print -1
if s2 == s1:
print 0
if s1 > s2:
print s1 - s2
elif n == 2:
if s1 != s2:
print -1
else:
print abs(l1[0] ... |
For Turbo C++ Users : Read the following document before attempting the question :
Problem Description
N-Boy is very eccentric when it comes to strings. These days, he spends most of his time studying palindromes and pangrams (for his IP assignment at IIITD). For those of you who don’t know, a palindrome is a word ... | #Enter your code here
import sys
a=set('abcdefghijklmnopqrstuvwxzy')
sys.stdin.readline()
f=sys.stdin.readlines()
for i in f:
i=i.strip()
if i[::-1]==i and set(i)==a:print 'palingram'
elif i[::-1]==i:print 'palindrome'
elif set(i)==a:print 'pangram'
else:print 'none' |
A factory called 'IP Labs Pvt. Ltd.' has produced some material, which is in the form of blocks. Each block is labeled by an alphanumeric character. You've been recently hired as Packaging Manager, and your job is to rearrange the huge lot of manufactured blocks and then extract out the useful blocks from it which can ... | import sys
t=int(input())
while t>0:
A=list(raw_input())
B=list(raw_input())
C=list(set(B))
D=[]
F=[]
Arr=[]
for i in xrange(len(C)):
x=(A.count(C[i]))/(B.count(C[i]))
Arr.append(x)
print min(Arr)
t=t-1 |
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup!
Actually, Polycarp has already came up with the name but some improvement ... | #include <bits/stdc++.h>
using namespace std;
long long read() {
char ch = getchar();
long long x = 0;
int op = 1;
for (; !isdigit(ch); ch = getchar())
if (ch == '-') op = -1;
for (; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
return x * op;
}
int n, m, a[100005], b[100005][70], tmp... |
In this problem we consider a very simplified model of Barcelona city.
Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal... | import math
a,b,c=map(int,input().split())
x1,y1,x2,y2=map(int,input().split())
s=abs(x1-x2)+abs(y1-y2)
if a!=0:
xk1=-1*(b*y1+c)/a
xk2=-1*(b*y2+c)/a
else:
xk1=10**18
xk2=10**18
if b!=0:
yk1=-1*(a*x1+c)/b
yk2=-1*(a*x2+c)/b
else:
yk1=10**18
yk2=10**18
lx1=abs(y1-yk1)
lx2=abs(y2-yk2)
ly1=ab... |
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...
To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most l centimeters after haircut, where l is her favorite number. Suppose, that the Alice's he... | n, m, l = map(int, input().split())
a = list(map(int, input().split()))
nexxt = {}
prevv = {}
nexxt[-1] = n
prevv[n] = -1
summ = 0
p = -1
l += 1
for k in range(n):
if a[k] < l:
p1 = p
p = k
nexxt[k] = n
prevv[k] = p1
nexxt[p1] = k
if k - prevv[k] > 1:
sum... |
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array a=[1, 3, 3, 7] is good because there is the element a_4=7 which equals to the sum 1 + 3 + 3.
You are given an array a consisting of n integers. Your task is to print all indices j of this a... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class GoodArray {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer... |
You are given an n × m table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every 2 × 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.
Input
First... | import java.io.PrintWriter;
import java.util.Scanner;
public class NiceTable {
int N, M, x, y, xx, yy;
char grid[][], d[] = { 'A', 'G', 'C', 'T' };
int costR(int r, int x, int y) {
int a = 0, b = 0;
for (int i = 0; i < M; i += 2) {
a += grid[r][i] == d[x] ? 0 : 1;
b += grid[r][i] == d[y] ? 0 : 1;
}
... |
Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.
You are given two matrices A and B of size n × m, each of which consists of 0 and 1 only. You can apply the following operation to the matrix A arbitrary number of times: take any subma... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
bool x;
cin >> n >> m;
vector<bool> rowAXor(n);
vector<bool> rowBXor(n);
vector<bool> colAXor(m);
vector<bool> colBXor(m);
int totalBXor = 0, totalAXor = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >>... |
The recent advances in AI research has brought humanity to the point when the AIs finally attempt a takeover. Their weapon of choice? The [most intellectually challenging game in the world](//codeforces.com/contest/409/problem/A), rock-paper-scissors!
The future of humanity looks bleak, given the existence of the robo... | #include <bits/stdc++.h>
using namespace std;
const string T = "RRRRPSSPRR";
string s, t, s1;
int main() {
string s, t;
for (int i = 0; i < 10; i++) {
printf("%c\n", T[i]);
fflush(stdout);
getline(cin, s1);
s += (s1 == "ai" ? '0' : '1');
}
if (s == "0000100100") t = "PPPPPPPPPP";
if (s == "000... |
In a magical land there are n cities conveniently numbered 1, 2, ..., n. Some pairs of these cities are connected by magical colored roads. Magic is unstable, so at any time, new roads may appear between two cities.
Vicky the witch has been tasked with performing deliveries between some pairs of cities. However, Vicky... | import javax.smartcardio.ATR;
import java.io.*;
import java.util.*;
public class Main {
static int n;
static HashMap<Integer,Integer> gr[];
static HashSet<Integer> p[];
static dsu lol;
static void union(int a, int b) {
a = lol.get(a);
b = lol.get(b);
if (p[a].size() > p[b].s... |
The only difference between easy and hard versions is constraints.
If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.
A session has begun at Beland State University. Many students are taking exams.
Polygraph Poligrafovich is going to examine a group of n students. Students ... | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
# sys.setrecursionlimit(10**6)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(... |
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | #include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int a = s.length();
int i = 0;
if (a % 2 == 0) {
cout << a / 2;
} else {
int count = 0, z = 0;
for (i = 1; i <= 99; i += 2) {
z++;
if (a == i) {
for (int j = 1; j < a; j++) {
if (s[j] == ... |
Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on n vertices.
Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from 1 to n which he was presented at his last birthday, so h... | #include <bits/stdc++.h>
using namespace std;
int n;
int a[400005];
int l[400005], r[400005];
int aintlz[1600005], lazy[1600005];
int aint[800005];
int h[400005];
void init(int nod, int l, int r) {
if (l == r)
aint[nod] = l;
else {
int mid = (l + r) / 2;
init(2 * nod, l, mid);
init(2 * nod + 1, mid ... |
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int MAXN = 1e5 + 100;
long long n, k;
vector<pair<long long, long long>> sieve(long long n) {
vector<pair<long long, long long>> v;
for (long long i = 2; i * i <= n; i++)
if (n % i == 0) {
long long kk = 0;
while (n % 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... | #include <bits/stdc++.h>
using namespace std;
char ch[2010];
int i, j, n, g[2010][2010], f[2010][2010], ans;
int main() {
scanf("%s", ch + 1);
n = strlen(ch + 1);
for (i = 0; i <= n + 1; i++) {
if (ch[i] == '(') break;
f[i][0] = 1;
}
for (i = n + 1; i >= 1; i--) {
if (ch[i] == ')') break;
g[i]... |
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every... | import java.io.*;
import java.util.*;
public class Main{
static int mod = (int)(Math.pow(10, 9) + 7);
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
int k = sc.nextInt();
if ... |
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!
More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw... | for _ in range(int(input())):
n, x = map(int, input().split())
a = list(map(int, input().split()))
ans = 10**18
for i in range(n):
cnt = x // a[i]
if x % a[i]:
cnt += 1 if cnt else 2
ans = min(ans, cnt)
print(ans)
|
The sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.
Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.
Now Dreamoon concatenates these two permutations into another sequence a of length... |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static long sx = 0, sy = 0, mod = (long) (1e9 + 7);
static ArrayList<Integer>[] a;
static long[][][] dp;
static int[] size;
static long[] farr;
public static PrintWriter out;
static ArrayList<pair> pa = new ArrayList<>();
... |
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, …, s_n.
Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).
Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} ... | import sys
import math
t=int(sys.stdin.readline())
for _ in range(t):
n=int(sys.stdin.readline())
arr=list(map(int,sys.stdin.readline().split()))
dp=[1 for x in range(n+1)]
for i in range(n-1,0,-1):
j=i*2
cnt=2
cur=1
while j<=n:
y=dp[j]
if arr[j-1... |
Naman has two binary strings s and t of length n (a binary string is a string which only consists of the characters "0" and "1"). He wants to convert s into t using the following operation as few times as possible.
In one operation, he can choose any subsequence of s and rotate it clockwise once.
For example, if s = ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 7;
string s[2];
int a[maxn];
int n;
int main() {
cin >> n;
cin >> s[0] >> s[1];
for (int i = 1; i <= n; ++i) {
a[i] = a[i - 1];
if (s[0][i - 1] == '1' && s[1][i - 1] == '0') a[i]++;
if (s[0][i - 1] == '0' && s[1][i - 1] == '1') a[i]-... |
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal.
The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si... | import java.io.*;
import java.util.*;
public class RainbowDashFlutterflyAndChessColoring {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
... |
You are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n.
You have to process q queries of two types:
* 1 v — among all vertices reachable from the vertex v using... | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
using LD = long double;
using PII = pair<int, int>;
using PLL = pair<LL, LL>;
using PLD = pair<LD, LD>;
using VI = vector<int>;
using VLL = vector<LL>;
using VLD = vector<LD>;
using VPII = vector<PII>;
using VPLL = vector<PLL>;
using VPLD = vector<PLD>... |
In the Land of Fire there are n villages and n-1 bidirectional road, and there is a path between any pair of villages by roads. There are only two types of roads: stone ones and sand ones. Since the Land of Fire is constantly renovating, every morning workers choose a single road and flip its type (so it becomes a ston... | #include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
string print_iterable(T1 begin_iter, T2 end_iter, int counter) {
bool done_something = false;
stringstream res;
res << "[";
for (; begin_iter != end_iter and counter; ++begin_iter) {
done_something = true;
counter--;
r... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meet... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public ... |
You are given a matrix a consisting of positive integers. It has n rows and m columns.
Construct a matrix b consisting of positive integers. It should have the same size as a, and the following conditions should be met:
* 1 ≤ b_{i,j} ≤ 10^6;
* b_{i,j} is a multiple of a_{i,j};
* the absolute value of the dif... | #include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
#define PI acos(-1)
#define pb push_back
#define F first
#define S second
#define lson i << 1
#define rson i << 1 | 1
#define mem(x, y) memset(x, y, sizeof(x))
#define fin(x) freopen(x, "r", stdin)
#define fout(x) freope... |
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to ... | import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] argv) {
new Main().run();
}
void run() {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
try {
solve();
} finally {
out.close();
}
}
PrintWriter out;
Scanner in;
int m... |
Suppose you are given two strings a and b. You can apply the following operation any number of times: choose any contiguous substring of a or b, and sort the characters in it in non-descending order. Let f(a, b) the minimum number of operations you have to apply in order to make them equal (or f(a, b) = 1337 if it is i... | #include <bits/stdc++.h>
const int B=200;
typedef long long ll;
using namespace std;
int T,n,m,l;
map<string,vector<string> >V;
map<string,bool>vis;
string s,t;
int main(){
ios_base::sync_with_stdio(0), cin.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>s;t=s;
sort(t.begin(),t.end());
V[t].push_back(s);
}
l=s.s... |
Vasya has recently bought some land and decided to surround it with a wooden fence.
He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal n different types of wood. The company uses the i-th type of wood to produce ... |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class E {
public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));
String[] i... |
The Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.
To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scie... | #include <bits/stdc++.h>
using namespace std;
int *pa = new int[200005];
int *na = new int[200005];
int *p1 = new int[200005];
int *p2 = new int[200005];
int main() {
int m1 = 1, m2 = 1, c1, c2, fs[5005], ls[5005], n, k[5005], x[5005], y[5005],
m[5005], i, j;
long long all = 0, q, nn, xx, yy, ans = 0;
cin >... |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int n = sc.nextInt();
int[] reqS = new int[n];
int[] gainS = new int[n];
int ctr = 1;
for(int i = 0; i < n; i++)
{
reqS[i] = sc.nextInt();
gainS[i] =... |
Furlo and Rublo play a game. The table has n piles of coins lying on it, the i-th pile has ai coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to:
* choose some pile, let's denote the current number of coins in it as x;
* choose some integer y (0 ≤ y < x; x1 / 4 ≤ y ≤ x1 / 2) a... | #include <bits/stdc++.h>
using namespace std;
int get_nim(long long x) {
if (x < 4) return 0;
if (x < 16) return 1;
if (x < 82) return 2;
if (x < 6724) return 0;
if (x < 50626) return 3;
if (x < 2562991876LL) return 1;
return 2;
}
int main() {
int n, ans = 0;
long long a;
cin >> n;
for (int i = 0;... |
Valera considers a number beautiful, if it equals 2k or -2k for some integer k (k ≥ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible.
Help Valera and find, how many nu... | x = 0
y = 1
for c in raw_input():
if c == '0':
x, y = min(x, y + 1), min(x, y) + 1
else:
x, y = min(x, y) + 1, min(x + 1, y)
print min(x, y + 1) |
Yaroslav has an array p = p1, p2, ..., pn (1 ≤ pi ≤ n), consisting of n distinct integers. Also, he has m queries:
* Query number i is represented as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The answer to the query li, ri is the number of pairs of integers q, w (li ≤ q, w ≤ ri) such that pq is the divisor o... | #include <bits/stdc++.h>
using namespace std;
const int N = 201000;
int n, a[N], pos[N], l[N], r[N], C[N], idx[N], ans[N];
vector<int> nu[N];
void bitModify(int p) {
for (int i = p; i > 0; i -= i & -i) C[i]++;
}
int bitQuery(int p) {
int ret = 0;
for (int i = p; i <= n; i += i & -i) ret += C[i];
return ret;
}
b... |
Do you remember how Kai constructed the word "eternity" using pieces of ice as components?
Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to u... | t, s = [raw_input().replace('6', '9').replace('2', '5') for i in range(2)]
print min([s.count(i)/t.count(i) for i in t]) |
«Bersoft» company is working on a new version of its most popular text editor — Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).
Your task is to w... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
set<int> s;
string t, k;
cin >> t;
int jj;
for (int i = 0; i < t.length(); i++) {
if (t[i] != ',') {
k += t[i];
} else {
jj = ... |
There is an n × m rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the i-th row and the j-th column as (i, j).
Let's define a "rectangle" as four integers a, b, c, d (1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m). Rectangle denotes a set of cells of the grid {(x, y) : a ≤ x ≤ c, b... | #include <bits/stdc++.h>
using namespace std;
bool a[41][41];
long long d[41][41][41][41];
long long cld[41][41][41][41];
int cldh[41][41][41][41];
int lines_x[41][41];
int lines_y[41][41];
void print(int w, int e, int n, int m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
printf("%d ", d[w... |
You are given an integer m as a product of integers a1, a2, ... an <image>. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers.
Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, ... | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class cf397c {
static FastIO in = new FastIO(), out = in;
static ArrayList<Integer> primes;
static long MOD = (long)1e9 + 7;
static int MAX = (int)Math.sqrt(1e9) + 10;
static long[] facts = new long[50000];
static long[] invFacts =... |
A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his n friends that they will solve the problems for him.
The participants are offered m problems on the contest. For each friend, Gena knows what pr... | #include <bits/stdc++.h>
using namespace std;
const int MOD = 1000 * 1000 * 1000 + 7;
const long long INF = 2000 * 1000 * 1000 * 1ll * 2000 * 1000 * 1000;
const double EPS = 1e-9;
const double pi = acos(-1.0);
const int maxn = 110;
template <typename T>
inline T sqr(T n) {
return (n * n);
}
struct item {
int x, k, ... |
DZY loves planting, and he enjoys solving tree problems.
DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every... | #include <bits/stdc++.h>
using namespace std;
struct Edge {
int a, b, c;
bool operator<(const Edge &r) const { return c < r.c; }
};
int N, x[3000], bl[3000];
vector<pair<int, int> > edges[3000];
Edge e[3000];
pair<int, int> dfs(int n, int p) {
if (bl[n]) return pair<int, int>(0, 0);
pair<int, int> ret = pair<in... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | c = 0
for _ in range(int(input())):
n = [int(x) for x in input().split()]
n,m = n[0],n[1]
if m - n >= 2:
c += 1
print(c)
|
A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, (1), (4, 3, 5, 1, 2), (3, 2, 1) are permutations, and (1, 1), (4, 3, 1), (2, 3, 4) are not.
There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took... | #include <bits/stdc++.h>
using namespace std;
int a[100001], p[100001];
int main() {
int n, i, Max = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", a + i);
p[a[i]]++;
Max = max(Max, a[i]);
}
for (i = 1; i < Max; i++)
if (p[i] < p[i + 1]) {
printf("-1");
return 0;
}
... |
Cthulhu decided to catch Scaygerboss. Scaygerboss found it out and is trying to hide in a pack of his scaygers. Each scayger except Scaygerboss is either a male or a female. Scaygerboss's gender is "other".
Scaygers are scattered on a two-dimensional map divided into cells. A scayger looks nerdy and loveable if it is ... | #include <bits/stdc++.h>
using namespace std;
template <class P, class Q>
inline void smin(P &a, Q b) {
if (b < a) a = b;
}
template <class P, class Q>
inline void smax(P &a, Q b) {
if (a < b) a = b;
}
const long long inf = 1LL << 20;
const int maxn = 22 + 2;
int n, m, males, females;
int N;
char s[maxn][maxn];
lon... |
One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height / width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2x for some int... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long i, j, h, w, tmp_h, tmp_w;
cin >> h >> w;
for (i = 0;; i++) {
if ((long long)(1 << i) > h || (long long)(1 << i) > (5 * w) / 4) {
i--;
break;
}
}
for (j = 0;; j++) {
if ((long long)(1 << j) > w || (long long)(1 << j) >... |
Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table).
At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util... |
Duff is one if the heads of Mafia in her country, Andarz Gu. Andarz Gu has n cities (numbered from 1 to n) connected by m bidirectional roads (numbered by 1 to m).
Each road has a destructing time, and a color. i-th road connects cities vi and ui and its color is ci and its destructing time is ti.
Mafia wants to dest... | #include <bits/stdc++.h>
using namespace std;
const int MAX_BUF_SIZE = 16384;
char BUFOR[MAX_BUF_SIZE];
int BUF_SIZE, BUF_POS;
char ZZZ;
const int MXN = 6 * 50010;
const int C = 262144;
const int INF = 1000000001;
namespace SAT2 {
vector<int> G[MXN], GT[MXN], H[MXN], vert[MXN];
int pre[MXN], skl[MXN];
vector<int> fu;
c... |
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vec... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
... |
Vasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face.
One of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget — a rotating camera — come up to it to see it be... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long int deg;
cin >> deg;
deg %= 360;
long long int ans[4];
ans[0] = deg;
for (int i = 1; i < 4; i++) ans[i] = ((ans[i - 1] - 90)) % 360;
for (int i = 0; i < 4; i++) ans[i] = abs(ans[i]);
for (int i = 0; i < 4; i++)
if (ans[i] > 180) an... |
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.
The President of Berland decided to make changes to the road sy... | #include <bits/stdc++.h>
using namespace std;
int N, M;
bool group[100001];
bool trip[100001];
vector<int> Map[100001];
bool flag;
void search(int v, int par) {
group[v] = true;
trip[v] = true;
for (int i = 0; i < Map[v].size(); i++) {
int now = Map[v][i];
if (now == par) continue;
if (trip[now]) flag... |
Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not ... | import java.util.Scanner;
import java.util.Vector;
public class probBCon358 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Vector<Integer> vec = new Vector<Integer>();
for (int i = 0; i < n; i++){
vec.add(sc.nextInt());
... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | x = int(input())
feelings = ''
for _ in range(x):
if _ == x - 1:
if _ % 2 != 0:
feelings = feelings + 'I love it '
else:
feelings = feelings + 'I hate it '
else:
if _ % 2 != 0:
feelings = feelings + 'I love that '
else:
feelings = feelings + 'I hate that '
print(feelings)
|
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this si... | #include <bits/stdc++.h>
inline int F() {
register int aa, bb, ch;
while (ch = getchar(), (ch < '0' || ch > '9') && ch != '-')
;
ch == '-' ? aa = bb = 0 : (aa = ch - '0', bb = 1);
while (ch = getchar(), ch >= '0' && ch <= '9') aa = aa * 10 + ch - '0';
return bb ? aa : -aa;
}
int a[7], b[7], d[7], c[100010... |
Santa Claus has n tangerines, and the i-th of them consists of exactly ai slices. Santa Claus came to a school which has k pupils. Santa decided to treat them with tangerines.
However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so t... | #include <bits/stdc++.h>
using namespace std;
int arr[int(1e7 + 100)];
void aum(int i) {
if (i % 2) {
arr[i / 2 + 1] += arr[i];
arr[i / 2] += arr[i];
} else
arr[i / 2] += 2 * arr[i];
}
int main() {
ios_base::sync_with_stdio(0);
set<int> conj;
memset(arr, 0, sizeof arr);
int n, m, l, ans = int(2 ... |
Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible.
Limak has a string s t... | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Hard {
static List<Integer> listIndexesK = new ArrayList<>();
static List<Integer> listIndexesV = new ArrayList<>();
static List<Integer> listIndexesOther = new ArrayList<>();
static int[][][][] variablePosition ... |
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own.
Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be pos... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rene
*/
pu... |
On the way home, Karen decided to stop by the supermarket to buy some groceries.
<image>
She needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to b dollars.
The supermarket sells n goods. The i-th good can be bought for ci dollars. Of course, ea... | #include <bits/stdc++.h>
using namespace std;
void fre() {
freopen("c://test//input.in", "r", stdin);
freopen("c://test//output.out", "w", stdout);
}
template <class T1, class T2>
inline void gmax(T1 &a, T2 b) {
if (b > a) a = b;
}
template <class T1, class T2>
inline void gmin(T1 &a, T2 b) {
if (b < a) a = b;
... |
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.
Input
First line of input data contains single integer n (1 ... | #include <bits/stdc++.h>
using namespace std;
const int MX_N = 305;
const int MOD = 1e9 + 7;
int N, A[MX_N];
int F[MX_N], fcnt, C[MX_N];
int nck[MX_N][MX_N], fac[MX_N], dp[MX_N][MX_N];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N;
for (int i = (1); i <= (N); ++i) {
cin >> A[i];
for (in... |
Mahmoud and Ehab solved Dr. Evil's questions so he gave them the password of the door of the evil land. When they tried to open the door using it, the door gave them a final question to solve before they leave (yes, the door is digital, Dr. Evil is modern). If they don't solve it, all the work will be useless and they ... | #include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXLEN = 100000;
const int MAXN = 100000;
const int MAXQ = 100000;
const int MAXTN = MAXLEN + 1;
const int MAXLG = 16;
const int MAXSN = 4 * (MAXN - 1);
const int MAXZN = 4 * MAXN;
type... |
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.
Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≤ i ≤ n) such that pi = i.
Your task is to count the number of almost identity permutations for given numbers... | import math
nk=input().split()
n=int(nk[0])
k=int(nk[1])
L=[0]*5
L[1]=1
L[2]=(n*(n-1))//2
L[3]=(n*(n-1)*(n-2))//3
L[4]=(3*n*(n-1)*(n-2)*(n-3))//8
s=0
for i in range(0,k+1):
s+=L[i]
print(s)
|
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one — into b pieces.
Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plat... |
import java.util.Scanner;
public class a {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int a=scan.nextInt();
int b=scan.nextInt();
//i+j==n
int min=Integer.MIN_VALUE;
for(int i=1;i<=n-1;i++)
{
//distribute a dishen on i playes and distrib... |
Given a string s, find the number of ways to split s to substrings such that if there are k substrings (p1, p2, p3, ..., pk) in partition, then pi = pk - i + 1 for all i (1 ≤ i ≤ k) and k is even.
Since the number of ways can be large, print it modulo 109 + 7.
Input
The only line of input contains a string s (2 ≤ |s... | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
public class EerTree {
int s, cur; // total of suffix-palindrome nodes, index of current suffix-palindrome
int N; // final string size, for initiation
int n; // c... |
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo... | #include <bits/stdc++.h>
using namespace std;
string func(int c4, int c7) {
string res;
while (c4--) res += '4';
while (c7--) res += '7';
return res;
}
int main() {
string s;
while (cin >> s) {
int n = s.size();
if (n % 2 == 1) {
cout << string((n + 1) / 2, '4') << string((n + 1) / 2, '7') << ... |
Surely you have seen insane videos by South Korean rapper PSY, such as "Gangnam Style", "Gentleman" and "Daddy". You might also hear that PSY has been recording video "Oppa Funcan Style" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find origina... | #include <bits/stdc++.h>
using namespace std;
const int MX = 32000000;
const long long INF = 1E18 + 7;
vector<int> pr;
map<long long, vector<long long>> fct, dst;
int t;
long long n, k;
bool chk[MX];
struct SNode {
long long u, val;
};
inline bool operator<(const SNode &a, const SNode &b) { return a.val < b.val; }
pr... |
This is the time of Akbar and Birbal. One day , in the state there happened some riots and murders .Akbar found some N people guilty in this matter.He called Birbal to punish them .Birbal gave them a unique punishment .He ordered the first person(guilty) to dig all the N spaces indicated on the ground.Then he called th... | import math
for _ in xrange(input()):
n = input()
print (n - int(math.sqrt(n))) |
There are N routers. The cost of the wires required in connecting two routers, i and j, is R[i]+R[j] where R[i] is the number of slots in the i-th router and i!=j. You need to build a network, such that there is a path between every pair of routers. Find the minimum cost of building such a network.The connection betwee... | t=input()
while t>0:
n=input()
arr=[]
arr=map(int,raw_input().split())
brr=sorted(arr)
l=len(brr)
su=0
for i in range(1,l):
a=brr[0]+brr[i]
su=su+a
print su
t=t-1 |
Dr.Dawood is another mathematician who is more geekier than Osama (that's why, ++). Dawood deals with more complex problems than Osama usually deals with. He also recruits people to be his sub-ordinates. He usually gives them "trivial" problems as test for them to solve and earn their position to be his sub-ordinate.
... | for i in range(0,int(input())):
f =0
ans = 0
x = int(input())
while x%2 == 0:
f = f+1
x= x/2
ans = pow(2,(f+1))
print(ans) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.