input
stringlengths
29
13k
output
stringlengths
9
73.4k
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m l...
// daniel kim import java.util.*; import java.io.*; // dijkstra public class cf20c { static long INF = Long.MAX_VALUE; static int V, E; static List<Node>[] adj; static long[] dist; static int[] pre; public static void main(String[] args) throws Exception { // Scanner in = new Scanner(new File("in"));...
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum: <image> Find the sum modulo 1073741824 (230). Input The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 2000). Output Print a sing...
#include <bits/stdc++.h> using namespace std; long long dp[(int)1e6 + 5]; long long factorize(long long n) { if (dp[n] != -1) return dp[n]; long long ans = 0; for (long long i = 1; i * i <= n; i++) { if (n % i == 0) { if (i * i != n) ans += 2; else ans++; } } dp[n] = ans; ...
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right. Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting ...
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.FileReader; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.File; import java.io.Wri...
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: 1. Add the integer xi to the first ai elements of the sequence. 2. Append an integer ki to the end of the sequenc...
import java.lang.*; import java.util.*; public class C{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); double total = 0; int memSum= 0; int n = sc.nextInt(); int[] seq = new int[n+1]; int[] mem = new int[n+1]; int len = 1 ; for(int i=0;i<n;i++){ int op = sc.nextInt() ;...
You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine. We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some...
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); int n, m; cin >> n >> m; vector<int> mems; for (int i = 0; i < n; i++) { int a; cin >> a; mems.push_back(a); } sort(mems.begin(), mems.end()); vector<int> need(40); for (int i = 0; i < m; i++) { int...
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl...
n = input() s = raw_input() ans = 0 l = len(s) if l < 4: print 0 else: for i in range(n,l,n): if s[i-2]==s[i-3] and s[i-1]==s[i-2]: ans+=1 print ans
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to: 1. dr(n) = S(n), if S(n) < 10; 2. dr(n) = dr( S(n) ), i...
k,d=map(int,input().split()) if(k==1 and d==0): print(0) elif(d==0): print("No solution") else: print(str(d)+('0'*(k-1)))
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided t...
import sys n = input() wallets = map(int,raw_input().split(" ")) total = sum(wallets) while True: for i in xrange(n-1): if wallets[i]!=0: wallets[i]-=1 total -= 1 sys.stdout.write('P') if total==0: break sys.stdout.write('...
In a Berland city S*** there is a tram engine house and only one tram. Three people work in the house — the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly c minutes to complete the route. The head...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:16000000") using namespace std; const int Maxn = 100005; int n, m; vector<int> neigh[Maxn]; int tim[Maxn]; int getCycle(int v, int t) { if (tim[v] != -1) return t - tim[v]; tim[v] = t; for (int i = 0; i < neigh[v].size(); i++) { int cand = getCycle(neig...
Let's assume that set S consists of m distinct intervals [l1, r1], [l2, r2], ..., [lm, rm] (1 ≤ li ≤ ri ≤ n; li, ri are integers). Let's assume that f(S) is the maximum number of intervals that you can choose from the set S, such that every two of them do not intersect. We assume that two intervals, [l1, r1] and [l2, ...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int N = 505; int f[2][N][N], p_2[N]; int main() { auto pow = [&](int a, int n) { int ans = 1; for (; n; n >>= 1, a = a * 1ll * a % mod) if (n & 1) ans = ans * 1ll * a % mod; return ans; }; auto add = [&](int &x, int y) ...
School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are i...
n, m = map(int , raw_input().split()) a = [0 for i in range(300)] for i in range(m): l, r = map(int , raw_input().split()) for j in range(l, r + 1): a[j] += 1 for i in range(1, n + 1): if a[i] != 1: print i, a[i] quit() print "OK"
During the last 24 hours Hamed and Malek spent all their time playing "Sharti". Now they are too exhausted to finish the last round. So they asked you for help to determine the winner of this round. "Sharti" is played on a n × n board with some of cells colored white and others colored black. The rows of the board ar...
#include <bits/stdc++.h> using namespace std; const int N = 100100; struct node { int x, l, r, t; node(int x = 0, int l = 0, int r = 0, int t = 0) : x(x), l(l), r(r), t(t) {} bool operator<(const node& a) const { return x < a.x; } } a[N]; int tag[N * 60], sm[N * 60], lc[N * 60], rc[N * 60], q1, q2, q3, clk; void ...
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh...
n=int(input()) l=list(map(int,input().split())) l.sort() s=0 c=0 for i in l: if(i>=s): c=c+1 s=s+i print(c)
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains t...
na,nb=map(int,input().split()) k,m=map(int,input().split()) a=[int(z)for z in input().split()] b=[int(z)for z in input().split()] print("YNEOS"[a[k-1]>=b[-m]::2]) # Interesting. --YKF
Bogdan has a birthday today and mom gave him a tree consisting of n vertecies. For every edge of the tree i, some number xi was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, m guests consecutively come to Bogdan's party. When the i-th guest co...
#include <bits/stdc++.h> using namespace std; struct node { long long u, v, w; } edge[200005]; long long n, m; vector<pair<long long, long long> > G[200005]; long long dep[200005], fa[200005], val[200005]; long long f[200005][21]; void makeSet() { for (long long i = 1; i <= n; i++) fa[i] = i; } long long find(long ...
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hed...
from sys import stdin,stdout,setrecursionlimit setrecursionlimit(10**5) from collections import defaultdict nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) PI=float('inf') def dfs(src): vis[src]=1 for neigh in g[src]: if neigh<src: if not vis[neigh]...
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d. Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes ...
#include <bits/stdc++.h> using namespace std; long long x[200007]; long long p[200007]; vector<pair<long long, long long> > v; set<pair<long long, long long> > s; set<pair<long long, long long> >::iterator it; int main() { long long d, n, lst, fst, ans = 0, temp; int m; cin >> d >> n >> m; for (int i = 0; i < m...
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Amo...
#include <bits/stdc++.h> int n; char s[20]; int a[20]; long long int powt[15]; long long int rem[15]; long long int f(int len) { if (len == 1) { if (a[0] == 9) return 1989; return 1990 + a[0]; } long long int sy = f(len - 1); while (1) { sy += powt[len - 1]; if (sy % powt[len] == rem[len - 1]) {...
Today Pari gave Arya a cool graph problem. Arya wrote a non-optimal solution for it, because he believes in his ability to optimize non-optimal solutions. In addition to being non-optimal, his code was buggy and he tried a lot to optimize it, so the code also became dirty! He keeps getting Time Limit Exceeds and he is ...
#include <bits/stdc++.h> const int MAX_N = 5123; const int inf = (int)1e9 + 123; using namespace std; int n, m; vector<int> g[MAX_N], first[MAX_N]; vector<int> st; bool u[MAX_N]; int cl[MAX_N]; vector<int> v[MAX_N], q[MAX_N]; void dfs(int v) { u[v] = 1; for (auto to : g[v]) if (!u[to]) dfs(to); st.push_back(v...
Once a walrus professor Plato asked his programming students to perform the following practical task. The students had to implement such a data structure that would support a convex hull on some set of points S. The input to the program had q queries of two types: 1. Add a point with coordinates (x, y) into the set...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; const int INF32 = 0x3f3f3f3f; const long long INF64 = 0x3f3f3f3f3f3f3f3f; const long long mod = 1e9 + 7; const double PI = acos(-1.0); const double EPS = 1.0e-8; struct Point { double x, y, t, d; Point(double _x = 0, double _y = 0, double _t =...
Berland consists of n cities and m bidirectional roads connecting pairs of cities. There is no road connecting a city to itself, and between any pair of cities there is no more than one road. It is possible to reach any city from any other moving along roads. Currently Mr. President is in the city s and his destinatio...
import java.io.*; import java.util.*; public class RoadOrientation { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void writeLabels(Node v) { if (v == null) { return; } writeLabels(v.l); label[v.id] = ptr++; writeLabels(v.r); } static class Node { Node l, r, up; int s...
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co...
import sys n = int(input()) for m in range(1, 1001): for j in range(2, 1001): if j < (n * m + 1) and (n * m + 1) % j == 0: print(m) sys.exit(0)
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1. Watson gave Sherlock a challenge to color these jewelry pieces such that t...
#include <bits/stdc++.h> using namespace std; int main() { long long int n, k = 1; cin >> n; if (n == 1) { cout << "1\n1"; } else if (n == 2) { cout << "1\n1 1"; } else { vector<bool> isprime(n + 2, true); vector<long long int> A(n + 2, 1); for (int i = 2; i <= n + 1; i++) { if (ispr...
A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist. Input The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corres...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b, long long& x, long long& y) { if (!b) { x = 1; y = 0; return a; } long long ans = gcd(b, a % b, x, y); int temp = x; x = y; y = temp - a / b * y; return ans; } int main() { long long a, b, c, d, x, y; cin...
Mister B has a house in the middle of a giant plain field, which attracted aliens life. For convenience, aliens specified the Cartesian coordinate system on the field in such a way that Mister B's house has coordinates (0, 0). After that they sent three beacons to the field, but something went wrong. One beacon was com...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 3; const int SQRT = 320; const int MOD = 1e9 + 7; const int INF = MOD; const long double PI = 3.141592653589793; const long double EPS = 1e-6; int sieve[2 * maxn]; long long n[4]; long long m[4]; long long s[4]; vector<pair<int, int>> ss; vector<pair<...
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the ar...
#include <bits/stdc++.h> using namespace std; const long long int N = 1000001; const long long int M = 1; vector<int> v[N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int _ = 1; while (_--) { long long int n, x = 0, y = 0, ans = 0, z; cin >> n; long long int a[n]...
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with ...
#include <bits/stdc++.h> using namespace std; const int mod = 1e6; const int maxn = 100000 + 10; bool vis[100]; int main() { int a, b, c, t1, t2; scanf("%d%d%d%d%d", &a, &b, &c, &t1, &t2); for (int i = 0; i < 10; i++) ; for (int i = 0; i < 10; i++) ; for (int i = 0; i < 10; i++) ; for (int i = 0...
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: * There are y elements in F, and all of them are integer numbers; * <image>. You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two array...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const double eps = 1e-5; const int maxn = 2e6 + 5; const int inf = 0x3f3f3f3f; const long long linf = 0x3f3f3f3f3f3f3f3f; const double PI = acos(-1); const int Times = 11; long long qpow_mod(long long a, long long b, long long c) { long long...
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se...
n,pos,l,r = [int(i) for i in input().split()] time_l = 0; if l != 1: time_l += abs(pos - l) + 1 # move to l and delete pos1 = l else: pos1 = pos if r != n: time_l += abs(r-pos1) + 1 # move to r and delete time_r = 0; if r != n: time_r += abs(pos - r) + 1 # move to l and delete pos1 = r else: ...
Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m × m of this matrix contains at least one zero. Consider the following problem: You are given two integers n and m. You have to construct an m-free square matrix of size n × n such that...
#include <bits/stdc++.h> using namespace std; int main() { int t; scanf("%d", &t); for (int i = 0; i < t; i++) { int q; scanf("%d", &q); if (q == 0) { printf("1 1\n"); continue; } int n = 0, m = 0, ch = 0, x = 1; for (int i = 1; i <= sqrt(q); i++) { if (q % i) continue; ...
A rectangle with sides A and B is cut into rectangles with cuts parallel to its sides. For example, if p horizontal and q vertical cuts were made, (p + 1) ⋅ (q + 1) rectangles were left after the cutting. After the cutting, rectangles were of n different types. Two rectangles are different if at least one side of one r...
#include <bits/stdc++.h> using namespace std; const int Maxn = 200005; int n; map<long long, map<long long, long long> > M; map<long long, long long> byrow, bycol; int res; long long gcd(long long a, long long b) { return a ? gcd(b % a, a) : b; } pair<long long, long long> Rat(long long a, long long b) { long long g ...
You have to handle a very complex water distribution system. The system consists of n junctions and m pipes, i-th pipe connects junctions x_i and y_i. The only thing you can do is adjusting the pipes. You have to choose m integer numbers f_1, f_2, ..., f_m and use them as pipe settings. i-th pipe will distribute f_i u...
import sys from time import time t1 = time() #sys.setrecursionlimit(300000) def i_ints(): return list(map(int, sys.stdin.readline().split())) def main(): limit =10**10 n, = i_ints() s = [0] + i_ints() if sum(s): print("Impossible") return print("Possible") if n ==...
You are given the following recurrences, F(n) = a * F(n - 1) * G(n - 2) + b * G(n - 1) * F(n - 2) for n ≥ 2 G(n) = c * G(n - 1) * F(n - 2) + d * (3 ^ F(n - 1) ) for n ≥2 H(n) = e * F(n) + f * G(n) for n ≥ 0 F[0] = F[1] = G[0] = 0 G[1] = 1 Input First line contains the following 6 numbers in order : a, b, c, d, ...
from math import * a,b,c,d,e,f = map(int,raw_input().split()) q=input() for i in range(q): t = input() if (t==0): print(0) elif (t==1): print(f) else: print((f*(1+(t-1)*d))%1000000007)
Chandu is a very strict mentor. He always gives a lot of work to his interns. So his interns decided to kill him. There is a party in the office on Saturday Night, and the interns decided to kill him on the same day. In the party, there are N beer bottles. Each bottle has a integer X written on it. Interns decided to m...
import math def no_of_factors(x): i=1 c=0 sqrtx=int(math.ceil(x**0.5)) if (math.sqrt(x)-int(math.sqrt(x)))>0.0: c=0 while i<sqrtx: if x%i==0: c+=2 if c==4: return c i+=1 else: c=-1 while i<=sqrtx: if x%i==0: c+=2 if c==4: return c ...
Sona is in-charge of inviting the guest. She don't know how much far they are from her place. She knows the guest house co-ordinates (gx,gy)and the co-ordinates of the place where she is standing(sx,sy). Help her to calculate the distance between the guest house and her place. Input First line contains guest house c...
import math one=list(map(int,raw_input().split(" "))) two=list(map(int,raw_input().split(" "))) print "%.5f" % math.sqrt(pow(two[0]-one[0],2)+pow(two[1]-one[1],2))
Today is the first class after a long vacation and as always Bagha woke up late. His friend, Nathumama has a motorcycle which they can use to reach class on time. However, Nathumama doesn't have enough fuel to reach class so Bagha makes a magic machine which can regenerate the fuel after travelling for some kilometers....
r=input() l=[] while r!=0: k=0 q=raw_input() q=q.split() b =int(q[1]) a=int(q[0]) j = 0 while a!=0: b=b-2 j = j +2 a = a-1 if j==6: a=a+2 j = 0 if b<=0: l.append("Yes") else: l.append("No") r = r-1 for a in l: print a
A list of names is taken as input, in which a particular name can occur multiple times. You need to arrange these names as they will appear in the dictionary and also print the number of times the arranged names appear in the list taken as input. Input: The first line of input contains an integer, t, which denotes th...
n = int(raw_input()) name = [] for i in range(n): name.append(raw_input()) name.sort() c = 1 i = 0 while i < n: pos = i+1 while i < n and pos < n and name[i] == name[pos]: c+=1 pos+=1 print name[i] , c i = pos c = 1
Our monk, while taking a stroll in the park, stumped upon a polynomial ( A X^2 + B X +C ) lying on the ground. The polynomial was dying! Being considerate, our monk tried to talk and revive the polynomial. The polynomial said: I have served my purpose, and shall not live anymore. Please fulfill my dying wish. Find m...
__author__ = 'ankur' def get_lowest_x(a, b, c, k): answer = -1 low = 0 high = 100000 if c >= k: return 0 while low <= high: mid = low + (high - low) / 2 left_side = (a * (mid * mid)) + (b * mid) + c if left_side >= k: answer = mid; high = mid...
Given an array A of N elements, find the number of distinct possible sums that can be obtained by taking any number of elements from the array and adding them. Note that 0 can always be obtained by taking none. First line of the input contains number of test cases T. Each test case has two lines. First line has N, t...
def possibleSums(n,elems): sums = sum(elems) dp = [[False] * (sums+1) for _ in xrange(n)] dp[0][0] = True dp[0][elems[0]] = True for i in xrange(1,n): for j in xrange(sums+1): dp[i][j] = dp[i-1][j] or (dp[i-1][j-elems[i]] if j - elems[i] >= 0 else False) return sum(dp[n-1]) def main(): ntests =...
See Russian Translation ZYX is a famous international-level linguistics and informatics competitor. He is the favorite to win this year's IOI competition. Fifiman, another great coder in his own right, known as the "King of Algorithms", was unfortunately overshadowed by ZYX's outstanding ability many times in various...
from sys import stdin INPUT = stdin.readlines() # N = number of countries # M = number of direct flights class DisjointPartition: ''' Union-find structure for maintaining disjoint sets ''' class Position: __slots__ = '_container', '_element', '_size', '_parent' def __init__(self, container, e): self._con...
Median of K numbers is defined as the (K/2)th smallest number, if K is even; and the ((K+1)/2)th smallest number if K is odd. For example, median of the 4 numbers: 2 1 8 7 is the 2nd smallest number i.e. 2, and the median of the 5 numbers: 2 1 8 7 6 is the 3rd smallest number i.e. 6. In this problem, you'll be g...
import bisect def median(nums, k): K = k + 1 return nums[(K/2)-1] if K % 2 == 0 else nums[((K+1)/2)-1] numbers = [int(raw_input()) for num in xrange(int(raw_input()))] sorted_numbers = [] median_sum = 0 for k, number in enumerate(numbers): bisect.insort(sorted_numbers, number) median_sum += median(sor...
Walter and Jesse's friend Mike had helped them in making Crymeth and hence, they wanted to give him a share. For deciding the share, they both decided to choose one number each, X and Y and found out that K^th Highest Common Factor of their two numbers is a good amount of Crymeth that can be given to Mike . Walter and ...
from fractions import gcd import math for _ in xrange(int(raw_input())): a,b,d=map(int,raw_input().split()); A=[]; q=gcd(a,b); s=int(math.sqrt(q)); for i in xrange(1,s+1): if q%i==0: A.append(i); A.append(q/i); if s*s==q: A.pop() A.sort(reverse=True); if len(A)<d: print "No crymeth today" else: print ...
We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is `.`, and black if c_{i,j} is `#`. Consider doing the following operation...
import java.util.*; import static java.lang.Math.*; class Main { final Scanner sc = new Scanner(System.in); public static void main(String[] args) { new Main().run(); } private void run() { int h = sc.nextInt(); int w = sc.nextInt(); int k = sc.nextInt(); Strin...
Snuke has a string s. From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows: * Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with `?`s. For example, if s is `mississippi`, we can choose the su...
def match(ch1, ch2): return ch1 == ch2 or ch1 == '?' or ch2 == '?' def solve(): MAXLEN = 2000 a = raw_input() b = raw_input() c = raw_input() lA = len(a); lB = len(b); lC = len(c) MAXLEN = max(lA, lB, lC) ab = [True for i in range(10*MAXLEN)] ac = [True for i in range(10*MAXLEN)] ...
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print `Yes`; if it cannot, print `No`. Constraints * 1 \leq N \leq 100 * N is an int...
import java.util.*; import java.util.stream.*; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(IntStream.range(1, 10).anyMatch(i -> n % i == 0 && n / i <= 9) ? "Yes" : "No"); } }
There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares. Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it. The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and...
import java.util.*; import java.lang.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int h = sc.nextInt(); int w = sc.nextInt(); String[] s = new String[h]; for (int i = 0; i < h; i++) { s[i] = sc.next(); } int[][] u = new int[h][w]; int[][] r = n...
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board. The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns. How many ways are there to choose where ...
N = int(input()) H = int(input()) W = int(input()) if H > N or W > N: print(0) else: print((N-W+1)*(N-H+1))
You are given a string S of length 2N consisting of lowercase English letters. There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition? * The string obtained by reading the characters painted red from left to right is equal to the string obtained by r...
def f(): n=int(input()) s=list(input()) a,b=s[n-1::-1],s[n:] from collections import defaultdict ad=defaultdict(int) bd=defaultdict(int) for i in range(2**n): sa,ta,sb,tb="","","","" for j in range(n): if i%2: sa+=a[j] sb+=b[j] ...
AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number. Constraints * 1 ≤ a,b ≤ 100 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the concatenation of a and b in this o...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); sc.close(); int num = a * (int)Math.pow(10, (int)Math.log10(b)+1) + b; int sqrt = (int)Math.sqrt(num); if(num == sqrt * sqrt) Syst...
You've come to your favorite store Infinitesco to buy some ice tea. The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply...
#include <iostream> #include <algorithm> using namespace std; int main() { long long q, h, s, d, n; cin >> q >> h >> s >> d >> n; cout << min({4 * q * n, 2 * h * n, s * n, n / 2 * d + min({4 * q, 2 * h, s}) * (n % 2)}); return 0; }
You are given an integer N. For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B. For example, F(3,11) = 2 since 3 has one digit and 11 has two digits. Find the minimum value of F...
#include<iostream> using namespace std; int main() { long long n; cin >> n; int ans = 10; for(long long i = 1; i*i <= n; i++) { if(n%i != 0) continue; if(to_string(n/i).size() < ans) ans = to_string(n/i).size(); } cout << ans << endl; return 0; }
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white. Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po...
w,h,n=map(int,input().split()) x1=0 y1=0 for i in range(n): x,y,a=map(int,input().split()) if a==1: x1=max(x1,x) elif a==2: w=min(w,x) elif a==3: y1=max(y,y1) elif a==4: h=min(h,y) print((w-x1)*(h-y1) if w > x1 and h > y1 else 0)
There is a plane like Figure 1 with 8 vertical and 8 horizontal squares. □ | □ | □ | □ | □ | □ | □ | □ --- | --- | --- | --- | --- | --- | --- | --- □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □...
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String[] shikaku = new String[8]; for (int i = 0; i < 8; i++) { shikaku[i] = sc.next(); } int x = 0; int y = 0; ...
There is Kannon-do in the mountain behind Ichiro's house. There are 30 steps from the foot to this Kannon-do, and Ichiro goes to Kannon-do almost every day. Ichiro can go up the stairs up to 3 steps with one foot. While playing, I noticed that there are so many types of stair climbing (the number of steps to skip). So...
#include<bits/stdc++.h> using namespace std; int main(){ while(1){ int n=0; cin>>n; if(n==0)break; int p[45]={0}; p[0]=1; p[1]=1; p[2]=2; for(int i=3;i<=30;i++){ p[i]=p[i-1]+p[i-2]+p[i-3]; } cout<<(p[n]/3650)+1<<endl; }...
Aiz, which is located in cyberspace, trades information with Wakamatsu. The two countries are developing their economies by exchanging useful data with each other. The two countries, whose national policy is philanthropy and equality, and above all, the old word of the Aizu region, "what must be done", conducts regular...
#include<cstdio> #include <iostream> #include<algorithm> #include<string> #include<queue> #include<vector> #include<functional> #include<cmath> #include<map> #include<stack> #include<set> #include<numeric> #define rep(i,n) for(int i=0; i<int(n); i++) using namespace std; typedef long long ll; typedef pair<int,int> P; ...
Taro decided to go to the summer festival held at JOI Shrine. N night shops are open along the way to JOI Shrine. Each night shop is numbered from 1 to N in order, and the fun of playing and the time it takes to play are determined by integers. The fun of playing at night shop i is Ai, and the time it takes to play at...
#include <bits/stdc++.h> #define FOR(i,n) for(int i=0;i<(int)(n);i++) #define FORR(i,m,n) for(int i=(int)(m);i<(int)(n);i++) #define pb(a) push_back(a) #define mp(x,y) make_pair(x,y) #define ALL(a) a.begin(),a.end() #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,-1,sizeof(a)) #define len(a) sizeof(a) #...
Problem KND is a student programmer at the University of Aizu. He is both a programmer and a fighter. He is known to be a sweet tooth, but he especially likes fresh cream. Eating fresh cream will allow you to break the concrete wall several times. Interested in its power, his neighbor decided to experiment with a new ...
#include <cstdio> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <list> #include <queue> #include <stack> #include <set> #include <map> #include <bitset> #include <numeric> #include <climits> #include <cfloat> using namespace ...
Your mission in this problem is to write a computer program that manipulates molecular for- mulae in virtual chemistry. As in real chemistry, each molecular formula represents a molecule consisting of one or more atoms. However, it may not have chemical reality. The following are the definitions of atomic symbols and ...
#include <bits/stdc++.h> using namespace std; #define LOG(...) fprintf(stderr, __VA_ARGS__) //#define LOG(...) #define FOR(i, a, b) for (int i = (int)(a); i < (int)(b); ++i) #define RFOR(i, a, b) for (int i = (int)(b - 1); i >= (int)(a); --i) #define REP(i, n) for (int i = 0; i < (int)(n); ++i) #define RREP(i, n) for...
Example Input 2 5 6 1000000000 2 Output 4 5 6 0 6 0 0 5 0 3 1000000000 0 0 2 999999999 0
#include <set> #include <map> #include <ctime> #include <cmath> #include <queue> #include <bitset> #include <cstdio> #include <string> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define lowbit(x) (x&(-x)) #define PII pair<LL,LL> #define FOR(i,a,b) for (LL i=(a);i...
ICPC Calculator In mathematics, we usually specify the order of operations by using parentheses. For example, 7 × (3 + 2) always means multiplying 7 by the result of 3 + 2 and never means adding 2 to the result of 7 × 3. However, there are people who do not like parentheses. International Counter of Parentheses Counci...
#include<bits/stdc++.h> using namespace std; #define rep(i,n) for(long long int i=0;i<n;++i) typedef long long int ll; int dfs(vector<string> a,int id){ int ret; if(a[id].back()=='*'){ ret=1; for(int i=id+1;i<a.size();i++){ if(a[id].size()+1==a[i].size()){ if(a[i].ba...
A TV program called "Saizo" is popular in a certain country. In this program, participants challenge field athletics and get a prize if they successfully capture it. Field athletics are made by arranging blocks of different heights in a row, and how to climb up and down the steps is important for capture (Fig. 1). You...
#include <iostream> #include <algorithm> using namespace std; int main(){ int T; cin >> T; while(T--){ int N, prev, maxup = 0, maxdown = 0; cin >> N >> prev; while(--N){ int height; cin >> height; if(prev < height){ maxup = max(maxup, height - prev); }else{ maxdown = max(maxdown, prev - h...
This is a city where the ground is a square of regular hexagons. Each square is represented by two integers as shown in the figure below. <image> The cat is about to go to the square (0, 0). The mischievous black rabbit knew this and decided to get in the way of the cat. The black rabbit can jump to the square with ...
#include <iostream> #include <cstdio> #include <cassert> #include <cstring> #include <vector> #include <valarray> #include <array> #include <queue> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <algorithm> #include <cmath> #include <complex> #include <random> #include <bitset>...
The full exploration sister is a very talented woman. Your sister can easily count the number of routes in a grid pattern if it is in the thousands. You and your exploration sister are now in a room lined with hexagonal tiles. The older sister seems to be very excited about the hexagon she sees for the first time. The ...
#include <iostream> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <utility> #include <queue> #define inf 1000000000 using namespace std; typedef pair<int, int> P; typedef pair<P, int> State; typedef pair<int, State> QState; struct edge{ int to, cost; edge(){} edge(int a, int b){ to = a, cost ...
JAG-channel Nathan O. Davis operates an electronic bulletin board called JAG-channel. He is currently working on adding a new feature called Thread View. Like many other electronic bulletin boards, JAG-channel is thread-based. Here, a thread refers to a group of conversations consisting of a series of posts. There ar...
#ifndef _WIN32 #include<iostream> #endif #include<string> #include<vector> #include<algorithm> #include<queue> #include<string.h> using namespace std; #define FOR(i,bg,ed) for(int i=(bg);i<(ed);i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() typedef vector<string> VS; VS wrap(VS v,char c) { int ...
A-Aun's breathing Problem Statement Maeda-san and Goto-san, who will both turn 70 years old in 2060, are long-time friends and friends who fought together at the ACM-ICPC in college. The two are still excited about competitive programming, drinking tea together. When the two of us drank tea together, Mr. Maeda said...
#include<bits/stdc++.h> #define rep(i,n)for(int i=0;i<n;i++) using namespace std; int main() { int n; scanf("%d", &n); int cnt = 0; rep(i, n) { string s; cin >> s; if (s == "A")cnt++; else cnt--; if (cnt < 0)break; } puts(cnt ? "NO" : "YES"); }
problem AOR Ika made a set $ S = \\ {a_1, ..., a_N \\} $ and a map $ f: S → S $. $ f (a_i) = b_i $. For any element $ x $ in the set $ S $, all maps $ g, h: S → S $ satisfying $ g (f (x)) = h (f (x)) $ are $ g (x). ) = Determine if h (x) $ is satisfied, and if not, configure one counterexample. Example Input 5 ...
#include <bits/stdc++.h> #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i<int(b);++i) #define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__) #define _rrep(i,n) _rrange(i,n,0) #define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i) #define r...
Problem Chocolate company Chinor Choco has decided to build n new stores. For each store, ask each store manager to prepare two candidates for the place you want to build, and build it in either place. Chinor Choco sells m types of chocolate, each manufactured at a different factory. All types of chocolate are sold a...
#include<bits/stdc++.h> using namespace std; struct StronglyConnectedComponents { vector< vector< int > > gg, rg; vector< pair< int, int > > edges; vector< int > comp, order, used; StronglyConnectedComponents(size_t v) : gg(v), rg(v), comp(v, -1), used(v, 0) {} void add_edge(int x, int y) { gg[x].pu...
Let's arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1. Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubbl...
def selection_sort(numbers, n, key=lambda x: x): """selection sort method Args: numbers: a list of numbers to be sorted n: len(numbers) key: sort key Returns: sorted numberd, number of swapped times """ x = [] for data in numbers: x.append(data) cou...
You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room. For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth fl...
a= [[[0]*10 for i in range(3)] for j in range(4)] n = int(input()) for i in range(n): b,f,r,v = map(int,input().split()) a[b-1][f-1][r-1] += v for i in range(4): for j in range(3): for k in range(10): print(" " + str(a[i][j][k]),end='') print() if i != 3: print("#"...
The chef is preparing a birthday cake for one of his guests, and his decided to write the age of the guest in candles on the cake. There are 10 types of candles, one for each of the digits '0' through '9'. The chef has forgotten the age of the guest, however, so doesn't know whether he has enough candles of the right t...
def main(): t=int(raw_input()) for _ in range(t): candles=[int(i) for i in raw_input().split()] if min(candles[1:])==0: print(candles[1:].index(0)+1) else: op="" if min(candles)<min(candles[1:]): op+="1" for __ in range(...
POINTS - 25 Sahil is very fond of drinking juice. Every morning he drinks one full bottle of Juice. In every 'm' days, his mother buys one more bottle of juice ( i.e. on day m, 2m, 3m). She buys it in the evening. If Sahil initially has 'n' bottles of juice calculate the number of consecutive days that pass before he r...
n,m=map(int,raw_input().split()) counter=0 while(n!=0): counter+=1 n-=1 if counter%m==0: n+=1 print counter
Chef has learned a new technique for comparing two recipes. A recipe contains a list of ingredients in increasing order of the times they will be processed. An ingredient is represented by a letter 'a'-'z'. The i-th letter in a recipe denotes the i-th ingredient. An ingredient can be used multiple times in a recipe. Th...
import sys def main(): for (r, s) in testcases(): if pseudo_granama(r, s): print "NO" else: print "YES" def testcases(cin = sys.stdin): nc = int(cin.next()) for _ in xrange(nc): r, s = cin.next().split() yield (r, s) def pseudo_granama(r, s): r, s = list(r), list(s) r.sort(); s....
Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams. Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering...
t = int(raw_input()) while t: N,K = map(int,raw_input().split()) L = [int(i) for i in raw_input().split()]; L.sort() m = max(K,N-K); print sum(L[-m:]) - sum(L[:-m]) t-=1
A rank list is a list of ranks of persons in a programming contest. Note that some of the persons might be having same rank. {1, 2}, {1, 2, 2} and {1, 1, 2, 3, 4, 4} are few examples of rank lists whereas {1, 3}, {0, 2}, {1, 2, 4} are not rank lists. Also note that a rank list need not to be sorted e.g. {2, 2, 1} and {...
t = input() it = 0 while (it < t): s = raw_input() s1 = s.split(" ") n = int(s1[0]) s = int(s1[1]) #print n, s if (s == (n*(n+1))/2): print "0" it += 1 continue s -= n for i in range(1,n): if ((s < ((n-i)*(n-i+1))/2) & (s >= ((n-i-1)*(n-i))/2) ): print i break it += 1
You all must know Walter White, from Breaking Bad who created the world’s purest crystal meth. As he is a school teacher, he has to attend school regularly. But Walter does not want to go to school, rather he wants to stay home and create new kinds of drugs. In the office where Walter works, has two guards who count ho...
t=input() for _ in xrange(t): a,b=map(int,raw_input().split()) print max(a,b),(a+b)
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider...
#include <bits/stdc++.h> using namespace std; const int maxn = int(1e3) + 10; const int maxm = 1005; int Left[maxn][maxm], Right[maxn][maxm], up[maxn][maxm], down[maxn][maxm]; int cnt[maxn][maxn]; char str[maxn][maxn]; char s[maxn][maxn]; int n, m; int a[maxn][maxm]; int c[maxn][maxm]; int top = 0; int lowbit(int x) { ...
The Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms speci...
#include <bits/stdc++.h> using namespace std; map<long long, vector<pair<long long, long long>>> m1; vector<long long> used; vector<vector<long long>> g; const long long inf = 1e9 + 7; void dfs(long long v, long long timer) { used[v] = timer; for (auto u : g[v]) { if (used[u] != timer) dfs(u, timer); } } long...
There are n cities in the country. Two candidates are fighting for the post of the President. The elections are set in the future, and both candidates have already planned how they are going to connect the cities with roads. Both plans will connect all cities using n - 1 roads only. That is, each plan can be viewed a...
#include <bits/stdc++.h> using namespace std; int read() { int r = 0, t = 1, c = getchar(); while (c < '0' || c > '9') { t = c == '-' ? -1 : 1; c = getchar(); } while (c >= '0' && c <= '9') { r = (r << 3) + (r << 1) + (c ^ 48); c = getchar(); } return r * t; } namespace run { int n, r1, r2, ...
The Fair Nut has found an array a of n integers. We call subarray l … r a sequence of consecutive elements of an array with indexes from l to r, i.e. a_l, a_{l+1}, a_{l+2}, …, a_{r-1}, a_{r}. No one knows the reason, but he calls a pair of subsegments good if and only if the following conditions are satisfied: 1. ...
#include <bits/stdc++.h> #pragma GCC target("avx") #pragma GCC optimize(3) #pragma GCC optimize("Ofast") #pragma GCC optimize("inline") #pragma GCC optimize("-fgcse") #pragma GCC optimize("-fgcse-lm") #pragma GCC optimize("-fipa-sra") #pragma GCC optimize("-ftree-pre") #pragma GCC optimize("-ftree-vrp") #pragma GCC opt...
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it. You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: fi...
#include <bits/stdc++.h> using namespace std; const int maxn = 16; const int maxm = 1e4 + 5; const int inf = 1e9 + 5; int n, m, a[maxn][maxm], cost[maxn][maxn]; void enter() { cin >> n >> m; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> a[i][j]; for (int i = 0; i < n; ++i) { for (int j = ...
Consider the following problem: given an array a containing n integers (indexed from 0 to n-1), find max_{0 ≤ l ≤ r ≤ n-1} ∑_{l ≤ i ≤ r} (r-l+1) ⋅ a_i. In this problem, 1 ≤ n ≤ 2 000 and |a_i| ≤ 10^6. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it....
#include <bits/stdc++.h> using namespace std; const int MAX = 1e6; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; int k; cin >> k; int goal = k + 2, S = 0; vector<int> ans; ans.push_back(-1); while (1) { if (S + MAX >= goal) { ans.push_back(goal - S); break; ...
Student Dima from Kremland has a matrix a of size n × m filled with non-negative integers. He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him! Formally, he wants to choose an integers sequence c_1, c_2, …...
n, m = map(int, input().split()) a = [[int(i) for i in input().split()] for _ in range(n)] t = a[0][0] for i in range(1, n): t ^= a[i][0] if t != 0: print("TAK") print(' '.join('1' for i in range(n))) else: for i in range(n): for j in range(1, m): if a[i][j] != a[i][0]: ...
Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul...
x, y, z = [int(x) for x in input().split()] if x == y and z == 0: print(0) elif x > y + z: print("+") elif y > x + z: print("-") else: print("?")
There are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area. The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be ...
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip import random import collections import math import itert...
This is an easier version of the next problem. In this version, q = 0. A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible num...
#include <bits/stdc++.h> using namespace std; int n, q; int a[200005]; int b[200005]; int l[200005]; int r[200005]; int cnt[200005]; int check[200005]; int ans; int main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); cin >> n >> q; int i, j; for (i = 1; i <= n; i++) cin >> a[i]; for (i = 1; i ...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
lucky_numbers = [4, 7, 44, 77, 47, 74, 444, 447, 474, 744, 777, 774, 747, 477] n = input() lucky = True for i in range(0, len(n)): if n[i] != '4' and n[i] != '7' : lucky = False break if lucky: print("YES") else: lucky = False for i in lucky_numbers: if int(n) % i == 0: ...
You are given n integers a_1, a_2, ..., a_n, such that for each 1≤ i ≤ n holds i-n≤ a_i≤ i-1. Find some nonempty subset of these integers, whose sum is equal to 0. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them. Input E...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.charset.Charset; import java.util.StringTokenizer; import ja...
[INSPION FullBand Master - INSPION](https://www.youtube.com/watch?v=kwsciXm_7sA) [INSPION - IOLITE-SUNSTONE](https://www.youtube.com/watch?v=kwsciXm_7sA) On another floor of the A.R.C. Markland-N, the young man Simon "Xenon" Jackson, takes a break after finishing his project early (as always). Having a lot of free ti...
#include <bits/stdc++.h> using namespace std; const int maxn = 3000 + 50; vector<int> edge[maxn]; int sub[maxn][maxn], fa[maxn][maxn]; long long n, ans, dp[maxn][maxn]; void dfs(int root, int k, int dad) { sub[root][k]++; fa[root][k] = dad; for (auto t : edge[k]) { if (t != dad) { dfs(root, t, k); ...
Being Santa Claus is very difficult. Sometimes you have to deal with difficult situations. Today Santa Claus came to the holiday and there were m children lined up in front of him. Let's number them from 1 to m. Grandfather Frost knows n spells. The i-th spell gives a candy to every child whose place is in the [L_i, R...
#include <bits/stdc++.h> #pragma GCC optimize(2) using namespace std; int n, m, k, dp[300], trans[300], id[10]; vector<pair<pair<int, int>, int> > v; signed main() { ios::sync_with_stdio(false); cin >> n >> m >> k; for (int i = 1; i <= n; i++) { int l, r; cin >> l >> r; v.push_back(make_pair(make_pair...
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, ...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeSet; /...
Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the n consecutive months — in the i-th month the company had income equal to a_i (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the f...
import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) x = int(input()) chg = [0] for i in range(n//2): chg.append(x-a[i]) for i in range(1, n//2+1): chg[i] += chg[i-1] for i in range(1, n//2+1): chg[i] = min(chg[i], chg[i-1]) pref = sum(a) for k in range((n+1)//2, ...
Acacius is studying strings theory. Today he came with the following problem. You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulti...
import sys import os from io import BytesIO, IOBase # credits of fastio to PyRival project in Github(https://github.com/cheran-senthil/PyRival) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() ...
Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A paren...
// package com.company; import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class EN5 { static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] Args)throws Exception{ FastReader scan=n...
As you may already know, Dušan is keen on playing with railway models. He has a big map with cities that are connected with railways. His map can be seen as a graph where vertices are cities and the railways connecting them are the edges. So far, the graph corresponding to his map is a tree. As you already know, a tree...
#include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; bool flg = false; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') flg = true; for (; isdigit(ch); ch = getchar()) x = (x << 3) + (x << 1) + (ch ^ 48); return flg ? -x : x; } int S; int n, k; struct Rec ...
We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the r...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; const long long mod = 998244353; int a[maxn], aa[maxn]; bool used[maxn]; int b[maxn]; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; memset(used, 1, sizeof(used)); used[0] = used[n + 1] = false; for (...
Consider a long corridor which can be divided into n square cells of size 1 × 1. These cells are numbered from 1 to n from left to right. There are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the a-th cell, the guard is in the b-th cell (a ≠ b). <image> One of the poss...
import java.io.*; import java.util.*; import java.util.Map.Entry; public class D { FastScanner in; PrintWriter out; boolean systemIO = true; public class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair clone() { return new Pai...
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: s of length n and t of length m. A sequence p_1, p_2, …, p_m, where 1 ≤ p_1 < p_2 < … < p_m ≤ n, is called beautiful, if s_{p_i} = t_i for all i from 1 to m. The width of a sequence is defined as max_{1 ...
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; //import javafx.util.*; public final class B { static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<ArrayList<Integer>> g,lang; static long mod=1000000007; static int D1[],...
To satisfy his love of matching socks, Phoenix has brought his n socks (n is even) to the sock store. Each of his socks has a color c_i and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: * recolor a sock to any color c' (1 ≤ c' ≤ n) * turn a left sock into a right ...
from collections import defaultdict t = int(input()) while t!=0: t=t-1 n,l,r = map(int,input().split()) list1 = list(map(int,input().split())) d1 = defaultdict(int) d2 = defaultdict(int) for i in range(l): d1[list1[i]]+=1 for i in range(l,n): d2[list1[i]]+=1 for ...
Let f(i) denote the minimum positive integer x such that x is not a divisor of i. Compute ∑_{i=1}^n f(i) modulo 10^9+7. In other words, compute f(1)+f(2)+...+f(n) modulo 10^9+7. Input The first line contains a single integer t (1≤ t≤ 10^4), the number of test cases. Then t cases follow. The only line of each test c...
#include <stdio.h> #define MD 1000000007 long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } int main() { int t; scanf("%d", &t); while (t--) { long long n, a, b, ans; scanf("%lld", &n); ans = n, b = 1; for (a = 1; a <= n; a++) { b *= a / gcd(a, b); if (b > n) break...