input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
One quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in ... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(... |
In a far away kingdom lives a very greedy king. To defend his land, he built n guard towers. Apart from the towers the kingdom has two armies, each headed by a tyrannical and narcissistic general. The generals can't stand each other, specifically, they will never let soldiers of two armies be present in one tower.
Dur... | #include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
int sx = mod, sy = mod, bx, by;
int cnt, n;
int vis[5001], cost[5001][5001], x[5001], y[5001];
bool dfs(int v, int c, int mid) {
if (vis[v] && c != vis[v]) return 0;
if (vis[v]) return 1;
vis[v] = c;
for (int i = 1; i <= n; i++)
if (c... |
One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Des... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10, mod = 1e9 + 7;
int n, k, f[N], sum[N], fac[N], ifac[N];
int power(int a, int b) {
int ret = 1;
while (b) {
if (b & 1) ret = 1ll * ret * a % mod;
a = 1ll * a * a % mod;
b >>= 1;
}
return ret;
}
int main() {
scanf("%d%d", &n, &k);... |
You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depen... | #include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
int ni() {
int val;
scanf("%i", &val);
return val;
}
pair<int, int> npi() {
pair<int, int> val;
scanf("%i %i", &... |
The last stage of Football World Cup is played using the play-off system.
There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the four... | import java.util.*;
import java.io.*;
import java.math.*;
public class codeforces
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
ArrayList<Integer> hs=new ArrayLis... |
Now that Heidi knows that she can assign Rebel spaceships to bases (recall the easy subtask), she is asking you: how exactly to do this? Now, given positions of N spaceships and N bases on a plane, your task is to connect spaceships and bases with line segments so that:
* The segments do not intersect.
* Such a ... | #include <bits/stdc++.h>
using namespace std;
int main() {
srand(time(NULL));
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, x, y;
cin >> n;
vector<tuple<int, int, int> > A(n << 1);
vector<int> ans(n);
function<void(int, int)> solve = [&](int l, int r) {
if (l == r) return;
auto line = [&]... |
You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.
Initially all m lamps are t... | def main():
n,m=map(int,input().split())
counts=[0]*m
a=[None]*n
for i in range(n):
line=input()
a[i]=line
for j in range(m):
counts[j]+=1 if line[j]=='1' else 0
if 1 not in counts:
print('YES')
return
checks=[]
for i in range(m):
if counts[i]==1:
checks.append(i)
leng=len(checks)
for i in r... |
Given an integer N,Find how many strings of length N are possible, consisting only of characters { 'A','B' and 'C' } with each character {'A','B' and 'C'} occurs at least once.
Input:
First line of each test case contains number of test cases T. Each test case contains a single integer N.
Output:
For each test ... | MOD=10**9+7
def power(base,pow):
ans=1
while (pow!=0):
if(pow%2==1):
ans=(ans*base)%MOD
base=(base*base)%MOD
pow=pow/2
return ans
if __name__ =="__main__":
t=int(raw_input())
for i in range(t):
n=int(raw_input())
if(n<3):
print 0
else:
print (3*(power(3,n-1) -power(2,n) +1 ))%MOD |
Given an array A of N integers, sort them in non-decreasing order.
Input Format
The first line of the input file contains a positive integer <N.
Then, N lines follow, each containing a single integer Ai, which is the i^th element of A.
Output Format
The output must contain exactly N lines, each line containing a sin... | N = input()
A = []
for i in xrange(N):
A.append(int(raw_input()))
A.sort()
for a in A:
print a |
People in Cubeland use cubic coins. Not only the unit of currency is called a cube but also the coins are shaped like cubes and their values are cubes. Coins with values of all cubic numbers up to 9261 (= 213), i.e., coins with the denominations of 1, 8, 27, ..., up to 9261 cubes, are available in Cubeland.
Your task i... | a=[]
for i in xrange(1,22):
a.append(i**3)
ans=[0]*10001
ans[0]=1
for j in a:
for i in xrange(j,10001):
ans[i]+=ans[i-j]
for _ in xrange(input()):
print ans[input()] |
Problem Statement
Unseen gang is the team of most wanted criminal. Unseen gang has planted bombs in different street and corner of the city. Gang members are sitting in the other part of the city, far away from the bomb site. They are controlling the bomb by sending the activation signal in the form of encrypted code.... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
s = raw_input()
n=int(raw_input())
j =0
temp =""
for i in s:
if j==n:
print temp
temp=""
j=0
temp+=i
j = j+1
if temp!="":
print temp |
Call a number stepping if adjacent digits, as well as the first and last digits, differ by one. How many n-digit base 11 stepping numbers are there? Give your answer modulo 4294967143.
For example, 8789A9 is a 6-digit base 11 stepping number. 9A0A and 234 are not stepping.
Input
The first line contains an integer T,... | noc = input()
series = []
while noc:
noc -=1
series.append(input())
print "19"
print "54"
print "171"
print "1958" |
You are given an array containing 2 \times n elements.You have to partition the numbers in to n pairs with the property that partition minimize the maximum sum of a pair.
Input
First line contains T number of test cases. Next line contain N number of pairs.
Next line contain 2*N positive integers represent elemen... | t=input()
for i in xrange(t):
n=input()
arr=[]
arr=map(int,raw_input().split())
arr.sort()
l=len(arr)
m=l
arr2=[]
for k in xrange(l/2):
su=arr[k]+arr[m-1]
arr2.append(su)
m-=1
print max(arr2) |
The events have started and one of them is Void fnx, the most anticipated Coding Event of the college. This year, one question has been bugging the coders for hours, Help them solve it. It goes as follows:
The palindromic number 595 can be written as the sum of consecutive squares: from 6 to 12.
Find the sum of all t... | import math
def ispalin(x):
o=[]
while x:
o.append(x%10)
x/=10
r=reversed(o)
for i,j in zip(o,r):
if i!=j:
return False
return True
s,b=raw_input().split()
s,b=(int)(s),(int)(b)
sq=(int)(math.sqrt(b))
a=[]
for i in range(1,10001):
num=i*i
for j in ran... |
Dark was deeply studying in the afternoon and came across a concept called as "REVERSE OF A NUMBER"
Hearing first time he became eager to learn and searched on "INTERNET" , after his research on reverse of a number he decided to design a program which can reverse any long numbers.
At the end of afternoon, he started... | t = int(raw_input())
while(t):
str=raw_input()
str1=str[::-1]
number=int(str1)
if number%2==0:
print "EVEN"
else:
print "ODD"
t-=1 |
Arithmancy is Draco Malfoy's favorite subject, but what spoils it for him is that Hermione Granger is in his class, and she is better than him at it. Prime numbers are of mystical importance in Arithmancy, and Lucky Numbers even more so. Lucky Numbers are those positive integers that have at least three distinct prime... | def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return set(factors)
ans=[0]
for k in xrange(30,2700):
if len(prime_factors(k))>2:
ans.append... |
Let there be a function f(N) such that f(N) denotes number of zeroes at the end of N! (factorial of N).
For example, f(5) = 1 because 5! = 120.
You have to compute f(N) for given N.
Input format : Input begins with integer t ( 1 ≤ t ≤ 10000) denoting number of test cases. Then there are t lines each containing exac... | for _ in range(int(raw_input())):
tz = 0
n = int(raw_input())
i = 1
r = 1
while r:
r = n / 5 ** i
tz += r
i += 1
print tz |
There is a grid of squares with H+1 horizontal rows and W vertical columns.
You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th ... | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using ll = long long;
using P = pair<ll, int>;
#define INF 1001001001
#define MAX 1000005
int main() {
int h, w;
cin >> h >> w;
map<int,int> sp;
multiset<int> diff;
rep(i,w) sp[i]=i,diff.insert(0);
vect... |
Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if ... | import java.util.*;
class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for(int i=0;i<m;i++){
n -= sc.nextInt();
}
if(n < 0){
System.out.println(-1);
}
... |
Given are three integers A_1, A_2, and A_3.
If A_1+A_2+A_3 is greater than or equal to 22, print `bust`; otherwise, print `win`.
Constraints
* 1 \leq A_i \leq 13 \ \ (i=1,2,3)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A_1 A_2 A_3
Output
If A_1+A_2+A_... | import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
for (int i = 0; i < 3; i++) sum += sc.nextInt();
if (sum >= 22) System.out.println("bust");
else System.out.println("win");
}
}
|
There are N empty boxes arranged in a row from left to right. The integer i is written on the i-th box from the left (1 \leq i \leq N).
For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.
We say a set of choices to put a ball or not in the boxes is good when the following con... | N = int(input())
A = list(map(int, input().split()))
B = [0]*(N+1)
x = []
for n in range(N):
i = N-n
BB = B[::i]
if (sum(BB))%2 == A[i-1]:
B[i] = 0
else:
B[i] = 1
x.append(str(i))
print(len(x))
print(' '.join(x)) |
There are N islands and M bridges.
The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.
Initially, we can travel between any two islands using some of these bridges.
However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to t... | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5+5;
int n, m, fa[MAXN];
struct EDGE
{
int u, v;
}e[MAXN];
long long ans[MAXN], sz[MAXN];
int find(int x)
{
if(x == fa[x])
return x;
return fa[x] = find(fa[x]);
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= m; ++i)
cin >> e[i].u >> e[i... |
Snuke has decided to use a robot to clean his room.
There are N pieces of trash on a number line. The i-th piece from the left is at position x_i. We would like to put all of them in a trash bin at position 0.
For the positions of the pieces of trash, 0 < x_1 < x_2 < ... < x_{N} \leq 10^{9} holds.
The robot is initi... | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=1e16;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int N; ll X; cin >> N >> X;
vector<ll> sum(N+1,0);
for (int i=N;i>0;--i) cin >> sum[i];
for (int i=0;i<N;++i) sum[i+1]+=sum[i];
ll ans=INF;
for (in... |
Takahashi has N blue cards and M red cards. A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.
Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will ea... | from collections import*
n,*a=open(0).read().split()
blue=a[0:int(n)]
red=a[int(n)+1:]
print(max(0,max(v-Counter(red)[k] for k,v in Counter(blue).items()))) |
We constructed a rectangular parallelepiped of dimensions A \times B \times C built of ABC cubic blocks of side 1. Then, we placed the parallelepiped in xyz-space as follows:
* For every triple i, j, k (0 \leq i < A, 0 \leq j < B, 0 \leq k < C), there exists a block that has a diagonal connecting the points (i, j, k) ... | #include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
ll mod = 1000000007;
ll get(ll lx, ll ly, ll ux, ll uy, ll a, ll b)
{
vector<ll>x, y;
x.push_back(lx), x.push_back(ux + 1), x.push_back(0), x.push_back(a);
y.push_back(ly), y.push_back(uy + 1), y.push_back(0), y.push_ba... |
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 vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi:
* Select a vertex... | #include<bits/stdc++.h>
#define N 200005
using namespace std;
vector<int> G[N];
int n,d[N];
void GG(){ printf("First"); exit(0);}
int dfs(int t,int fa)
{
int i,cnt=0;
for(i=0;i<G[t].size();i++)
if(G[t][i]!=fa)
cnt+=dfs(G[t][i],t);
if(cnt>=2) GG();
if(cnt==1) return 0;
else return 1;
}
int main()
{
int i,x,y;... |
Kode Festival is an anual contest where the hardest stone in the world is determined. (Kode is a Japanese word for "hardness".)
This year, 2^N stones participated. The hardness of the i-th stone is A_i.
In the contest, stones are thrown at each other in a knockout tournament.
When two stones with hardness X and Y ar... | def main():
N = int(input())
A = []
for _ in range(pow(2, N)): A.append(int(input()))
# print(A)
while len(A) > 1:
temp = []
for i in range(len(A)//2):
if A[2*i] < A[2*i+1]: temp.append(A[2*i+1] - A[2*i])
elif A[2*i] > A[2*i+1]: temp.append(A[2*i] - A[2*i+1]... |
Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K.
You are given an undirected tree with N verti... | import sys
input = sys.stdin.readline
n,k = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
ans = n
rad = k//2
for center in range(1,n+1):
stack = [center]
dep = [[-1,-1] for _ in range(n+1)]... |
<image>
At the request of a friend who started learning abacus, you decided to create a program to display the abacus beads. Create a program that takes a certain number as input and outputs a row of abacus beads. However, the number of digits of the abacus to be displayed is 5 digits, and the arrangement of beads fr... | f=0
while 1:
try:n=int(input())
except:break
if f:print()
f=1
a=[['*' for _ in range(5)]for _ in range(8)]
for i in range(4,-1,-1):
b=n%10
a[not b//5][i]=' '
a[b%5+3][i]=' '
n//=10
a[2]='='*5
for i in a:
print(''.join(i),end='')
print() |
Aka Beko, trying to escape from 40 bandits, got lost in the city of A. Aka Beko wants to go to City B, where the new hideout is, but the map has been stolen by a bandit.
Kobborg, one of the thieves, sympathized with Aka Beko and felt sorry for him. So I secretly told Aka Beko, "I want to help you go to City B, but I w... | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <ctime>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <functional>
#include <fstream>
#include... |
problem
At IOI Confectionery, rice crackers are baked using the traditional method since the company was founded. This traditional method is to bake the front side for a certain period of time with charcoal, turn it over when the front side is baked, and bake the back side for a certain period of time with charcoal. W... | #include <bits/stdc++.h>
using namespace std;
#define Rep(i, N) for(int i = 0; i < N; i++)
int main()
{
int H, W;
int mas[15][10005];
while(cin >> H >> W, W || H) {
Rep(i, H) Rep(j, W) cin >> mas[i][j];
int maxv = 0;
Rep(i, 1 << H) {
int cnt = 0;
Rep(j, W) {
int cnts = 0;
Rep(k, H) {... |
She catched the thrown coin that draws parabolic curve with her sparkling fingers. She is an ESPer. Yes, she is an electro-master who has the third strongest power among more than one million ESPers in the city. Being flicked by her thumb, the coin is accelerated by electromagnetic force and is shot as Fleming's right-... | #include<iostream>
#include<cmath>
#include<cstdio>
#include<complex>
using namespace std;
typedef complex<double> Point;
#define EPS (1e-10)
#define EQ(a,b) (abs((a)-(b)) < EPS)
#define EQV(a,b) ( EQ( (a).real() , (b).real() ) && EQ( (a).imag(), (b).imag() ) )
double abs(Point a,Point b) {
return sqrt( (a.real()-... |
A mobile phone company ACMICPC (Advanced Cellular, Mobile, and Internet-Connected Phone Corporation) is planning to set up a collection of antennas for mobile phones in a city called Maxnorm. The company ACMICPC has several collections for locations of antennas as their candidate plans, and now they want to know which ... | # AOJ 1202: Mobile Phone Coverage
# Python3 2018.7.28
from bisect import bisect_left
cno = 0
while True:
n = int(input())
if n == 0: break
tbl, xx, yy = [], set(), set()
for i in range(n):
x, y, r = map(float, input().split())
x, y, r = int(100*x), int(100*y), int(100*r)
x1, y1, x2, y2 = x-r, y-r, x+r, y+r
... |
A straight tunnel without branches is crowded with busy ants coming and going. Some ants walk left to right and others right to left. All ants walk at a constant speed of 1 cm/s. When two ants meet, they try to pass each other. However, some sections of the tunnel are narrow and two ants cannot pass each other. When tw... | #include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
const ll INF = (ll)1000000... |
Problem
Given a natural number N less than or equal to 12, find the smallest natural number such that the number of divisors is exactly N.
Constraints
* 1 ≤ N ≤ 12
Input
One natural number N is given in one line.
Output
Output the smallest natural number on a line so that the number of divisors is exactly N.
Ex... | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
int n;
cin >> n;
int answer = 0;
for(int i = 1; answer == 0; ++i){
int c = 0;
for(int j = 1; j * j <= i; ++j){
if(i % j == 0){
++c;
if(j * j != i){ ++c; }... |
You are given N non-overlapping circles in xy-plane. The radius of each circle varies, but the radius of the largest circle is not double longer than that of the smallest.
<image>
Figure 1: The Sample Input
The distance between two circles C1 and C2 is given by the usual formula
<image>
where (xi, yi ) is the coor... | import java.util.Arrays;
import java.util.Random;
//The Closest Circle
public class Main{
class Scanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-') return -nextInt();
int res = 0;
do {
res *= 10;
... |
Problem D: Mr. Rito Post Office
You are a programmer working at a post office on a remote island. The area you live in consists of multiple islands. There is one or more port towns on each island. There may be other towns and villages in addition to them. You have to use a boat to go from one island to another. You ca... | #include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <functional>
#include <set>
#include <queue>
#include <cctype>
#include <climits>
#include <stack>
using namespace std;
int n,m,r;
const int INF=1e7;
int d[2][20... |
Time Limit: 8 sec / Memory Limit: 64 MB
Example
Input
2
0 0 5 0 10
1 0 6 0 10
1
0.000000 0.000000
6.000000 0.000000
Output
2 | #include <iostream>
#include <iomanip>
#include <complex>
#include <vector>
#include <algorithm>
#include <cmath>
#include <array>
#include <map>
using namespace std;
const int inf = 1e9;
const double EPS = 1e-6;
const double INF = 1e12;
const double PI = acos(-1);
#define EQ(n,m) (abs((n)-(m)) < EPS)
#define X real()
... |
Problem Statement
Texas hold 'em is one of the standard poker games, originated in Texas, United States. It is played with a standard deck of 52 cards, which has 4 suits (spades, hearts, diamonds and clubs) and 13 ranks (A, K, Q, J and 10-2), without jokers.
With betting aside, a game goes as described below.
At the... | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int,... |
Example
Input
2 2 3
0 0
2 0
0 0
0 2
0 0
1 1
1 1
Output
3 | #include <bits/stdc++.h>
using namespace std;
using lld = int64_t;
using I128 = __int128;
typedef long long ll;
using pII = pair<I128,I128>;
using pll = pair<ll,ll>;
typedef pair<int,int> pii;
typedef pair<double,double> pdd;
typedef complex<double> cplex;
const double pi=acos(-1);
const int INF = 500000;
const int N =... |
problem
AOR Co., Ltd. (Association Of Return home) has $ N $ employees.
Employee $ i $ wants to use the elevator to go down to the $ 1 $ floor and arrives in front of the elevator on the $ F_i $ floor at time $ t_i $. You decide to remotely control an elevator that has only $ 1 $ on the $ 1 $ floor at time $ 0 $ and ... | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)(1e17)
#define MAX 110000
int N, D;
int t[MAX], F[MAX];
signed main(){
int num = 0, ans = 0;
cin>>N>>D;
for(int i = 0; i < N; i++){
cin>>t[i]>>F[i];
}
t[N] = INF;
F[N] = 1;
if(t[0] < F[0]-1){
cout<<-1<<endl;... |
Problem Statement
One day (call it day 0), you find a permutation $P$ of $N$ integers written on the blackboard in a single row. Fortunately you have another permutation $Q$ of $N$ integers, so you decide to play with these permutations.
Every morning of the day 1,2,3,... , you rewrite every number on the blackboard ... | #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdio>
#include <complex>
#include <numeric>
#include <string.h>
#include <random>
#define rep(i,n) for (int i = 0; i < (int)n; i++)
using namespace std;
typedef long long ll;
typedef u... |
Problem statement
When you heard that this year's KUPC can be joined as a team, you decided to talk to your friends and join as a team.
Eventually, $ 4 $ people, including you, got together.
Individual strength is expressed in ratings, and $ 4 $ person ratings are $ a $, $ b $, $ c $, and $ d $, respectively.
You d... | #include "bits/stdc++.h"
using namespace std;
int main() {
int A, B, C, D;
cin >> A >> B >> C >> D;
cout << min(min(abs(A + B - C - D), abs(A + C - B - D)), abs(A + D - B - C)) << endl;
}
|
Find articulation points of a given undirected graph G(V, E).
A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|... | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
static const int MAX = 100000;
#define ROOT 0
vector<int> G[MAX];
bool visited[MAX];
int prenum[MAX];
int lowest[MAX];
int parents[MAX];
bool is_artpoint[MAX];
int NCHILD_ROOT = 0;
void visit(int n, int parent) {
static int v = 0;
vis... |
Doge and Cate can no longer coexist in the same planet. Time has finally come to decide once and for all, who will reign over this planet.
They agreed on a non violent way to settle this. Both are given an array of N integers and a positive integer K. In a single operation, one can change an element of the array to any... | T=int(raw_input());
for t in range(T) :
l=raw_input().split();
N=int(l[0]);
K=int(l[1]);
l=raw_input().split();
A=[int(i) for i in l];
countdict={};
for i in A :
if i in countdict :
countdict[i]=countdict[i]+1;
else :
countdict[i]=1;
mindiff=N+1;
for key in countdict :
if K>countdict[key]:
diff=... |
In Byteland they have a very strange monetary system.
Each Bytelandian gold coin has an integer number written on it. A coin n
can be exchanged in a bank into three coins: n/2, n/3 and n/4.
But these numbers are all rounded down (the banks have to make a profit).
You can also sell Bytelandian coins for American doll... | def solve(coin2):
d = {0:0}
def exchange(coin):
if coin in d:
return d[coin]
else:
d[coin] = max(coin, exchange(coin/2) + exchange(coin/3) + exchange(coin/4))
return d[coin]
return exchange(coin2)
def coins():
import sys
for coin in sys.stdin:
... |
WARNING Large input/output files. Use faster I/O.
It's Galactik Football time! The Galactik Football Assosiation (GFA) has announced a football tournament between all the teams of all the planets in the galaxy (say N). Teams like Snow Kids, Shadows, Xenons, Red Tigers, Wambas, Pirates, etc. are in total enthusiasm and ... | #! /usr/bin/python
import sys
max_val = sys.maxint
inp = sys.stdin.readline().split()
N, M = int(inp[0]), int(inp[1])
g = range(N+1) # group of i'th point which is equal to least point index in the group;
# all points connected to each other are in a same group
for i in xrange(M):
inp = sys.s... |
The Little Elephant loves lucky strings. Everybody knows that the lucky string is a string of digits that contains only the lucky digits 4 and 7. For example, strings "47", "744", "4" are lucky while "5", "17", "467" are not.
The Little Elephant has the strings A and B of digits. These strings are of equal lengths, t... | import sys, os
import unittest
def getToTarget(target, values, priorities):
returnTarget = 0
returnValues = values
for p in priorities:
x = values[p]
toTarget = target-returnTarget
add = min(x,toTarget)
returnValues[p] = x-add
returnTarget += add
return return... |
Mo the pro does not want to be late for the promo of Incident'14, the annual cultural fest of NITK. In his excitement, he drops his only 2 wrist watches. He sets his watches according to a wall clock. After some time N he discovers that one of the watch is X minutes fast, and the other watch is Y minutes slow. What ... | tc = int(raw_input())
while (tc>0):
tc = tc - 1
a, b, c = map(int, raw_input().split())
print a*720/(b+c) |
In this problem, you are given two strings S1 and S2, your task is to determine whether one string is an anagram of the other. An anagram of a string is a string obtained by permuting the letters of a string. For example aaba and aaab are anagrams, while abcd and deba are not.
Input
The first line would consist of t... | t =int(raw_input())
for i in range(0,t):
input = raw_input().split(" ")
a = input[0]
b =input[1]
da = {}
for ch in a:
if da.has_key(ch):
da[ch]+=1
else:
da[ch]=1
db={}
for ch in b:
if db.has_key(ch):
db[ch]+=1
else:
... |
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x... | #include <bits/stdc++.h>
using namespace std;
vector<pair<long long int, long long int> > vs;
long long int a[200007];
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int n, n2, m, i, j, u, v, ans = 1000000000000000000;
cin >> n;
n2 = 2 * n;
for (i = 0; i < n2; i++) cin >> a[i];
... |
You have n coins, each of the same value of 1.
Distribute them into packets such that any amount x (1 ≤ x ≤ n) can be formed using some (possibly one or all) number of these packets.
Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve... | import java.util.*;
public class Packets{
public static void main(String[] args){
int n;
int k=1;
int r=1;
int ans=1;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
while(n>k){
r*=2;
k+=r;
ans++;
}
S... |
Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.
The Dark Assembly consists of n senators. Each of... | #include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double eps = 1e-8;
int tot = 0;
int cnt[8];
int lvl[8];
int loy[8];
int n, k, A;
double ans = 0;
void gao() {
double curWin = 0;
for (int mask = 0; mask < (1 << n); ++mask) {
int winnum = 0;
double B = 0;
double pers = 1;
... |
On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.
There are n bricks lined in a row on the ground. Chouti has got m paint buckets of different colors at hand, so he painted each brick in one of those m colors.
Having finished painting all bricks, Chouti was s... | from math import factorial
[n, m, k] = [int(i) for i in input().split()]
mod = 998244353
l = m*((m-1)**k)
L = factorial(n-1)//factorial(n-1-k)//factorial(k)
print((l*L)%mod)
|
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:
<image>
It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar pi... | #include <bits/stdc++.h>
using namespace std;
const long long INF = 999999999999999999;
const double PI = acos(-1.0);
void stop() { exit(0); }
int main() {
double n, r;
cin >> n >> r;
double sn = sin(PI / n);
double x = (2.0 * r * sn) / (2.0 - 2.0 * sn);
printf("%.9lf", x);
stop();
}
|
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
bool prime[1000001];
long long spf[10000001];
long long f[300005];
long long pow1(long long x, long long y) {
long long res = 1;
x = x % mod;
if (x == 0) return 0;
while (y > 0) {
if (y & 1) res = (res * x) % mod;
y = y >> 1;
... |
We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a... | #include <bits/stdc++.h>
const long long inf = 1e18 + 7, N = 500007;
using namespace std;
long long ar[N], fr[N];
long long n, m, a, b, i, j, k, l, sum, cnt, ans, mx, mn = inf;
string s[55];
vector<long long> v;
int32_t main() {
cin >> n;
for (i = 1; i <= n; i++) cin >> ar[i], fr[ar[i]]++;
i = 4;
if (n == 1)
... |
At Moscow Workshops ICPC team gets a balloon for each problem they solved first. Team MSU Red Panda got so many balloons that they didn't know how to spend them. So they came up with a problem with them.
There are several balloons, not more than 10^6 in total, each one is colored in one of k colors. We can perform the... | #include <bits/stdc++.h>
template <class T>
inline void read(T &res) {
res = 0;
bool bo = 0;
char c;
while (((c = getchar()) < '0' || c > '9') && c != '-')
;
if (c == '-')
bo = 1;
else
res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
if (... |
Mishka's favourite experimental indie band has recently dropped a new album! Songs of that album share one gimmick. Each name s_i is one of the following types:
* 1~c — a single lowercase Latin letter;
* 2~j~c — name s_j (1 ≤ j < i) with a single lowercase Latin letter appended to its end.
Songs are numbered ... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math,O3")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const long long N = 4e5 + 10;
const long long M = 3e8 + 1;
const long long big = 1e18;
const long long shift = 1000;
cons... |
There are n positive integers written on the blackboard. Also, a positive number k ≥ 2 is chosen, and none of the numbers on the blackboard are divisible by k. In one operation, you can choose any two integers x and y, erase them and write one extra number f(x + y), where f(x) is equal to x if x is not divisible by k, ... | #include <bits/stdc++.h>
using namespace std;
int n, k, a[16], b[16];
bitset<2005> f[1 << 16];
bool vis[16];
void solve(int s, int i) {
if (!(s & (s - 1))) return;
for (int u = 0; u <= n - 1; ++u)
if (s >> u & 1 && a[u] < i && f[s ^ (1 << u)][i - a[u]]) {
solve(s ^ (1 << u), i - a[u]);
return;
}... |
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1.
Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1... | #include <bits/stdc++.h>
using namespace std;
char s[1050], ans[1050];
int fl[1050], c[1050];
int is_prime(int n) {
double sqd = n;
sqd = sqrt(sqd);
int sq = sqd;
sq++;
for (int i = 2; i <= sq; i++) {
if ((n % i) == 0) return 0;
}
return 1;
}
int main() {
int i, j, k, l, test, t = 1;
scanf("%s", s... |
Let's call a positive integer composite if it has at least one divisor other than 1 and itself. For example:
* the following numbers are composite: 1024, 4, 6, 9;
* the following numbers are not composite: 13, 1, 2, 3, 37.
You are given a positive integer n. Find two composite integers a,b such that a-b=n.
I... | #include <bits/stdc++.h>
using namespace std;
int main() {
int x;
cin >> x;
int m = 0;
int z = x;
x += 4;
for (int i = 2; i < x; i++) {
if (x % i != 0) {
m = 1;
} else {
cout << x << " "
<< "4";
m = 0;
break;
}
}
if (m == 1) {
x = z;
x += 6;
for... |
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar... | for _ in range(int(input())):
n=int(input())
s=input()
if len(s)==1:
print(-1)
else:
#ans=s[0]
ans=''
f=0
for i in range(0,n):
if int(s[i])%2==1 and f<2:
ans+=s[i]
f+=1
#break
if f<2:
... |
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | #####################################
import atexit, io, sys, collections, math, heapq, fractions, bisect
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
####################################
def f(ais,pis):
non = set([pi-1 for pi in pis])
for i... |
Kate has a set S of n integers \{1, ..., n\} .
She thinks that imperfection of a subset M ⊆ S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a ≠ b.
Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am... | from collections import *
from math import *
N = int(5e5+5)
p = [0 for i in range(N)]
for i in range(2,N):
if(p[i] == 0):
for j in range(i*i,N,i):
if(p[j] == 0): p[j] = i
n = int(input())
a = [1 for i in range(n+1)]
primes = []
ct = 0
for i in range(1,n+1):
if p[i] == 0:
ct += 1
primes.append(i)
g = 2
dig ... |
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.
You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n... | import math
def solve():
n = int(input())
n *= 2
all = (n-2) * math.pi
one = math.pi - all/n
now = one
ans = 0.5
for i in range(n//2-1):
ans += max(math.cos(now), 0)
now += one
print(ans*2)
for i in range(int(input())):
solve()
|
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | t=int(input())
for i in range(t):
x, y, n=map(int,input().split())
print(n-(n-y)%x) |
Let's call a list of positive integers a_0, a_1, ..., a_{n-1} a power sequence if there is a positive integer c, so that for every 0 ≤ i ≤ n-1 then a_i = c^i.
Given a list of n positive integers a_0, a_1, ..., a_{n-1}, you are allowed to:
* Reorder the list (i.e. pick a permutation p of \{0,1,...,n - 1\} and change... | import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')
MOD = 10 ** 9 + 7
def gcd(a, b):
while b:
a, b = b, a%b
return a
def isPrime(n):
if (n <= 1):
return False
i = 2
while i ** 2 <= n:
if n % i == 0:
return False
i += 1
return True
def primeFactors(n):
facto... |
This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.
Pikachu is a cute and friendly pokémon living in the wild pikachu herd.
But it has become known recently that infamous team R... | input=__import__('sys').stdin.readline
def check(*inds):
global localmax, localmin, maxs, mins
for ind in inds:
if not ok(ind):continue
if localmax[ind]==0 and s[ind-1]<s[ind]>s[ind+1]:localmax[ind]=1;maxs+=s[ind]
if localmin[ind]==0 and s[ind-1]>s[ind]<s[ind+1]:localmin[ind]=1;mins+=s[ind]
def upd0(*inds):
gl... |
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices ... | #include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;
const int M = 1000000007;
const long long LM = 1LL << 60;
vector<int> solve(const vector<vector<int>>& edge, int k) {
int n = edge.size();
queue<int> q;
vector<int> deg(n);
vector<bool> del(n);
for (int i = 0; i < n; ++i) {
deg[i] = e... |
Athenaeus has just finished creating his latest musical composition and will present it tomorrow to the people of Athens. Unfortunately, the melody is rather dull and highly likely won't be met with a warm reception.
His song consists of n notes, which we will treat as positive integers. The diversity of a song is th... | #include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<int> arr(n);
vector<int> arr1(n);
for (int i=0;i<n;++i){
cin >> arr[i];
arr1[i] = arr[i] + 1;
}
set<int> st;
for (int i=0;i<n;++i){
if (st.find(arr[i]) ... |
You are given a positive integer x. Check whether the number x is representable as the sum of the cubes of two positive integers.
Formally, you need to check if there are two integers a and b (1 ≤ a, b) such that a^3+b^3=x.
For example, if x = 35, then the numbers a=2 and b=3 are suitable (2^3+3^3=8+27=35). If x=4, t... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int const N = 1e4 + 4;
map<ll, bool> frq;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int test; cin >> test;
for (int i = 1; i < N; i++)
frq [1ll * i * i * i] = true;
while (test--) {
ll n; cin >> n;
... |
Polycarp is wondering about buying a new computer, which costs c tugriks. To do this, he wants to get a job as a programmer in a big company.
There are n positions in Polycarp's company, numbered starting from one. An employee in position i earns a[i] tugriks every day. The higher the position number, the more tugriks... | import java.io.*;
import java.util.*;
public class Main2{
static int n;
static long a[],b[];
static long solve(int i,long c,long have) {
if(c<=have)return 0;
long stay=(c-have+a[i]-1)/a[i];
if(i==n-1) {
return stay;
}
long move;
if(have>=b[i]) {
move=0;
}
else {
move=((b[i]-have+a[i]-1)/a[i... |
One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.
One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've b... | #include <bits/stdc++.h>
using namespace std;
const int LMT = 202;
const int zero = 200;
int rest[LMT];
double dp[LMT][LMT][LMT << 1], p[LMT];
int main() {
int n, l, k, x;
double ans = 0;
scanf("%d%d%d", &n, &l, &k);
;
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
p[i] = x / 100.0;
}
for (int i ... |
Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.
A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebr... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, i;
cin >> n;
long long int dp[n + 1][2], m = 1000000007;
dp[0][0] = 0;
dp[0][1] = 0;
for (i = 1; i <= n; i++) {
dp[i][i % 2] = (dp[i - 1][1 - (i % 2)] + 1 + dp[i - 1][(i % 2... |
In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world — the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the dr... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class E implements Runnable {
private static class Team implements Comparable<Team> {
public String name;
public int rating;
p... |
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance betw... | #include <bits/stdc++.h>
using namespace std;
long long int grid[305][305], result[305][305];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL);
long long int i, j, t, n, m, k, l, r, temp, sum, mini, maxi, flag;
cin >> n;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
cin >> grid[i][j]... |
In the Isle of Guernsey there are n different types of coins. For each i (1 ≤ i ≤ n), coin of type i is worth ai cents. It is possible that ai = aj for some i and j (i ≠ j).
Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1 ≤ i ≤ q), the pair bi, ci tells Jessie ... | #include <bits/stdc++.h>
using namespace std;
namespace FGF {
const int N = 5e5 + 5, mo = 1e9 + 7;
long long n, a[N], m, q, fa[N], vis[N], dep[N], ins[N], dp[N], sum[N];
vector<int> g[N];
void dfs(int u) {
ins[u] = 1;
for (auto v : g[u]) sum[v] = a[v] + sum[u], dfs(v), dep[u] = dep[v] + 1;
m -= dep[u] * a[u];
}
v... |
A process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a conti... | #include <bits/stdc++.h>
void gi(long long int &x) {
char ch = getchar();
x = 0;
while (ch < '0' || ch > '9') ch = getchar();
while (!(ch < '0' || ch > '9')) x = x * 10 + ch - 48, ch = getchar();
}
long long int n, m, l[202020], r[202020], q[202020];
void swap(long long int i, long long int j) {
long long int... |
Don't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≤ x, y ≤ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transp... | #include <bits/stdc++.h>
using namespace std;
template <class T>
void setmin(T &a, T b) {
if (b < a) a = b;
}
template <class T>
void setmax(T &a, T b) {
if (b > a) a = b;
}
template <class T>
T gcd(T a, T b) {
return b == 0 ? a : gcd(b, a % b);
}
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
... |
Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.
Vasya needs to collect all these items, however he won't do it by himself. He us... | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:640000000")
using namespace std;
const double eps = 1e-9;
const double pi = acos(-1.0);
const int maxn = (int)1e5 + 10;
int n, l, r, ql, qr;
int w[maxn];
long long sum[maxn];
long long solve() {
sum[0] = 0;
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - ... |
Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the peopl... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class B
{
public static void main(String[] args)
{
MyScanner in = new MyScanner();
int N = in.nextInt();
int[] a = new int[N];
int[] b = new i... |
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment ... | #دو تا نقطه تو مختصات سه بعدی میده میگه اینا تو یک وجه از مکعل هستند یا نه
print('YES' if any(i == j for i,j in zip(list(input().split()) ,list(input().split()))) else 'NO') |
Cold winter evenings in Tomsk are very boring — nobody wants be on the streets at such a time. Residents of Tomsk while away the time sitting in warm apartments, inventing a lot of different games. One of such games is 'Colored Jenga'.
This game requires wooden blocks of three colors: red, green and blue. A tower of n... | #include <bits/stdc++.h>
using namespace std;
template <typename A, typename B>
ostream &operator<<(ostream &s, const pair<A, B> &p) {
return s << "(" << p.first << "," << p.second << ")";
}
template <typename T>
ostream &operator<<(ostream &s, const vector<T> &c) {
s << "[ ";
for (auto it : c) s << it << " ";
... |
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater... | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > ans;
const int M = 1e5;
bool vis[M + 5];
bool isPrime[M + 5];
int factor[M + 5];
void getPrime() {
for (int i = 0; i <= M; i++) isPrime[i] = 1;
isPrime[0] = isPrime[1] = 0;
for (int i = 2; i * i <= M; i++) {
if (isPrime[i]) {
for (int... |
Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial.
Vasya has made a bet with his friends that h... | #include <bits/stdc++.h>
using namespace std;
long long t, a, b;
int main() {
cin >> t >> a >> b;
if (t == 1) {
if (a == 1 && b == 1) {
cout << "inf" << endl;
return 0;
} else if (a == 1) {
cout << 0 << endl;
return 0;
} else {
int flag = 0;
long long p = 1;
whi... |
Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.
Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue ente... | #include <bits/stdc++.h>
using namespace std;
long long int modulo = 1000000007;
int main(int argc, char** argv) {
int n, t;
double p;
cin >> n >> p >> t;
vector<vector<double> > dp(t + 1, vector<double>(n + 1, 0.0));
dp[0][0] = 1.0;
for (int i = 0; i <= t - 1; ++i) {
for (int j = 0; j <= n - 1; ++j) {
... |
In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any ... | from itertools import combinations_with_replacement
from collections import deque
#sys.stdin = open("input_py.txt","r")
n, m = map(int, input().split())
G = [ [] for i in range(n)]
for i in range(m):
x, y = map(int, input().split())
x-=1; y-=1
G[x].append(y)
G[y].append(x)
def BFS(s):
dist = [-... |
You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the l... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
long long a, b, c, s;
long long gao(long long a, long long b, long long xl, long long xr) {
if (xl > xr) return 0;
if (a * xl + b < 0 && a * xr + b < 0) return 0;
double key = -b * 1.0 / a;
long long keyx;
if (a > 0) {
keyx = (key - EP... |
Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go ... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 124000;
bool tag[maxn];
vector<int> v1[maxn], v2[maxn];
int a[maxn];
bool check[maxn];
int d;
bool Go(int x, int fa) {
for (int i = 0; i < v1[x].size(); i++) {
if (fa == v1[x][i]) continue;
if (Go(v1[x][i], x)) {
v2[x].push_back(v1[x][i]);
... |
It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not en... | #include <bits/stdc++.h>
using namespace std;
char s[100005], ans[100005];
int main() {
int n;
scanf("%d", &n);
int flag = 0, flag2 = 0;
int cnt = 0;
for (int i = 0; i < n; i++) {
scanf("%s", s);
if (s[0] == '0')
flag = 1;
else {
if (s[0] != '1') {
flag2 = 1;
strcpy(ans... |
Yash loves playing with trees and gets especially excited when they have something to do with prime numbers. On his 20th birthday he was granted with a rooted tree of n nodes to answer queries on. Hearing of prime numbers on trees, Yash gets too intoxicated with excitement and asks you to help out and answer queries on... | #include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5 + 5;
const int maxM = 1e3 + 5;
const long long INF = 1e18;
const long long MOD = 1e9 + 7;
long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); }
long long sq(long long x) { return (x * x) % MOD; }
long long modP(long long a, long lon... |
You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edge... | #include <bits/stdc++.h>
using namespace std;
int n, m;
char in[10];
vector<list<int> > V;
map<pair<int, int>, bool> M;
struct Edge {
int x, y;
bool c;
};
Edge E[101000];
bool v[101000];
bool T[101000];
bool col;
void BFS() {
queue<int> Q;
for (int i = 1; i <= n; ++i)
if (v[i] == false) {
list<int> L;... |
When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.
Mole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is bl... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 5, MOD = 1e9 + 7;
const long long INF = 9e18;
namespace IStream {
const int LLL = 1 << 15;
char buffer[LLL + 5], *s, *t;
inline char get_char() {
if (s == t) {
t = (s = buffer) + fread(buffer, 1, LLL, stdin);
if (s == t) return EOF;
}
retur... |
For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}.
In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matc... | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import static java.lang.Math.min;
import static java.util.Collections.binarySearch;
import static java.util.... |
Polycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there.
"Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant.
Let's assume a customer currently has b bonuses and she has to pay r burles for a ... | #include <bits/stdc++.h>
const int N = 5054, M = 10054;
int n, B;
int a[N], A[N], ans[N];
int dp[2][M], *cur = *dp, *nxt = dp[1];
short from[N][M];
inline bool down(int &x, const int y) { return x > y ? x = y, 1 : 0; }
int main() {
int i, j, nj, u, v, used, s = 0;
scanf("%d%d", &n, &B);
memset(nxt, 63, sizeof *dp... |
One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one... | #include <bits/stdc++.h>
using namespace std;
long long n, a[500], b[500], ans[500][4], l, r, smm, sum, k;
int flag = 0;
int main() {
ios_base::sync_with_stdio(0);
cin >> n;
memset(b, 0, sizeof b);
memset(a, 0, sizeof a);
for (long long i = (1); i <= (n); i++) {
cin >> a[i];
if (a[i] != 0) flag = 1;
... |
Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not.
Stepan's dissatisfaction is the maximum num... | #include <bits/stdc++.h>
using namespace std;
long long n, k;
string s;
long long cache[101][105];
long long dp(long long pos, long long tk) {
if (tk > k) return -1e18;
if (pos == n) return tk == k;
long long ans = tk == k;
if (cache[pos][tk] != -1) return cache[pos][tk];
if (s[pos] != '?')
return cache[p... |
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly.
However, Ciel fee... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
void print(vector<T>& v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << ' ';
}
cout << '\n';
}
vector<int> z_function(string s) {
int n = (int)s.length();
vector<int> z(n);
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <... |
There are n students in Polycarp's class (including himself). A few days ago all students wrote an essay "My best friend". Each student's essay was dedicated to one of the students of class, to his/her best friend. Note that student b's best friend is not necessarily student a, if a's best friend is b.
And now the tea... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 110000;
int n;
struct Tinit {
int f, u;
} A[maxn];
struct Tcxx {
int A, B;
Tcxx(int _A = 0, int _B = 0) { A = _A, B = _B; }
inline bool operator<(const Tcxx &b) const {
return A != b.A ? A < b.A : B < b.B;
}
inline Tcxx operator+(const Tcxx ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.