input
stringlengths
29
13k
output
stringlengths
9
73.4k
Functional graph is a directed graph in which all vertices have outdegree equal to 1. Loops are allowed. Some vertices of a functional graph lay on a cycle. From the others we can come to a cycle by making a finite number of steps along the edges (we consider only finite functional graphs in this problem). Let's comp...
#include <bits/stdc++.h> const int N = 307; int max(int a, int b) { return a > b ? a : b; } int n, m, mx, len[N], dis[N], fa[N], x[N], y[N], cnt[N], mxd[N], e[N][N], vis[N], L[N], R[N], mat[N]; std::vector<int> vec[N]; char s1[5], s2[5]; int dfs(int u) { for (int v = 1; v <= m; ++v) if (e[u][v] && !vis[v] && ...
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of th...
#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; char a[MAXLEN + 1]; int alen; char b[MAXLEN + 1]; int blen; int ldp[MAXLEN + 1]; int rdp[MAXLEN + 1]; int nxt[MAXLEN + 1][26]; int prv[MAXLEN + 1][26]; void run() { s...
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)). On the last lesson Anton learned about the regular simple bracket s...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.ObjectInputStream.GetField; import java.io.PrintWriter; import java.math.BigInteger; i...
Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems. For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends...
#include <bits/stdc++.h> using namespace std; long long point(long long a, long long b) { long long x = 500; while (x < 3000 and 2 * a <= b) { a *= 2; x += 500; } return x; } int main() { long long n, i, j, k; scanf("%lld", &n); long long arr[n + 1][5], count[5], score[5]; memset(count, 0, sizeo...
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class E_Roun...
Consider an array A with N elements, all being the same integer a. Define the product transformation as a simultaneous update Ai = Ai·Ai + 1, that is multiplying each element to the element right to it for <image>, with the last number AN remaining the same. For example, if we start with an array A with a = 2 and N = ...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b, long long &x, long long &y) { if (a == 0) { x = 0; y = 1; return b; } long long x1, y1; long long ret = gcd(b % a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return ret; } long long discreteLog(long long a, l...
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
judul = input() nama = ["Danil", "Olya", "Slava", "Ann", "Nikita"] cek = 0 ada = [] for i in range(0, 5): ada.append(judul.count(nama[i])) cek = cek + ada[i] if cek == 1: print("YES") else: print("NO")
You have a fraction <image>. You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point. Input The first contains three single positive integers a, b, c (1 ≤ a < b ≤ 105, 0 ≤ c ≤ 9). Output Print position of the first occurrence of digit c into the fraction. Positions...
a,b,c = map(int, input().split()) t = a q, r = divmod(t, b) for i in range(1, 10**5+1): q, r = divmod(r*10, b) #print(q) if q == c: print(i) exit() else: print(-1)
Imp is really pleased that you helped him. But it you solve the last problem, his gladness would raise even more. <image> Let's define <image> for some set of integers <image> as the number of pairs a, b in <image>, such that: * a is strictly less than b; * a divides b without a remainder. You are to find su...
#include <bits/stdc++.h> using namespace std; int n, k; long long dp[300000 + 100]; bool is_prime[300000 + 100]; void solve() { memset(dp, 0, sizeof(dp)); fill(is_prime, is_prime + n + 1, true); is_prime[0] = is_prime[1] = false; for (int i = 1; i <= n; i++) { for (int j = i * 2; j <= n; j += i) { dp[...
Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information. Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred...
#include <bits/stdc++.h> using namespace std; int main() { unsigned long long n, m; cin >> n >> m; unsigned long long a, b, s = 0, s1[n], s2[m], c = 0; for (unsigned long long i = 0; i < n; i++) { cin >> a; s += a; s1[i] = s; } s = 0; for (unsigned long long i = 0; i < m; i++) { cin >> b; ...
The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops. If x is the number of passengers in a bus just before the current bus stop and y is the number of passengers in the bus just after current bus stop, the sy...
import java.io.*; import java.util.*; public class BusVideo { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int stops = sc.nextInt(); int capacity = sc.nextInt(); int minLoss = 0; int maxGain = 0; int curr = 0; sc.nextLine(); for(int i = 0; i < stops; i+...
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed. Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as...
a = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292] n = int(input()) if n < len(a): print (a[n]) else: print (a[11] + 49*(n-11))
Our juniors has just entered in coding community. Their first task is to find the frequency of Best numbers present in given list of elements. Best numbers are numbers which are divisible by 2. SAMPLE INPUT 2 5 1 2 3 4 5 3 1 3 5 SAMPLE OUTPUT 2 0 Explanation Number of test cases=2 1st test case, number of elements ...
for p in range(input()): input() l=map(int,raw_input().split()) print sum([l.count(i) for i in set(l) if i%2==0])
In HackerLand, they have a very strange monetary system. Each gold coin has an integer number 'N' written on it. A coin N can be split into any number of coins. For example {11} can be split into {5,6} or {2,4,5} or any other possible way. You are offered such a coin to take home. But your family does not like coins w...
import sys import math n = input() def is_prime(n): if n==1: return False if n % 2 == 0 and n > 2: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True for i in range(n): temp = input() if temp==3: print...
Gandalf's army is fighting against Sauron's army and each of army has even number of N men for current war to be fought. Both of them want to finsh the war fastly . So both fought in manner that war was finished in three turns. Each turn consisting of one army shooting against enemy army furiously, all...
def getfactor(n): c=0 while n != 0 : if (n%2 == 0): n=n/2 c+=1 else : return 0 return c def getval(num): if (getfactor(num) != 0 ): print getfactor(num) else: print num /2 num = int(raw_input()) for i in xrange(num): getval(int(raw_input()))
You have reached the final level of Hunger Games and as usual a tough task awaits you. You have a circular dining table and N hungery animals.You need to place them on the table.Each animal has a hunger value. You can place the animals in any order on the circular table.Once you place them you need to calculate the Dan...
n=input() list1=raw_input().split() list1=[int(i) for i in list1] list1.sort() #print list1 list2=[] for i in range(1,n-2): list2.append(list1[i+2]-list1[i]) list2.append(list1[2]-list1[0]) list2.append(list1[1]-list1[0]) list2.append(list1[n-1]-list1[n-2]) list2.sort() print list2[n-1]
Task is simple. You are provided with a string of curly brackets and you have to do the following - Print 0 if the brackets are balanced. Print k if it is unbalanced, where k is the number of actions performed to balance it. Print -1 if it cannot be balanced. Definition of a Balanced String - { } is a balanced strin...
from math import * T=input() while(T): T-=1 N=raw_input() count_1=0 count=0 for x in N: if(x=='{'): count_1+=1 elif(x=='}'): count_1-=1 if(count_1<0): count+=1 count_1=0 if((count+count_1)%2==0): print int(ceil(count/2.0)) + int(ceil(count_1/2.0)) else: print -1
Doraemon gave Nobita a gadget that swaps words inside a string in the following manner : If there are W words, word 1 is swapped with word W, word 2 is swapped with word W-1 and so on. The problem is that Nobita himself cannot verify the answer for large strings. Help him write a program to do so. INPUT : the first ...
t = int(raw_input()) for i in range(t): str = raw_input().split() d =[] for j in reversed(str): d.append(j) print ' '.join(d)
Pythagorean triplet (a,b,c) satisfies: You will be given an integer N. You have to count how many triplets a,b,c exist such that 1 ≤ a ≤ b ≤ c ≤ N. Input: First line contains T, the number of testcases. Each testcase consists of only one integer in one line. Output: For each testcase, print the required answ...
tri = lambda m,n:(m**2-n**2, 2*m*n, m**2+n**2) def coprime(x, y): while y: x, y = y, x%y return x==1 n = input() while n: n -= 1 m = input() c, i = 0, 2 l = int(pow(m,0.5)) + 1 while i<l: j = 1 while j<i: if coprime(i,j) and (i**2+j**2)<=m and (i-j)%2: c += m/(i**2+j**2) j += 1 i += 1 prin...
Shil likes to perform Crazy Operation on an array A1,A2,...AN. Given an array A1,A2,...AN and permutation P1,P2, ..,PN, a Crazy Operation consists of two parts: Perform Operation Bi = Ai for every i in 1..N Perform Operation Ai = BPi for every i in 1..N. Here P is a permutation from 1 to N. Shil asks you to prin...
n,t=map(int,raw_input().split()) a=[0]+map(int,raw_input().split()) p=[0]+map(int,raw_input().split()) q=[i for i in range(n)] def app(p,x): res=[0]*len(p) for i in range(len(p)): res[i]=x[p[i]] return res while t>0: if t%2: a=app(p,a) p=app(p,p) t/=2 print " ".join(map(str,a[1:]))
Raman got placed in AWS. He is organizing his job party in which N number of people are invited and only K people joined the party. Ofcourse, Raman is also present in the party! K ≤ N In the party everyone starts shaking hands with everyone else. Given, any two persons shake hand exactly once. Can you tell the tota...
t=input() while t>0: t-=1 n, k=raw_input().split(" ") n, k=int(n), int(k) print (k*(k+1))/2
Mr. Retardo has lost his marbles. He's a professor, and absolutely loathes his students. And since going full retard, he asks them all sorts of useless questions. His latest obsession is prime numbers, and he gives all his a students random number n and asks them to check if it is prime. Check if it is!! Note that th...
from math import sqrt def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(sqrt(n)) f = 5 while f <= r: if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True for _ in xrange(input())...
There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i. Find the number of different values that the median of X_1, X_2, \cdots, X_N can take. Constraints * 2 \leq N \leq 2 \times 10^5 * 1 \leq A_i \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard ...
#include <bits/stdc++.h> using namespace std; typedef long long int LL; typedef pair<int,int> P; typedef pair<LL,LL> PL; int main(){ LL n; cin>>n; LL a[200010],b[200010]; for(LL i=0;i<n;i++){ cin>>a[i]>>b[i]; } sort(a,a+n); sort(b,b+n); if(n%2!=0){ LL m=n/2; cout<<b[m]-a[m]+1<<endl; }...
Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller? Constraints * 1 \leq a \leq 9 * 1 \leq b \leq 9 * a and b are integers. Input Input is given from Stan...
N = list(map(int, input().split())) a = N.sort() print(str(N[0])*N[1])
E869120 is initially standing at the origin (0, 0) in a two-dimensional plane. He has N engines, which can be used as follows: * When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the ...
import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Objects; public class Main { public static void main(String[] args) { FastScanner fsc = new FastScanner(); int n = fsc.nextInt(); LightComplex[] c = new...
There are N integers, A_1, A_2, ..., A_N, written on the blackboard. You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written. Find the maximum possible greatest common divisor of the N integers on the blackboard afte...
#include <bits/stdc++.h> using namespace std; int gcd(int x, int y){ int r; while((r=x%y)!=0){x=y; y=r;} return y; } int main(){ int N; cin >> N; vector<int> A(N); for(int i=0;i<N;i++)cin >> A[i]; sort(A.begin(),A.end()); for(int i=A[1];i>=1;i--){ int cnt=0; bool q=true; for(int j=0;j<N;j++)...
You are given N-1 subsets of \\{1,2,...,N\\}. Let the i-th set be E_i. Let us choose two distinct elements u_i and v_i from each set E_i, and consider a graph T with N vertices and N-1 edges, whose vertex set is \\{1,2,..,N\\} and whose edge set is (u_1,v_1),(u_2,v_2),...,(u_{N-1},v_{N-1}). Determine if T can be a tre...
#include <bits/stdc++.h> using namespace std; typedef bool boolean; const int inf = (signed) (~0u >> 1); typedef class Edge { public: int ed, nx, r; Edge() { } Edge(int ed, int nx, int r) : ed(ed), nx(nx), r(r) { } } Edge; typedef class MapManager { public: int *h; vector<Edge> E; MapManager() { } ...
You are given a positive integer X. Find the largest perfect power that is at most X. Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2. Constraints * 1 ≤ X ≤ 1000 * X is an integer. Input Input is given from Standard Input ...
#include <iostream> #include <cmath> using namespace std; int main() { int X; cin >> X; int ans = 1; for(int i = 2; i < X; ++i) { for(int j = 2; pow(i, j) <= X; ++j) { ans = max(ans, int(pow(i, j))); } } cout << ans << endl; }
Consider an infinite sequence a_1, a_2, … Initially, the values of all the terms are 0, and from this state we will sequentially perform Q operations. The i-th operation (1 ≤ i ≤ Q) is as follows: * For every positive integer j, add x_i to the value of a_{j × m_i}. Find the value of the largest term after these Q o...
#include <bits/stdc++.h> #define int long long #define rep(i,n) for(int i=0;i<(int)(n);i++) #define rep1(i,n) for(int i=1;i<=(int)(n);i++) #define all(c) c.begin(),c.end() #define pb push_back #define fs first #define sc second #define show(x) cout << #x << " = " << x << endl #define chmin(x,y) x=min(x,y) #define chmax...
You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n. It is known that each of the n integers 1,...,n appears at least once in this sequence. For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given s...
# ------ combination ------- N, MOD = 10**5 + 1, 10**9 + 7 fc, ifc = [0] * (N+1), [0] * (N+1) def power(n, a): res, exp = 1, n while(a): if a & 1: res = res * exp % MOD exp = exp * exp % MOD a = a >> 1 return res fc[0] = 1 for i in range(1, N+1): fc[i] = fc[i-1] * i...
You are given an integer N. Find the number of the positive divisors of N!, modulo 10^9+7. Constraints * 1≤N≤10^3 Input The input is given from Standard Input in the following format: N Output Print the number of the positive divisors of N!, modulo 10^9+7. Examples Input 3 Output 4 Input 6 Output 3...
n = int(input()) multiplier = [0 for _ in range(n)] for m in range(2, n+1): a = m i = 2 while i ** 2 <= m: while a % i == 0: a = int(a / i) multiplier[i-1] += 1 i += 1 if a != 1: multiplier[a-1] += 1 ans = 1 for x in multiplier: ans *= x + 1 print(ans...
There is a grid with R rows and C columns. We call the cell in the r-th row and c-th column (r,c). Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i,c_i) for each i (1≤i≤N). After that he fell asleep. Mr. Aoki found the grid and tries to surprise Mr....
#include <stdio.h> #include <iostream> #include <vector> #include <assert.h> #include <set> #include <map> #include <cmath> #include <queue> #include <stack> #include <string> #include <sstream> #include <memory.h> #include <time.h> #include <string.h> #include <stdlib.h> #include <algorithm> using namespace std; typed...
Create a program that converts the date expressed in the Christian era to the Japanese calendar using the era name and outputs the date. The input is three integers, as shown in the example, in the order year, month, and day. Convert this as shown in the sample output. If the date before the Meiji era is entered, pleas...
#include <iostream> using namespace std; int main(){ char c[20]; while(cin.getline(c,16)){ int y,m,d; y = c[0]*1000+c[1]*100+c[2]*10+c[3]; y -= '0'*1111; m = d = 0; int i = 5; while(c[i] != ' '){ m *= 10; m += c[i]-'0'; ++i; } ++i; while(c[i]){ d *= 10; d += c[i]-'0'; ++i; } ...
A popular game in a certain country, Pachimon Creature, has been remade and released in Japan. If you love games, after playing this game many times, you've come to think about how you can clear it the fastest. However, no matter how much you think about it, you didn't know the fastest way to capture it, so you decided...
#include <cstdio> #include <cstring> #include <cctype> #include <cmath> #include <utility> #include <vector> #include <algorithm> using namespace std; typedef pair<int,int> P; #define DIST(X,Y)(abs((X).first-(Y).first)+abs((X).second-(Y).second)) int dp[6][1000]; vector<P> location[7]; char M[1000][1001]; int main() { ...
In Japan, temperature is usually expressed using the Celsius (℃) scale. In America, they used the Fahrenheit (℉) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Today’s temperature is $68$ degrees" is commonly encountered while you are in America. A value in Fahrenhei...
x=input() x=int(x) y=(x-30)//2 print(y)
The fundamental idea in the JPEG compression algorithm is to sort coeffi- cient of given image by zigzag path and encode it. In this problem, we don’t discuss about details of the algorithm, but you are asked to make simple pro- gram. You are given single integer N , and you must output zigzag path on a matrix where si...
#include <bits/stdc++.h> using namespace std; #define REP(i,a,b) for(int i=a;i<b;i++) #define rep(i,n) REP(i,0,n) int N; bool bump(int x, int y) { return x<0||y<0||N<=x||N<=y; } int main() { int Tc = 1; while(cin >> N && N) { int cnt = 1; int dx = 1, dy = -1; int x = 0, y = 0; int ans[N][N]; ...
You have a computer literacy course in your university. In the computer system, the login/logout records of all PCs in a day are stored in a file. Although students may use two or more PCs at a time, no one can log in to a PC which has been logged in by someone who has not logged out of that PC yet. You are asked to w...
//Analyzing Login/Logout Records #include<bits/stdc++.h> using namespace std; int pc[1000][721], st[10000][721]; int main(){ int N, M; while(cin>>N>>M, !(N==0&&M==0)){ int r; memset(pc, 0, sizeof(pc)); memset(st, 0, sizeof(st)); cin>>r; while(r--){ int t, n, m, s; cin>>t>>n>>m>>s; ...
On a small planet named Bandai, a landing party of the starship Tadamigawa discovered colorful cubes traveling on flat areas of the planet surface, which the landing party named beds. A cube appears at a certain position on a bed, travels on the bed for a while, and then disappears. After a longtime observation, a scie...
#include<iostream> #include<queue> #include<set> using namespace std; #define NORTH 0 #define EAST 1 #define SOUTH 2 #define WEST 3 #define DIRMAX 4 #define DBOTTOM 0 #define DSOUTH 1 #define DWEST 2 #define DNORTH 3 #define DEAST 4 #define DTOP 5 const int dc[] = {120,24,6,2,1}; struct Dice{ int D[6]; void ro...
Problem I chose creature observation as the theme of my free study during the summer vacation and purchased a creature observation kit. This creature prefers to live in a three-dimensional grid-like space. Only one animal can be placed in each cell. It repeats birth and death every day according to the surrounding en...
#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_...
Mr. Bill is shopping at the store. There are some coins in his wallet (10-yen coins, 50-yen coins, 100-yen coins, 500-yen coins), but he is now trying to consume as much of this coin as possible. In other words, by paying for the goods with an appropriate number of coins, we are trying to minimize the total number of c...
#include <algorithm> #include <iostream> using namespace std; int mincoin(int a) { int i, j, k, l, n; l = a/500; k = (a%500)/100; j = (a%100)/50; i = (a%50)/10; n = i+k+j+l; return n; } int main() { int price, a, b, c, d, i, j, k, l, p, q, r, s, change, num, tempnum; cin >> price; if (price ==...
Twin adventurers Rin and Len are searching for treasure in the Mirror Cave. The cave has two pairs of rooms, the Hall of Mirrors, and an expensive treasure lies behind the door of the room. For convenience, each of the two rooms is considered to have W × H cells arranged in a grid pattern. The outside of the room is s...
#include <iostream> #include <string> #include <queue> using namespace std; struct state{ int lx,ly,rx,ry; }; int dx[] = {0,1,0,-1},dy[] = {1,0,-1,0}; bool dp[50][50][50][50]; int main(){ int h,w; while(cin >> w >> h,h){ int lx,ly,rx,ry; for(int i = 0;i < 50;i++){ for(int j = 0;j < 50;j++){ for(int k =...
Mr. Don is an administrator of a famous quiz website named QMACloneClone. The users there can submit their own questions to the system as well as search for question texts with arbitrary queries. This search system employs bi-gram search method. The bi-gram search method introduces two phases, namely preprocessing and...
#include <bits/stdc++.h> using namespace std; #define int long long #define all(v) (v).begin(), (v).end() #define resz(v, ...) (v).clear(), (v).resize(__VA_ARGS__) #define reps(i, m, n) for(int i = (int)(m); i < (int)(n); i++) #define rep(i, n) reps(i, 0, n) template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>...
You are on board a trading ship as a crew. The ship is now going to pass through a strait notorious for many pirates often robbing ships. The Maritime Police has attempted to expel those pirates many times, but failed their attempts as the pirates are fairly strong. For this reason, every ship passing through the stra...
#include <cstdio> #include <cmath> int W, H, N; int x[500], y[500], p[502]; int findset(int x) { return x == p[x] ? x : p[x] = findset(p[x]); } int main() { scanf("%d %d %d", &W, &H, &N); for (int i = 0; i < N; ++i) scanf("%d %d", &x[i], &y[i]); double L = 0; double R = 2e9; while (R - L > 1e-4) { double ...
Sunake is in the form of a polygonal line consisting of n vertices (without self-intersection). First, Sunake-kun's i-th vertex is at (xi, yi). You can move continuously by translating or rotating, but you cannot deform (change the length of the polygonal line or the angle between the two line segments). y = 0 is the w...
import java.awt.geom.Line2D; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class Main { static InputStream is; static PrintWriter out; static String IN...
Example Input 5 5 4 6 3 2 4 2 5 2 1 4 3 4 5 4 Output 6
#include <bits/stdc++.h> using namespace std; const int inf = 1e9; int main() { int w, h, k; cin >> w >> h >> k; int n; cin >> n; vector<vector<int>> cost(w, vector<int>(h / 2, 1)); for(int i = 0; i < n; ++i) { int x, y; cin >> x >> y; x--, y--; if(y % 2 == 0) continue; ...
J: City Santa decides to deliver a present to a city. The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with one house delivering gifts to each parcel. The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $. Santa mov...
#include<iostream> using namespace std; int main(){ int h, w, s, t; cin >> h >> w >> s >> t; if(h > w) swap(h,w), swap(s,t); if(h == 1){ cout << (t==0||t==w-1 ? "Yes" : "No") << endl; }else{ bool ok = w%2 == 0 || h%2 == 0; // wもhも奇数のとき、縦s、横tの線で長方形の区画を4等分したときに // 4区...
Problem Given a permutation of length $ N $ $ P = \\ {P_1, P_2, \ ldots, P_N \\} $ and the integer $ K $. Determine if the permutation $ P $ can be monotonically increased by repeating the following operation any number of times $ 0 $ or more. * Choose the integer $ x \ (0 \ le x \ le N-K) $. Patrol right shift aroun...
#include <iostream> #include <utility> #include <stdio.h> #include <math.h> #include <algorithm> #include <vector> #define llint long long #define mod 998244353 #define eps 1e-8 using namespace std; struct BIT{ int size; vector<int> bit; BIT(){size = 0;} BIT(int s){ size = s; bit.resize(size+1); init(); } ...
Write a program which prints the central coordinate ($cx$,$cy$) and the radius $r$ of a circumscribed circle of a triangle which is constructed by three points ($x_1$, $y_1$), ($x_2$, $y_2$) and ($x_3$, $y_3$) on the plane surface. Constraints * $-10000 \leq x_i, y_i \leq 10000$ * The three points are not on the same...
#include <bits/stdc++.h> using namespace std; #pragma region Geometry const double EPS=1e-8,PI=acos(-1); inline bool EQ(double a,double b){return fabs(b-a)<EPS;} static const int COUNTER_CLOCKWISE=1; static const int CLOCKWISE=-1; static const int ONLINE_BACK=2; static const int ONLINE_FRONT=-2; static const int ON_SE...
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique. * insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation. * find($x$): Report the number of $x$ in $S$ (0 or 1). Constraints * $1 \leq q \leq 200,000$ * $0 \leq ...
n = int(input()) s = set() for _ in range(n): a, b = map(int,input().split()) if a == 0: s.add(b) print(len(s)) else: if b in s: print(1) else: print(0)
Today a plane was hijacked by a maniac. All the passengers of the flight are taken as hostage. Chef is also one of them. He invited one of the passengers to play a game with him. If he loses the game, he will release all the passengers, otherwise he will kill all of them. A high risk affair it is. Chef volunteered fo...
import re def processBallons(line, k): x = re.split(" ", line) r = int(x[0]); g = int(x[1]); b = int(x[2]) # return 1+min(r,k-1)+min(g,k-1)+min(b,k-1) if __name__ == '__main__': T = int(raw_input()) for t in range(T): line = raw_input() k = int(raw_input()) print process...
Consider a k x k matrix M with entries as the following: M(i, i) = 1 (Diagonal is all 1s) M(i, i+1) = 1 (Diagonal just above the main diagonal is all 1s) M(i, i-1) = -1 (Diagonal just below the main diagonal is all -1s) All the other elements of M are 0 Example for k = 4 would be: 1 1 0 0 -1 1 1 0 0 -1 1 1 0 0 -1 ...
import time arr=[0]*(100000+6) sp=[2]*(100000+6) sp[1]=1 sp[0]=0 def generateSP(n): for i in range(3,n+1,2): #print(i) #print(arr[i]) if arr[i]==0: arr[i]=1 #print("y"+str(i)) sp[i]=i j=i while j*i<=n: if arr[j*i]==0...
Nowadays out little Chef is traveling a lot. While traveling, on one unlucky day, he lost into a mysterious country. Nearby people handed little Chef to the King for investigations. After proper investigation they found little Chef innocent. Little Chef had no money with him to return to his country Byteland, so the Ki...
for I in range(input()): x=raw_input().split() a=long(x[0]) b=long(x[1]) sum=0 if b==1: print a continue while a!=0: sum+=a%b a/=b print sum
To test a new cloud computing service, you decide to write a program that generates the Pascal Triangle in a distributed fashion. You wish to estimate the amount of network traffic that would be expected between nodes. Since the nodes exchange the computed values in base 10, you want to know the number of digits in the...
#BISMILLAH #NCRAAS import operator as op import math T=raw_input() T=int(T) while T > 0 : s=raw_input().split(' ') n=int(s[0]) m=int(s[1]) value = math.factorial(n)/math.factorial(m)/math.factorial(n-m) print int(math.log(value,10))+1,int(math.log(value,2))+1 T-=1
Andrii is good in Math, but not in Programming. He is asking you to solve following problem: Given an integer number N and two sets of integer A and B. Let set A contain all numbers from 1 to N and set B contain all numbers from N + 1 to 2N. Multiset C contains all sums a + b such that a belongs to A and b belongs to B...
n,q = map(int,raw_input().split()) half=(1+(n+1)+n+(2*n))/2 for i in range(0,q): inp = input() diff = abs(half-inp) if(inp<(1+(n+1)) or inp>(n+(2*n))): print "0" elif(inp==half): print(n) else: print(n-diff)
The following is an easy game that the setter of this problem played when he was 8: A boatman, a wolf, a sheep, and a cabbage are on the bank of a river. They have a small boat that is capable of carrying the boatman and at most one other animal/item with him. However, if left alone by the boatman, the wolf can eat the...
for t in xrange(input()): n,m=map(int,raw_input().split()) arr=[] for i in range(m): arr+=map(int,raw_input().split()) if m>=3: print 'NO' elif m==2: arr=set(arr) if len(arr)<4:print 'YES' else:print 'NO' e...
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are r...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 7; char stk[maxn]; int dp[maxn], sid[maxn], fl[maxn]; string s; int main() { std::ios::sync_with_stdio(false); int n, k, top = 0; cin >> n >> k; cin >> s; for (int i = 0; i < s.size(); ++i) { stk[top] = s[i]; sid[top++] = i; whil...
There is an array a of 2^{30} integers, indexed from 0 to 2^{30}-1. Initially, you know that 0 ≤ a_i < 2^{30} (0 ≤ i < 2^{30}), but you do not know any of the values. Your task is to process queries of two types: * 1 l r x: You are informed that the bitwise xor of the subarray [l, r] (ends inclusive) is equal to x. ...
#include <bits/stdc++.h> using namespace std; namespace ufs { int fa[400005]; int w[400005]; void makeset(int n) { for (int i = 1; i <= n; i++) fa[i] = i; } int findset(int x) { if (fa[x] == x) return x; int t = findset(fa[x]); w[x] ^= w[fa[x]]; return fa[x] = t; } void merge(int u, int v, int ty) { swap(u,...
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the en...
#include <bits/stdc++.h> using namespace std; int N; void add(int x, int y, vector<vector<int>>& cnt, vector<pair<int, int>>& pos) { if (x < 0 || x >= N || y < 0 || y >= N) return; cnt[x][y]++; if (cnt[x][y] >= 4) { cnt[x][y] = -100; pos.push_back({x, y}); } } bool simulate(vector<pair<int, int>> pos) {...
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th...
#include <bits/stdc++.h> using namespace std; int main() { int i, k; char s[7], c[7], d[7]; scanf("%s", s); c[0] = s[0]; c[1] = s[1]; c[2] = '\0'; d[0] = s[4]; d[1] = s[3]; d[2] = '\0'; int b = 0; for (i = 1; i >= 0; i--) { b = b * 10 + c[i]; } int f = 0; for (i = 3; i <= 4; i++) { f...
You are given an undirected weighted connected graph with n vertices and m edges without loops and multiple edges. The i-th edge is e_i = (u_i, v_i, w_i); the distance between vertices u_i and v_i along the edge e_i is w_i (1 ≤ w_i). The graph is connected, i. e. for any pair of vertices, there is at least one path be...
#include <bits/stdc++.h> using namespace std; const int N = 500007; int n, m; int fa[N]; struct node { int u, v, w; bool operator<(const node &t) const { return w < t.w; } } G[N]; int Find(int x) { return x == fa[x] ? x : fa[x] = Find(fa[x]); } void Merge(int x, int y) { x = Find(x), y = Find(y); if (x != y) fa...
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monument...
#include <bits/stdc++.h> using namespace std; const long long N = 1e5 + 5, MOD = 1e9 + 7; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); long long n, m, a[1005][1005], maxr[1005], maxc[1005]; unordered_map<long long, long long> r[1005], c[1005]; signed main() { ios_base::sync_with_stdio(false); ...
You are given a permutation p of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once). Let's call some subsegment p[l, r] of this permutation special if p_l + p_r = max _{i = l}^{r} p_i. Please calculate the number of special subsegments. Input The first line contain...
#include <bits/stdc++.h> using namespace std; const int N = 200043; int lf[N]; int rg[N]; int n; int ans = 0; int p[N]; int q[N]; void update(int l, int r, int l2, int r2, int sum) { for (int i = l; i <= r; i++) { int o = sum - p[i]; if (o >= 1 && o <= n && l2 <= q[o] && q[o] <= r2) ans++; } } int main() { ...
You are given a rooted tree on n vertices. The vertices are numbered from 1 to n; the root is the vertex number 1. Each vertex has two integers associated with it: a_i and b_i. We denote the set of all ancestors of v (including v itself) by R(v). The awesomeness of a vertex v is defined as $$$\left| ∑_{w ∈ R(v)} a_w...
#include <bits/stdc++.h> #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") #pragma GCC target( \ "sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native") using namespace std; const int MN = 1000005, inf = 1000000005, mod = 1000000007; const l...
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which * two planks of length at least k+1 — the base of the ladder; * k planks of length at least 1 — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example...
T = int(input()) for t in range(T): N = int(input()) Arr = list(map(int, input().split())) Arr.sort(reverse=True) M = min(Arr[0], Arr[1]) if (len(Arr) == 1 or M-1 == 0): print(0) else: print(min(len(Arr)-2, M-1))
There are b boys and g girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and n participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya ...
#include <bits/stdc++.h> int value(int boy, int girl, int game) { int b; int r; int sum; b = 0; r = 0; sum = 0; while (b <= boy) { while (r <= girl) { if (b + r == game) sum++; else if (b + r > game) break; r++; } r = 0; b++; } return (sum); } int main...
Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of n tracks numbered from 1 to n. The playlist is automatic and cyclic: whenever track i finishes playing, track i+1 starts playing automatically; after track n goes track 1. For each track i, you...
#include <bits/stdc++.h> using namespace std; const double PI = acos(-1.0); const long long INF = 1e9 + 47; const long long LINF = INF * INF; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N = 1 << 19; int n; int a[N]; int ans[N]; int t[N << 1]; void build(int v, int tl, int tr) { if (...
Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm. His farm is presented by a rectangle grid with r rows and c columns. Some of these cells contain rice, others are empty. k chickens are living on his farm. The number of chicken...
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for(int Case = 0; Case < t; Case++){ int r, c, k; r = scanner.nextInt(); c = scanner.nextInt(); ...
Santa has to send presents to the kids. He has a large stack of n presents, numbered from 1 to n; the topmost present has number a_1, the next present is a_2, and so on; the bottom present has number a_n. All numbers are distinct. Santa has a list of m distinct presents he has to send: b_1, b_2, ..., b_m. He will send...
for _ in range(int(input())): n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) rec = {} for i in range(n): rec[a[i]] = i # print(rec) ans = 0 lim = 0 for i in range(m): if rec[b[i]] > lim: ans += 2*(r...
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan...
#include <bits/stdc++.h> using namespace std; int main() { int n, s = 0, x1 = 0, x2 = 0, y; cin >> n; for (int i = 1; i <= n; i++) { cin >> y; s += y; if (y % 2 == 0) x2++; else x1++; } if (s % 2 == 0) cout << x2; else cout << x1; }
A popular reality show is recruiting a new cast for the third season! n candidates numbered from 1 to n have been interviewed. The candidate i has aggressiveness level l_i, and recruiting this candidate will cost the show s_i roubles. The show host reviewes applications of all candidates from i=1 to i=n by increasing ...
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T &x) { x = 0; char c = getchar(); bool flag = false; while (!isdigit(c)) { if (c == '-') flag = true; c = getchar(); } while (isdigit(c)) { x = (x << 1) + (x << 3) + (c ^ 48); c = getchar(); } if (flag)...
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi...
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class test { public static void main (String[] args) throws java.lang.Exception { int t; Scanner sc=new Scanner(System.in); ...
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: * Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree...
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-->0) { int n = sc.nextInt(); int x = sc.nextInt(); int deg[] = new int[n+1]; for(int i=0; i<n-1;...
Koa the Koala has a binary string s of length n. Koa can perform no more than n-1 (possibly zero) operations of the following form: In one operation Koa selects positions i and i+1 for some i with 1 ≤ i < |s| and sets s_i to max(s_i, s_{i+1}). Then Koa deletes position i+1 from s (after the removal, the remaining part...
#include <bits/stdc++.h> using namespace std; mt19937 rnd(239); const long long MOD = 1e9 + 7; const int N = 1e6 + 239; long long dp[N]; long long sum[N]; int solve() { string s; if (!(cin >> s)) return 1; vector<long long> a; int cur = 0; for (int i = 0; i < ((int)((s).size())); i++) { if (s[i] == '1') {...
A brick is defined as a rectangle with integer side lengths with either width 1 or height 1 (or both). There is an n× m grid, and each cell is colored either black or white. A tiling is a way to place bricks onto the grid such that each black cell is covered by exactly one brick, and each white cell is not covered by ...
#include <bits/stdc++.h> using namespace std; int n, m; int fi[80004], ne[80004 << 4], to[80004 << 4], c[80004 << 4], num = 1; void add(int x, int y, int z) { ne[++num] = fi[x]; fi[x] = num; to[num] = y; c[num] = z; ne[++num] = fi[y]; fi[y] = num; to[num] = x; c[num] = 0; } int dep[80004], q[80004], l, ...
Masha has n types of tiles of size 2 × 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type. Masha decides to construct the square of size m × m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ...
def check(flst, size): if size <= 0: return "NO" elif size % 2 == 0: for each in flst: if each[1] == each[2]: return "YES" return "NO" else: return "NO" tsts = int(input()) for i in range(tsts): init = input().split(" ") types = int(init[0...
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their h...
def findmax(arr): idx = 0 for i in range(len(arr)): if arr[i]> arr[idx]: idx = i return idx def findmin(arr): idx = len(arr)-1 for i in range(len(arr)-1,-1,-1): if arr[i] < arr[idx]: idx = i return idx x = int(input()) arr = list(map(int,input().split(" ")...
You have an array a_1, a_2, ..., a_n. All a_i are positive integers. In one step you can choose three distinct indices i, j, and k (i ≠ j; i ≠ k; j ≠ k) and assign the sum of a_j and a_k to a_i, i. e. make a_i = a_j + a_k. Can you make all a_i lower or equal to d using the operation above any number of times (possibl...
#include<bits/stdc++.h> using namespace std; int t,n,x,y,d,z,p; int main(){ for(scanf("%d",&t);t;t--){ scanf("%d%d",&n,&d); x=y=1e9;p=0; for(int i=0;i<n;i++){ scanf("%d",&z); if(z>d)p=1; if(x>z)y=x,x=z; else if(y>z)y=z; } puts(x+y<=d||!p?"YES":"NO"); } return 0; }
Let's say you are standing on the XY-plane at point (0, 0) and you want to reach point (n, n). You can move only in two directions: * to the right, i. e. horizontally and in the direction that increase your x coordinate, * or up, i. e. vertically and in the direction that increase your y coordinate. In othe...
for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) best = float("inf") mn = [float("inf")] * 2 sm = [0] * 2 for i in range(n): mn[i%2] = min(mn[i%2], arr[i]) sm[i%2] += arr[i] best = min(best, sm[0]+mn[0]*(n-i//2-1) + sm[1]+mn[1]*(n-(i-1)...
Nastia has 2 positive integers A and B. She defines that: * The integer is good if it is divisible by A ⋅ B; * Otherwise, the integer is nearly good, if it is divisible by A. For example, if A = 6 and B = 4, the integers 24 and 72 are good, the integers 6, 660 and 12 are nearly good, the integers 16, 7 are ne...
for _ in range(int(input())) : a,b = list(map(int,input().split())) if b == 1 : print("NO") else : if b == 2 : b = 4 print( "YES" ) print( a, a*(b-1), a*b )
Let's call an array a consisting of n positive (greater than 0) integers beautiful if the following condition is held for every i from 1 to n: either a_i = 1, or at least one of the numbers a_i - 1 and a_i - 2 exists in the array as well. For example: * the array [5, 3, 1] is beautiful: for a_1, the number a_1 - 2...
/**Bismillahir Rahmanir Rahim.**/ #include<bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long long int ll; typedef long double ld; #define Faster ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define pi acos(-1) #defin...
Paul Erdős's prediction came true. Finally an alien force landed on the Earth. In contrary to our expectation they didn't asked the humans to compute the value of a Ramsey number (maybe they had solved it themselves). They asked another question which seemed as hard as calculating Ramsey numbers. Aliens threatened that...
#include <bits/stdc++.h> using namespace std; int n, m; string b[2048], s; int idx[2048]; pair<int, int> dp[2048][2048]; vector<int> ps[2048][32]; int suf[2048][32]; int get_pos(int ix, int lo, char ch) { const int c = ch - 'a'; return *lower_bound(ps[ix][c].begin(), ps[ix][c].end(), lo); } int get_ix(int lo, char ...
You've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class PlateGame { public static void main(String args [] ) throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); StringTo...
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query ...
#include <bits/stdc++.h> inline int sbt(int x) { return __builtin_popcount(x); } using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { ...
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an. Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar. Polycarpus took a piece of...
#include <bits/stdc++.h> using namespace std; const int MX = 25; int ans[1 << 20]; int main(int argc, char *argv[]) { int n; cin >> n; int val; int last[20]; for (int i = (0), _b = (20); i < (_b); ++i) last[i] = -1; for (int i = (0), _b = (n); i < (_b); ++i) { cin >> val; if (!val) { ans[0] = ...
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive. Input Input contains one integer number n (1 ≤ n ≤ 3000). Output Output the amount ...
# ALMOST PRIME # Estacio Pereira, estacio.neto@ccc.ufcg.edu.br # UFCG # INPUT number = int(raw_input()) # PROCESS prime = 0 div = 2 divi = [] num = number numero = number almost = 0 while num != 1: prime = 0 div = 2 divi = [] while num != 1: if not num % div and not div in divi: prime += 1 num /= div d...
The problem uses a simplified TCP/IP address model, please read the statement carefully. An IP address is a 32-bit integer, represented as a group of four decimal 8-bit integers (without leading zeroes), separated by commas. For example, record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1...
#include <bits/stdc++.h> using namespace std; int a[10], N, need[10], used[10]; set<string> answer; char cur[15]; void scan() { cin >> N; for (int i = 0; i < N; ++i) { cin >> a[i]; need[a[i]] = 1; } } string toIp(string &str, int t1, int t2, int t3) { string res; for (int i = 0; i < str.size(); ++i) {...
Smart Beaver became interested in drawing. He draws suns. However, at some point, Smart Beaver realized that simply drawing suns is boring. So he decided to design a program that will process his drawings. You are given a picture drawn by the beaver. It will have two colors: one for the background and one for the suns ...
import java.util.*; import java.io.*; public class Suns { FastScanner in; PrintWriter out; int[] di = new int[] { 1, 0, -1, 0 }; int[] dj = new int[] { 0, 1, 0, -1 }; boolean feet(int i, int j, int[][] a) { return i >= 0 && j >= 0 && i < a.length && j < a[0].length; } int[][] erosion(int[][] a) { int[][]...
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on. Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-...
import java.sql.Time; import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class MainTest { static void print(int a[]) { for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void print(long a[]) { for(int i=0;i...
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" ...
s = input() n = len(s) l = [] i = 0 while i<n: j = i+1 while j<n and s[j]==s[i]: j+=1 if (j-i)==1: l.append(s[i]) i+=1 continue l.append(s[i]) l.append(s[i]) k = j+1 while k<n and s[k]==s[j]: k+=1 if j<n: l.append(s[j]) i = k print("".j...
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi. To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.StringTokenizer; @SuppressWarnings("unused") public class A { public static FastScann...
We'll call a sequence of integers a good k-d sequence if we can add to it at most k numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference d. You got hold of some sequence a, consisting of n integers. Your task is to find its longest contiguous subsegment, such that...
#include <bits/stdc++.h> using namespace std; struct seg_tree { int sign[210000 * 4], minn[210000 * 4]; void add(int p, int l, int r, int x, int y, int k) { int mid = (l + r) / 2; if (x <= l && y >= r) { sign[p] += k; minn[p] += k; return; } if (x <= mid) add(p * 2, l, mid, x, y, k...
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has n groups of people. The i-th group from the beginning has ...
#include <bits/stdc++.h> using namespace std; const int N = 111111; int n, m, k, a[N], ans, cnt; int main() { cin >> n >> m; for (int i = 1; i <= n; ++i) cin >> a[i]; a[n + 1] = (int)1e9; for (int i = 1; i <= n + 1; ++i) { cnt += a[i]; if (cnt > m) ++ans, cnt = a[i]; } cout << ans; return 0; }
You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest am...
import java.util.List; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.math.BigInteger; import java.util.Collections; import java.io.InputStream...
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers...
n = int(input()) t = [] for i in range(1, 32): t.append(i * (i + 1) / 2) print('YES' if n in t else 'NO')
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the secon...
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] D = new int[N]; int[] X = new int[N]; Queue<Integer> queue = new LinkedList<I...
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? No...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; pair<int, int> arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i].first; cin >> arr[i].second; } sort(arr, arr + n); int size = 1; int co = arr[0].first; int we = arr[0].second; long long val = co + we; priority_q...
Let's define the permutation of length n as an array p = [p1, p2, ..., pn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on. Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a...
#include <bits/stdc++.h> using namespace std; long long k, fib[66]; int n; int main() { scanf("%d%I64d", &n, &k); fib[0] = 1LL; fib[1] = 1LL; for (int i = 2; i <= n; ++i) { fib[i] = fib[i - 2] + fib[i - 1]; } int out = 1; for (int i = n; i > 0; --i) { if (k <= fib[i - 1]) { printf("%d ", out...
Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thu...
#include <bits/stdc++.h> using namespace std; int main() { cout << fixed; cout.precision(9); int n, x1, y1, x2, y2; cin >> n >> x1 >> y1 >> x2 >> y2; int res = 1000000; if (x1 == x2 && (x1 == 0 || x1 == n)) { res = min(res, abs(y1 - y2)); } if (y1 == y2 && (y1 == 0 || y1 == n)) { res = min(res, ...
You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour. Input The first line contains three integers a, b, m (1 ≤ a, b ≤ 1000, 0 ≤ m ≤ 105), a is the size of the first part, b is the size ...
#include <bits/stdc++.h> using namespace std; const int Nmax = 1005, Mmax = 1e5 + 5; int n, m, edges, i, C = 0, x, y; int color[Mmax], edge[Mmax][2], go1[Nmax][Nmax], go2[Nmax][Nmax], grad1[Nmax], grad2[Nmax]; void swap_colors1(int node, int c1, int c2); void swap_colors2(int node, int c1, int c2); void swap_colors...
Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals. A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: a...
#include <bits/stdc++.h> const int N = 100000 + 10; int n; struct Point { int x, y; inline bool operator<(const Point &rhs) const { return x != rhs.x ? x < rhs.x : y < rhs.y; } } point[N]; struct Info { int min, max; Info() : min(INT_MAX), max(INT_MIN) {} Info(int _x) : min(_x), max(_x) {} Info(int _m...