input
stringlengths
29
13k
output
stringlengths
9
73.4k
Indiana Jones found ancient Aztec catacombs containing a golden idol. The catacombs consists of n caves. Each pair of caves is connected with a two-way corridor that can be opened or closed. The entrance to the catacombs is in the cave 1, the idol and the exit are in the cave n. When Indiana goes from a cave x to a ca...
#include <bits/stdc++.h> using namespace std; vector<int> g[300010], ans, rec; set<pair<int, int>> edge; int n, m, u, v; int dis[300010], fa[300010], in[300010]; int cls[300010], vis[300010]; void dfs(int u) { rec.push_back(u); vis[u] = 1; for (int v : g[u]) if (!vis[v]) dfs(v); } int main() { scanf("%d %d"...
Consider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to ai ml per second (this amount may be a real number). The water delivered by i-th tap has temperature ti. If for every <image> you set i-th tap to deliver exactly xi ml of ...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 7; long long n, T, t[N], x[N], sa, sb; long double ans; vector<pair<long long, long long> > a, b; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> T; for (int i = 0; i < n; i++) cin >> x[i]; for (int i = 0; i < ...
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one gro...
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b);...
In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terribl...
#include <bits/stdc++.h> using namespace std; long long f[505][505]; int main() { int n, k; scanf("%d%d", &n, &k); for (int i = 0; i <= n; i++) f[0][i] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { for (int k = 0; k < j; k++) { (f[j][i] += f[k][i - 1] * f[j - k - 1][i - 1]...
bhargav has dream to study his MS is foreign country. So, He started his preparation for GRE. There are huge number of words that he has to prepare for. So, firs he wanted to group all synonyms and antonyms. As there are huge number of words that he has to group. So, he asked help to group all synonyms and antonyms of ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' s=raw_input() n=input() a=0 sy=0 for i in range(n): s1=raw_input() if s1[0]==s[0] and len(s1)==len(s): sy+=1 if chr(ord(s[0])+3)==s1[0] and len(s1)==len(s): ...
Raghu wants to design a converter such that when a user inputs a binary number it gets converted to Octal number & also the correspond alphabet to it. Example- if a user inputs- 10101101 then the output is 255 BEE Note : for decimal places there should be a space between the alphabetic signs Ex- for input 1011011011...
bindict = {'000':0,'001':1,'010':2,'100':4,'101':5,'110':6,'111':7,'011':3} binary = raw_input().split('.') for index,value in enumerate(binary): arr = [] if(index==0): while(len(value)%3!=0): value='0'+value j = 1 i = 0 while(j<=len(value)): if(j%3==0...
After decrypting the code Enigma crew came to know that there are N locations where bombs has been planted. X1, X2 …. Xn are the N locations. Among this locations, one X location is the central hub which control all the other Xn-1 location. 1 or more than 1 signal is send to N locations. The decrypted code simplified ...
def isPrime(num): if num == 0 or num == 1: return False if num == 2: return True if num % 2 == 0: return False i = 3 while i <= num**0.5+1: if num%i == 0: return False i = i+2 return True t = int(raw_input()) Arr = map(int, raw_input().strip().split(' ')) mx = -1 for i in Arr: #print i, isPrim...
You are given a string of lower case letters. Your task is to figure out the index of the character on whose removal it will make the string a palindrome. There will always be a valid solution. In case the string is already a palindrome, then -1 is also a valid answer along with possible indices. Input Format The fi...
for _ in range(input()): strn = raw_input().strip() le = len(strn) if le < 3: print "0" continue index = 0 f = 1 while index < le / 2: if strn[index] == strn[-1-index]: index+=1 else: f = 0 break if f == 1: print "-...
Mattey has an assignment that he should submit tomorrow. The assignment has one question which asks to write a program to multiply two numbers without using ''* operator. As Mattey finds no interest in this subject, he never listens to classes and so do not know about shift operators. He comes to you to learn about th...
T=int(raw_input()) while T>0: sd=list() n=list(raw_input().split()) pro=int(n[0])*int(n[1]) c=0 x=int(n[0]) y=int(n[1]) s=x rem=1 # c=num-1 while y!=0: te=y%2 sd.extend(str(te)) y=y/2 c=c+1 # print sd[0] me=0 c=c-1 while c >= 0:...
There are N boxes .The i^th box contains ai candies . The frog Om Nom is sitting in box number 1 .Om Nom wants to collect as many candies as he can . However , Om Nom jumps in a peculiar fashion . Om Nom can jump from box number j to box number i only if j | i (j divides i) . Whenever Om Nom lands in a box , he collect...
import math n=input() alist=map(int,raw_input().split()) track=[alist[i]+alist[0] for i in range(n)] track[0]-=alist[0] for i in range(2,int(n/2)+2): x=i+i while x<=n: track[x-1]=max(track[x-1],track[i-1]+alist[x-1]) x+=i for i in track: print i,
Codex is about to start and Ram has not done dinner yet. So, he quickly goes to hostel mess and finds a long queue in front of food counter. But somehow he manages to take the food plate and reaches in front of the queue. The plates are divided into sections such that it has 2 rows and N columns. Due to the crowd Ram...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' from math import factorial def ncr(n,r): if(n<0 or r<0): return 0 elif(n<r): return 0 else: return factorial(n)/(factorial(r)*factorial(n-r)) t = input() for i in range(0,t): ...
PROBLEM SPECIFICATION: You are given three positive integers 'n' , 'a' and 'b' . In the given range from 1 to 'n' how many distinct numbers are completely divisible by 'a' or 'b' or both? NOTE: The range includes both 1 and 'n'. INPUT SPECIFICATION: You will be given 't' test cases. Each test case will contain three ...
def lcm(x, y): if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm t = int(raw_input()) for j in range(t): c = 0 n,a,b = tuple(map(int,raw_input().split())) ...
As Gudi escapes the room and moves onto to the next floor, the Wizard of UD receives her at the gate! The wizard questions her intelligence and does not allow her to move ahead unless she answers his puzzle correctly. The wizard says : Imagine that you are trapped in a dungeon, little girl . And the gate to the exit i...
#!/usr/bin/env python #-*- coding:utf-8 -*- import sys, math, random, operator #from string import ascii_lowercase #from string import ascii_uppercase from fractions import Fraction, gcd from decimal import Decimal, getcontext from itertools import product, permutations, combinations from Queue import Queue, PriorityQ...
Tak performed the following action N times: rolling two dice. The result of the i-th roll is D_{i,1} and D_{i,2}. Check if doublets occurred at least three times in a row. Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold. Constraints * 3 \...
n=int(input()) ans=0 flg=0 aa="No" for _ in range(n): a,b=map(int,input().split()) if a==b: ans+=1 else: ans=0 if ans==3: aa="Yes" print(aa)
There is a cave. The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside. It is dark in th...
from collections import deque N,M=map(int,input().split()) G=[ [] for _ in range(N) ] for i in range(M): A,B=map(int,input().split()) A-=1 B-=1 G[A].append(B) G[B].append(A) searched=[0]*N searched[0]=1 ans=[-1]*N d=deque() d.append(0) while(len(d)!=0): tmp=d.popleft() for g in G[tmp]: if searched[g]...
Niwango created a playlist of N songs. The title and the duration of the i-th song are s_i and t_i seconds, respectively. It is guaranteed that s_1,\ldots,s_N are all distinct. Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, w...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); String[] S = new String[N]; int[] t = new int[N]; for (int i = 0; i < N; i++) { S[i] = in.next(); t[i] = in.nextInt(); } String X = in.next(); int in...
We have a grid with N rows and M columns of squares. Each integer from 1 to NM is written in this grid once. The number written in the square at the i-th row from the top and the j-th column from the left is A_{ij}. You need to rearrange these numbers as follows: 1. First, for each of the N rows, rearrange the number...
#include <bits/stdc++.h> #define clr(x) memset(x,0,sizeof x) #define For(i,a,b) for (int i=(a);i<=(b);i++) #define Fod(i,b,a) for (int i=(b);i>=(a);i--) #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define fi first #define se second #define outval(x) cerr<<#x" = "<<x<<endl #define outtag(x) cerr<<"--------...
You are given three integers A, B and C. Determine if there exists an equilateral triangle whose sides have lengths A, B and C. Constraints * All values in input are integers. * 1 \leq A,B,C \leq 100 Input Input is given from Standard Input in the following format: A B C Output If there exists an equilateral ...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int A = scanner.nextInt(); int B= scanner.nextInt(); ...
Amidakuji is a traditional method of lottery in Japan. To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical l...
H,W,K = map(int,input().split()) dp = [] for i in range(H+1): L = [0]*W dp.append(L) fb = [1,1] for i in range(W-2): fb.append(fb[i]+fb[i+1]) dp[0][0] = 1 if W != 1: for i in range(1,H+1): for j in range(W): if 1 <= j <= W-2: dp[i][j] = dp[i-1][j-1]*fb[j-1]*fb[W-j-1]+dp[i-1][j]*fb[j]*fb[W-j-1]...
Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams o...
N,X = map(int, input().split()) M = [int(input()) for _ in range(N)] X = X - sum(M) print(N + X//min(M))
Ringo has a tree with N vertices. The i-th of the N-1 edges in this tree connects Vertex A_i and Vertex B_i and has a weight of C_i. Additionally, Vertex i has a weight of X_i. Here, we define f(u,v) as the distance between Vertex u and Vertex v, plus X_u + X_v. We will consider a complete graph G with N vertices. Th...
#include<cstdio> #include<queue> #include<vector> #include<algorithm> using namespace std; typedef long long ll; struct edge { ll x,y; bool operator<(const edge&z)const { return x>z.x||(x==z.x&&y<z.y); } }h,v; struct edge2 { ll x,y,z; }e[400005]; ll n,i,x,y,z,tot=0,ev[3][400005],dsu[200005],dis[400005],pre[40000...
AtCoDeer has three cards, one red, one green and one blue. An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card. We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer. Is this integer...
#include <iostream> using namespace std; int main(){ int r,g,b; cin>>r>>g>>b; int a=10*g+b; if(0==a%4){ cout<<"YES"; }else{ cout<<"NO"; } }
There are N people, conveniently numbered 1 through N. They were standing in a row yesterday, but now they are unsure of the order in which they were standing. However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the nu...
#include<cstdio> using namespace std; typedef long long ll; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < n; i++) int n, a[100000]; int c[100000]; ll mod_pow(ll x, int n){ if(n == 0) return 1; return x * mod_pow(x, n - 1) % MOD; } ll solve(){ rep(i, n){ if(!(n ^ (a[i] & 1))) return 0; if(a[i]...
For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows: * f(b,n) = n, when n < b * f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b, and n \ {\rm mod} \ b denotes the remainder of n div...
n=int(input()) s=int(input()) b_ans=1 if n==s: b_ans=n+1 if b_ans==1: for b in range(2,int(n**0.5)+1): nn=n st=[] while(nn>0): st.append(nn%b) nn=(nn-st[-1])/b if sum(st)==s: b_ans=b break if b_ans==1: for p in range(int(n**0.5),0,-1): b=(n-s+p)/p if b.is_i...
A smelt fishing tournament was held at Lake Hibara. It seems that catch and release is recommended this time. Create a program that reads the participant number and the number of fish caught or released in order as one event, and outputs the participant number and the number of animals that have acquired the most smel...
#include <iostream> #include <algorithm> #include <map> #include <vector> #include <queue> using namespace std; typedef long long lli; typedef pair<int,int> T; const int MAXN = 1000006; const int INF = 1<<29; class RMQ { private: int n; T dat[4*MAXN-1]; public: void init(int _n = MAXN, T a = T(INF,INF)) { ...
In Aizuwakamatsu Village, which is located far north of Aizuwakamatsu City, a bridge called "Yabashi" is the only way to move to the surrounding villages. Despite the large number of passers-by, the bridge is so old that it is almost broken. <image> Yabashi is strong enough to withstand up to 150 [kg]. For example,...
#include<bits/stdc++.h> #define rep(i,n)for(ll i=0;i<n;i++) using namespace std; typedef long long ll; ll m[100], a[100], b[100]; int main() { ll n; while (scanf("%lld", &n), n) { vector<ll>v; rep(i, n) { scanf("%lld%lld%lld", &m[i], &a[i], &b[i]); v.push_back(a[i]); } for (ll i : v) { ll cnt = 0; ...
Alice is spending his time on an independent study to apply to the Nationwide Mathematics Contest. This year’s theme is "Beautiful Sequence." As Alice is interested in the working of computers, she wants to create a beautiful sequence using only 0 and 1. She defines a "Beautiful" sequence of length $N$ that consists on...
#include <iostream> #include <vector> #include <iostream> using namespace std; using int64 = long long int; const int64 MOD = 1000000007; int64 mod_pow(int64 A, int64 k) { int64 res = 1; for(; k>0; k>>=1) { if(k & 1) (res *= A) %= MOD; (A *= A) %= MOD; } return res; } int64 dp[100010]; int main() { ...
In 2215 A.D., a war between two planets, ACM and ICPC, is being more and more intense. ACM introduced new combat planes. These planes have a special system that is called Graze, and fighting power of a plane increases when it is close to energy bullets that ICPC combat planes shoot. Both combat planes and energy bull...
//32 #include<iostream> #include<vector> #include<utility> using namespace std; typedef pair<int,int> pii; #define S(X) ((X)*(X)) int main(){ for(int a,b,r;cin>>a>>b>>r,a|b|r;){ int x[100000],y[100000]; for(int i=0;i<a;i++){ cin>>x[i]>>y[i]; } vector<pii> v[250][250]; for(int i=0;i<b;i++...
Pablo Squarson is a well-known cubism artist. This year's theme for Pablo Squarson is "Squares". Today we are visiting his studio to see how his masterpieces are given birth. At the center of his studio, there is a huuuuuge table and beside it are many, many squares of the same size. Pablo Squarson puts one of the squ...
import sys import collections while True: N = int(sys.stdin.readline()) if N == 0: break pos = {0:(0, 0)} for i in xrange(N - 1): n, d = map(int, sys.stdin.readline().split()) if d == 0: pos[i + 1] = (pos[n][0] - 1, pos[n][1]) elif d == 1: ...
"Balloons should be captured efficiently", the game designer says. He is designing an oldfashioned game with two dimensional graphics. In the game, balloons fall onto the ground one after another, and the player manipulates a robot vehicle on the ground to capture the balloons. The player can control the vehicle to mov...
#include <bits/stdc++.h> using namespace std; // よこ, たて vector<pair<int, int>> v; int ok=100000000; int ng=-1; void msearch(int i, int p, int bn, int t, int x, int move){ if(move<ok){ if(i==v.size()){ if(ok>move+x){ ok=move+x; } }else if(x==0){ if...
Taro had his own personal computer and set a password for login. However, Taro inadvertently forgot the password. Then, remembering that there was a piece of paper with the password written down, Taro found the paper and was surprised to see it. The paper was cut and there were only fragments, and there were some stain...
#include<bits/stdc++.h> using namespace std; #define lint long long #define P pair<int, int> #define LLP pair<long long, long long> #define REP(i, x, n) for(int i = (x), i##_len = (int)(n) ; i < i##_len ; ++i) #define rep(i, n) for(int i = 0, i##_len = (int)(n) ; i < i##_len ; ++i) #define repr(i, n) for(int i = (int)...
Brian Jones is an undergraduate student at Advanced College of Metropolitan. Recently he was given an assignment in his class of Computer Science to write a program that plays a dealer of blackjack. Blackjack is a game played with one or more decks of playing cards. The objective of each player is to have the score of...
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws Exception { // BufferedReader stdIn = new BufferedReader(new FileReader(new // File("c:\\2024-input.txt"))); BufferedReader stdIn =...
You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T: * M v: (Mark) Mark node v. * Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root no...
def root(x): while P[x] != x: x = P[x] return x def mark(x): P[x-1] = x-1 def query(x): v = root(x-1) +1 return v while True: N,Q = map(int,input().strip().split(" ")) if N == Q == 0: break P = [] P.append(0) for i in range(N-1): p_i = int(input().strip()...
International Carpenters Professionals Company (ICPC) is a top construction company with a lot of expert carpenters. What makes ICPC a top company is their original language. The syntax of the language is simply given in CFG as follows: S -> SS | (S) | )S( | ε In other words, a right parenthesis can be closed by a...
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <cfloat> #include <ctime> #include <cassert> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <functional> #include...
1 Problem Statement There is a bit string of length n. When the i-th bit from the left is 1, the score is a_i points. The number of 1s within the distance w around the i-th bit from the left (= | \\ {j \ in \\ {1, ..., n \\} ∩ \\ {iw, ..., i + w \\} | When the jth bit from the left is 1 \\} |) is odd, the score is b...
#include <cstdio> #include <cmath> #include <cstring> #include <cstdlib> #include <climits> #include <ctime> #include <queue> #include <stack> #include <algorithm> #include <list> #include <vector> #include <set> #include <map> #include <iostream> #include <deque> #include <complex> #include <string> #include <iomanip>...
Problem statement N-winged rabbit is on a balance beam of length L-1. The initial position of the i-th rabbit is the integer x_i, which satisfies 0 ≤ x_ {i} \ lt x_ {i + 1} ≤ L−1. The coordinates increase as you move to the right. Any i-th rabbit can jump to the right (ie, move from x_i to x_i + a_i) any number of tim...
#define _USE_MATH_DEFINES #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<string> #include<vector> #include<list> #include<map> #include<set> #include<cmath> #include<queue> #include<cstring> #include<stack> #include<functional> using namespace std; typedef long long ll; const ll MOD ...
F: Bath overflows --Overflow of Furo - story The hot spring inn Paro is passionate about the hot springs that it is proud of, and is attracting professional bathers. Bath professionals mainly manage the plumbing of hot springs, and manage and coordinate the complicated and intricate plumbing network that connects mul...
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <deque> #include <list> #include <queue> #include <stack> #include <vector> #include <utility> #include <algorithm> #include <map> #include <set> #include <complex> #include <cmath> #include <limits> #include <climits> #include <ctime> ...
problem Given the sequence $ A $ of length $ N $. Find the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $. The longest increasing subsequence of the sequence $ A $ is the longest subsequence that satisfies $ A_i <A_j $ with all $ i <j $. output Outp...
#include <bits/stdc++.h> // #include <boost/multiprecision/cpp_int.hpp> #define int long long #define inf 1000000007 #define pa pair<int,int> #define ll long long #define pal pair<double,double> #define ppap pair<pa,int> #define PI 3.14159265358979323846 #define paa pair<int,char> #define mp make_...
C: Canisal cryptography problem Ebi-chan was given the string C obtained by encrypting a non-negative integer D with "canisal cipher". This cipher replaces each number in decimal notation with a fixed number (not necessarily different from the original). Different numbers will not be replaced with the same number, an...
#define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <cstring> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <list> #include <algorithm> #include <functio...
Given a matrix (H × W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s. Constraints * 1 ≤ H, W ≤ 1,400 Input H W c1,1 c1,2 ... c1,W c2,1 c2,2 ... c2,W : cH,1 cH,2 ... cH,W In the first line, two integers H and W separated by a space character are given. In the follo...
#include<bits/stdc++.h> using namespace std; const int maxn=1400; int dp[maxn][maxn],g[maxn][maxn]; int getlargestsquare(int h,int w) { int maxwidth=0; for(int i=0;i<h;i++){ for(int j=0;j<w;j++){ dp[i][j]=(g[i][j]+1)%2; maxwidth|=dp[i][j]; } } for(int i=1;i<h...
Extended Euclid Algorithm Given positive integers a and b, find the integer solution (x, y) to ax + by = gcd(a, b), where gcd(a, b) is the greatest common divisor of a and b. Constraints * 1 ≤ a, b ≤ 109 Input a b Two positive integers a and b are given separated by a space in a line. Output Print two inte...
#define _USE_MATH_DEFINES #include <cstdio> #include <cstdlib> #include <iostream> #include <cmath> #include <cstring> #include <algorithm> #include <vector> #include <queue> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <functional> using namespace std; typedef pair<long ...
For Turbo C++ Users : Read the following document before attempting the question : Problem Description Hank Pym is an aspiring student at IIITD. He has almost completed his work on Ultron, the ultimate artificial intelligence. However, one thing remains. He feels that Ultron should have a fail-safe code which can b...
max = 10**5 a = [True]*max prime = [] for i in range(2,max): if a[i]: prime.append(i) j = 2*i while j < max: a[j] = False j += i n = input() for z in range(n): k = input() count = 0 track = 0 while track < len(prime) and k!=1: while k%prime[tra...
In Ciel's restaurant, a waiter is training. Since the waiter isn't good at arithmetic, sometimes he gives guests wrong change. Ciel gives him a simple problem. What is A-B (A minus B) ? Surprisingly, his answer is wrong. To be more precise, his answer has exactly one wrong digit. Can you imagine this? Can you make th...
test = map(int,raw_input().split()) count = str(abs(test[0] - test[1])) l = ['1','2','3','4','5','6','7','8','9'] l.remove(count[0]) string = '' string += l[0] string += count[1:len(count)+1] print int(string)
Common Integer Andy wants to prove his practical programming knowledge to his old pal. He will get two numbers both in the range 10 to 99. if there exists a comon integer in both the numbers, he has to write TRUE or else FALSE. For Example: if input numbers are 12 and 24, the output must be TRUE since the common in...
x=raw_input() a,b=x.split() d=0 for i in a: if i in b: print "TRUE" d=1 break if d==0: print "FALSE"
Mrs. Verma has decided to sell his car. N people have offered to buy the car. Instead of selling to the highest bidder, Mrs. Verma decides to sell his company to the Kth lowest bidder. How much money will Mrs. Verma get? Input The first line of the input contains 2 space-separated integers, N and K. The next line cont...
n, k = map(int, raw_input().split()); a = [int(i) for i in raw_input().split()]; a.sort(); print a[k - 1];
Phillip has become fascinated with sequences lately. He looks for sequences all the time. His favorite sequence is the Fibonacci sequence, where any element is equal to the sum of the two previous elements. However, he isn't able to figure out the correct number for positions beyond 8 without writing it on paper. C...
fib=[] i1,i2,i3=map(int, raw_input().split()) y=i3 p=i1 fib.append(p) r=i2 fib.append(r) while(y): n=p+r fib.append(n) p=r r=n y-=1 print fib.pop((i3-1))
Problem Statement Write a program that accepts a number and outputs the same. Sample Input 123 Sample Output 123
num=int(raw_input()) print num
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
s=input() a=['a','e','i','o','u'] c=0 for i in range(len(s)): if(i==len(s)-1): if s[i] in a or s[i]=='n': c+=1 continue elif s[i] in a: c+=1 continue elif(s[i]=='n'): c+=1 continue else: if s[i+1] in a: c+=...
There is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i. You would like to put together some boxes. Putting together boxes with indices in the segment [l, r...
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T &x) { x = 0; int fu = 1; char c = getchar(); while (c > 57 || c < 48) { if (c == 45) fu = -1; c = getchar(); } while (c <= 57 && c >= 48) { x = (x << 3) + (x << 1) + c - 48; c = getchar(); } x *= fu; }...
You are given a tuple generator f^{(k)} = (f_1^{(k)}, f_2^{(k)}, ..., f_n^{(k)}), where f_i^{(k)} = (a_i ⋅ f_i^{(k - 1)} + b_i) mod p_i and f^{(0)} = (x_1, x_2, ..., x_n). Here x mod y denotes the remainder of x when divided by y. All p_i are primes. One can see that with fixed sequences x_i, y_i, a_i the tuples f^{(k...
#include <bits/stdc++.h> using namespace std; const int N = 2e6 + 10, mod = 1e9 + 7; int rd() { int x = 0, w = 1; char ch = 0; while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + (ch ^ 48); ch = getchar(); } return x * w; } ...
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order. We define the distance between two points p_1 = (x_1...
#include <bits/stdc++.h> using namespace std; int n; int ans[300003]; pair<int, int> A[300003]; vector<pair<int, int> > vec; int state(int first) { return (first < 0) ? -1 : +1; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d %d", &A[i].first, &A[i].second); for (int i = 0; i < n; i++) { ...
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3). You are given a p...
#include <bits/stdc++.h> using namespace std; const int kNmax = 2e5 + 10; const int kMod = 998244353; int n, p[kNmax]; int emptyLeft[kNmax], emptyRight[kNmax]; int countBigger[kNmax], countSmaller[kNmax]; int res; bool seen[kNmax]; class FT { public: FT(int n) { sz_ = n; arr_.resize(sz_ + 5); } int lsb(i...
You are given a permutation p_1, p_2, ..., p_n. You should answer q queries. Each query is a pair (l_i, r_i), and you should calculate f(l_i, r_i). Let's denote m_{l, r} as the position of the maximum in subsegment p_l, p_{l+1}, ..., p_r. Then f(l, r) = (r - l + 1) + f(l, m_{l,r} - 1) + f(m_{l,r} + 1, r) if l ≤ r or ...
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const long long mod = 998244353; const int MXN = 1e6 + 7; int n, q; int ar[MXN], ls[MXN], rs[MXN]; int stk[MXN]; long long ans[MXN]; std::vector<int> vs[MXN]; struct FenwickTree { long long BIT[MXN], N; void init(int n) { N = n + 3; f...
Two integer sequences existed initially — one of them was strictly increasing, and the other one — strictly decreasing. Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and th...
n = int(input()) a = [int(s) for s in input().split()] d = dict() for i in a: x = d.get(i,0) if x == 0: d[i] = 1 else: d[i] += 1 up = [] down = [] for i in d.keys(): k = d[i] if k == 1: up.append(i) elif k == 2: up.append(i) down.append(i) else: ...
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day — exactly 2 problems, during the third day — exactly 3 problems, and so on. During the k-th day he should solve k problems. Polycarp has a list of n contests, th...
a = int(input()) b = [int(x) for x in input().split()] b.sort() s = 1 q = 0 for i in b: if i >= s: s += 1 q += 1 print(q)
The Cybermen and the Daleks have long been the Doctor's main enemies. Everyone knows that both these species enjoy destroying everything they encounter. However, a little-known fact about them is that they both also love taking Turing tests! Heidi designed a series of increasingly difficult tasks for them to spend the...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); long long int n, i, j; vector<pair<long long int, long long int> > v; cin >> n; for (i = 0; i < 4 * n + 1; i++) { long long int x, y; cin >> x >> y; v.push_back(make_pair(x, y)); } for (i = 0; i < v.si...
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given an integer n. You have to find a sequence s consisting of digits \{1, 3, 7\} such that it has exactly n subsequences equal to 1337. For example, seque...
for _ in range(int(raw_input())): n = int(raw_input()) if n <= 10 ** 5 - 5: print('133' + '7' * n) else: cf = 300 g = n - (cf + 2) * (cf + 1) // 2 b = g // (cf * (cf - 1) // 2) c = g % (cf * (cf - 1) // 2) print('1' + '3' * cf + '7' * b + '1' * c + '337')
For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an N × N lightbulbs square board with a magical lightbulb bar of size N × 1 that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The...
#include <bits/stdc++.h> const int N = 4050; int n; std::vector<int> G[N << 1]; bool mark[N << 1]; int S[N << 1], c; bool dfs(int x) { if (mark[x ^ 1]) return 0; if (mark[x]) return 1; mark[x] = 1; S[c++] = x; for (int i = 0; i < G[x].size(); ++i) if (!dfs(G[x][i])) return 0; return 1; } void init(int x...
You are given a tree consisting of n vertices. A tree is an undirected connected acyclic graph. <image> Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color. You have to paint the vertices so that any path consisting of exactly th...
#include <bits/stdc++.h> using namespace std; vector<long long> adj[100005]; long long parent[100005]; vector<long long> temp; void find_parent(long long v, long long par) { parent[v] = par; for (auto p : adj[v]) if (p != par) find_parent(p, v); } long long find_col(long long x, long long y) { long long z; ...
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≤ i ≤ n - 1. Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 5; const long long Mod = 1e9 + 7; long long powmod(long long a, long long b) { long long res = 1; a %= Mod; assert(b >= 0); for (; b; b >>= 1) { if (b & 1) res = res * a % Mod; a = a * a % Mod; } return res; } long long gcd(long lo...
Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, ..., a_n and challenged him to choose an integer X such that the value \underset{1 ≤ i ≤ n}{max} (a_i ⊕ X) is minimum possible, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). As always, Badawy is too ...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int cnt = 1, T[N * 31][2], n; long long t, a[N * 31]; void insert(long long x) { int u = 0; for (int i = 30; i >= 0; i--) { int v = (x >> i) & 1; if (!T[u][v]) { memset(T[cnt], 0, sizeof(T[cnt])); a[cnt] = 0; T[u][v] = cn...
The only difference between easy and hard versions is the constraint on k. Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue. Gildong is going to take videos for n days, starting from day 1 to day n. ...
#include <bits/stdc++.h> using namespace std; const long long INF = 1e18; template <typename TI, typename TX, typename TL> class SegmentTree { public: struct node { long long x = -INF; node(){}; node(const TX &y) { set(y); }; void set(const TX &y) { x = y; }; }; node merge(const node &a, const no...
Dreamoon likes coloring cells very much. There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n. You are given an integer m and m integers l_1, l_2, …, l_m (1 ≤ l_i ≤ n) Dreamoon will perform m operations. In i-th operation, Dreamoon will choose a number ...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pi = pair<int, int>; using vi = vector<int>; const int nax = 100 * 1000 + 10; int n, m; int l[nax]; int p[nax]; ll sum; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i = 1; i <= m; ++i) { cin >> l[i]; ...
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integ...
from collections import Counter from math import floor, sqrt try: long except NameError: long = int def fac(n): step = lambda x: 1 + (x<<2) - ((x>>1)<<1) maxq = long(floor(sqrt(n))) d = 1 q = 2 if n % 2 == 0 else 3 while q <= maxq and n % q != 0: q = step(d) d += 1 ...
Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020... There are n different types of food and m Lee's best friends. Lee has w_i plates of the i-th type of food and each friend has two different favorit...
#include <bits/stdc++.h> using namespace std; int X[200005], Y[200005], W[200005], S[200005], colormark[200005], mark[200005]; vector<int> V[200005]; vector<int> ans; int main() { set<pair<int, int>> pq; int n, m; cin >> n >> m; for (int i = 1; i <= n; i++) cin >> W[i]; for (int i = 0; i < m; i++) { cin >...
A binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix a consisting of n rows and m columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their...
import java.io.*; import java.util.*; import java.math.*; import java.util.regex.*; public class Solution { static class cell{ int r, c; public cell(int r, int c) { this.r = r; this.c = c; } } static class Pair<E, V> implements Comparable<Pair<E, V>>{ E a; V b; public Pair(E x, V y) {a = x;...
You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there i...
t = int(input()) ns = [] for i in range(t): n = int(input()) arr = list(map(int, input().split())) nums = set(arr) dct1 = {} dct2 = {num: 0 for num in nums} for idx, el in enumerate(arr): if el in dct1: dct2[el] = max(dct2[el], idx - dct1[el]) else: d...
Polycarp is editing a complicated computer program. First, variable x is declared and assigned to 0. Then there are instructions of two types: 1. set y v — assign x a value y or spend v burles to remove that instruction (thus, not reassign x); 2. if y ... end block — execute instructions inside the if block if t...
/* _ _ _ _ _ _ _ _ _ \_\ /_/ \_\_\_\_\_\ \_\ /_/ \_\ /_/ \_\ \_\ /_/ \_\_/ \_\ \_\_/ \_\ \_\ \_\ \_\ \_\ \_\ \_\ \_\ \_\\_\ \_\ */ #pragma GCC optimize ("O3") #pragma GCC target ("sse4") #include <bits/stdc++.h> using ll = int64_t; c...
Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move. In a move, a player must choose an index i (1 ≤ i ≤ n) ...
import java.util.Scanner; public class Welcomejava { public static void main(String[] args) { // TODO code application Scanner input = new Scanner(System.in); int t ; t = input.nextInt(); while (t-->0) { String s ; s = input.next(); ...
You are given a string s, consisting of lowercase Latin letters. While there is at least one character in the string s that is repeated at least twice, you perform the following operation: * you choose the index i (1 ≤ i ≤ |s|) such that the character at position i occurs at least two times in the string s, and del...
for _ in range(int(input())): s = input(); stack = []; seen = set(); last_occurrence = {c: i for i, c in enumerate(s)} for i, c in enumerate(s): if c not in seen: while stack and c > stack[-1] and i < last_occurrence[stack[-1]]: seen.discard(stack.pop(...
Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag). You are given an n × m grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those ...
I=lambda: map(int, raw_input().split()) t = input() for _ in xrange(t): n, m = I() fCol = None ok = True for j in xrange(n): a = list(raw_input()) if not ok: continue for i in xrange(m): k = (i+j)%2 if a[i] == 'W': if k == 0: if fCol == 'R': if ok: ok = False break el...
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: * On the first step the string consists of a single character "a". * On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of ...
#include <bits/stdc++.h> using namespace std; int a, b, c, d; int f(int a, int b, int c, int d, int n) { if (a > b || c > d) return 0; if (a == c) return min(b, d) - a + 1; if (a > c) swap(a, c), swap(b, d); if (b >= d) return d - c + 1; int x = 1 << n; if (b < x && d < x) return f(a, b, c, d, n - 1); if ...
Let's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) an...
#include <bits/stdc++.h> using namespace std; int main() { int n, m, k; cin >> n >> m >> k; vector<int> v(n); vector<int> c(m + 5, 0); for (int i = 0; i < n; i++) { cin >> v[i]; } int l = 0, r = 0; int res = 1; c[v[0] - 1]++; int maxC = 1; int maxI = v[0] - 1; while (r < n) { if (c[v[r] ...
The Little Elephant very much loves sums on intervals. This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be inclu...
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author George Marcus */ public class Main { public static void main(String[] args) { Inpu...
Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not. The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads...
import java.io.*; import java.util.*; public class AsphaltedRoads2Sat { public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(rd.readLine()); N...
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d. Note that the order of the points inside the group of three chosen point...
#include <bits/stdc++.h> using namespace std; long long a[100005]; int main() { long long n, d; cin >> n >> d; for (int i = 1; i <= n; i++) cin >> a[i]; long long l = 1, r = 2; long long ans = 0; while (l <= n || r <= n) { if (l >= r) { r = l + 1; continue; } if (r > n) { ans +...
Many of you must be familiar with the Google Code Jam round rules. Let us remind you of some key moments that are crucial to solving this problem. During the round, the participants are suggested to solve several problems, each divided into two subproblems: an easy one with small limits (Small input), and a hard one wi...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1605; const long double eps = 1e-10; struct data { int a, b, s, t; long double p; bool operator<(const data& d2) const { return t * p * (1 - d2.p) < d2.t * d2.p * (1 - p); } } a[MAXN]; int N, T; long double f[MAXN][MAXN], g[MAXN][MAXN], ans = -1...
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
n = int(input()) d = {} l = [] for _ in range(n): name, score = input().split() score = int(score) l.append((name,score)) d[name] = d.get(name, 0) + score m = max([x for x in d.values()]) ties = [x for x,y in d.items() if y == m] # print(ties) if len(ties) == 1: print(ties[0]) exit() el...
You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle). Your task is to determine if the rectan...
#include <bits/stdc++.h> using namespace std; struct coord { int x1, x2, y1, y2; }; int main() { int n; cin >> n; coord rect[n]; int mnX = 31401, mnY = 31401, mxX = 0, mxY = 0; long long area = 0; for (int i = 0; i < n; i++) { cin >> rect[i].x1 >> rect[i].y1 >> rect[i].x2 >> rect[i].y2; area += 1L...
You are given a rooted tree with n vertices. In each leaf vertex there's a single integer — the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf. A tree is b...
#include <bits/stdc++.h> using namespace std; const int N = 100010; const long long inf = 1ll << 60; int n, tot; int to[N << 1], nex[N << 1], head[N]; long long ans = 0, p[N], sum[N]; bool flag; void SE(int u, int v) { to[++tot] = v; nex[tot] = head[u]; head[u] = tot; return; } long long _GCD(long long x, long ...
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
st = input() B = st.count('B') S = st.count('S') C = st.count('C') b,s,c=map(int,input().split()) bp, sp, cp = map(int,input().split()) r=int(input()) lm=0; rm=int(1e15)+1 while rm-lm>1: m=(rm+lm)//2 # print(m) bb=max(m*B-b,0) ss=max(m*S-s,0) cc=max(m*C-c, 0) #print(bp*bb+ss*sp+cc*cp) if bp*b...
SmallR likes a game called "Deleting Substrings". In the game you are given a sequence of integers w, you can modify the sequence and get points. The only type of modification you can perform is (unexpected, right?) deleting substrings. More formally, you can choose several contiguous elements of w and delete them from...
#include <bits/stdc++.h> const int N = 405, inf = 1000000007; using namespace std; int g[N], f[N][N][2], n, a[N], v[N]; void dp() { for (int i = 1; i <= n; ++i) { f[i][i][0] = 0; f[i][i][1] = v[1]; } for (int L = 2; L <= n; ++L) for (int l = 1; l <= n - L + 1; ++l) { int r = l + L - 1; f[l...
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show. The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: * Is it true that y is stric...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); int a; cin >> a; int l = -2e9; int r = 2e9; while (a--) { string c; int n; char s; cin >> c >> n >> s; if (c == ">") { if (s == 'Y') l = max(l, n + 1); else r = min(r, n);...
When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: * There is no vertex that has more than two incident edges painted the same color. * For any two...
#include <bits/stdc++.h> int _max(int x, int y) { return x > y ? x : y; } int n; int f[1002000], dp[1002000], ma[1002000], sec[1002000]; bool Update(int x) { int o = dp[x], pos = 0; if (ma[f[x]] == dp[x]) pos = 1; dp[x] = _max(ma[x], sec[x] + 1); if (pos == 0) { if (ma[f[x]] <= dp[x]) sec[f[x]] = ma[f...
You are given a weighted undirected graph on n vertices and m edges. Find the shortest path from vertex s to vertex t or else state that such path doesn't exist. Input The first line of the input contains two space-separated integers — n and m (1 ≤ n ≤ 105; 0 ≤ m ≤ 105). Next m lines contain the description of the g...
#include <bits/stdc++.h> using namespace std; char buf[1 << 21], *p1 = buf, *p2 = buf; template <class T> inline bool cmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } inline int read() { char ch; bool flag = 0; int res; while (!isdigit( ch = (p1 == p2 && (p2 = (p1 = buf) + fre...
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right. Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: * Each piece should contain at least l numbers. * The difference between the maximal and the minimal number on the piece...
#include <bits/stdc++.h> using namespace std; const int maxn = 100010; const int INF = 1e9 + 7; int n, s, l, dp[maxn], a[maxn]; multiset<int> st, v; int main() { cin >> n >> s >> l; for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1, j = 1; i <= n; i++) { st.insert(a[i]); while (*st.rbegin() ...
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old. They will have dinner around some round tables. You want to distribute foxes such that: 1. Each fox is sitting at some table. 2. Each table has at least 3 foxes sitting around it. 3...
#include <bits/stdc++.h> using namespace std; const int inf = (int)1e9; const long long INF = (long long)5e18; const int MOD = 998244353; int _abs(int x) { return x < 0 ? -x : x; } int add(int x, int y) { x += y; return x >= MOD ? x - MOD : x; } int sub(int x, int y) { x -= y; return x < 0 ? x + MOD : x; } void...
Tavas lives in Kansas. Kansas has n cities numbered from 1 to n connected with m bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities. Tavas invented a game and called...
#include <bits/stdc++.h> using namespace std; long long read() { long long x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); } return x * f; } stru...
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of gia...
#include <bits/stdc++.h> using namespace std; const int maxv = 2045; const long long mod = 1e9 + 7; const int maxn = 1e6 + 40; long long fac[maxn], inv[maxn]; long long qpow(long long a, long long p) { long long ans = 1; long long xx = a; while (p > 0) { if (p & 1) ans = (xx * ans) % mod; xx = (xx * xx) %...
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimi...
#include <bits/stdc++.h> using namespace std; int n; int w[1000000]; int m[2000001]; int main() { cin >> n; for (int i = 0; i < n; i++) { scanf("%d", &w[i]); m[w[i]]++; } sort(w, w + n); long long ans = 0; for (int i = 0; i <= 1000130; i++) { long long f = m[i]; if (f == 0) { continue;...
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference betw...
input() servers = [int(x) for x in input().split(" ", )] servers.sort() avg = int(sum(servers) / len(servers)) extra = sum(servers) % len(servers) count = 0 for i in range(len(servers)): count += abs(avg + (i >= (len(servers) - extra)) - servers[i]) / 2 print(int(count))
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time. Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately ev...
n,t=map(int,input().split()) print(n*((1.000000011)**t))
Input The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid"). Output Output a single integer. Examples Input A221033 Output 21 Input A223635 Output 22 Input A232726 Outpu...
#include <bits/stdc++.h> using namespace std; int main() { string s; int i, l, z = 0; cin >> s; l = s.size(); for (i = 0; i < l; i++) if (s[i] == 'A') z += 1; else if (s[i] == '1') z += 10; else z += s[i] - '0'; cout << z; return 0; }
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer. Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards. He is allowed to at most once discard two or three cards wi...
from collections import Counter a = map(int,raw_input().split()) s = sum(a) a = Counter(a) #print a result = s #print result for k,v in a.items(): #print k,v if v>=2: result = min(result,s - k *min(3,v)) print result
The big consignment of t-shirts goes on sale in the shop before the beginning of the spring. In all n types of t-shirts go on sale. The t-shirt of the i-th type has two integer parameters — ci and qi, where ci — is the price of the i-th type t-shirt, qi — is the quality of the i-th type t-shirt. It should be assumed th...
#include <bits/stdc++.h> using namespace std; inline void read(int &n) { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); n = x * f; } int outputarray[...
You are given an undirected graph, constisting of n vertices and m edges. Each edge of the graph has some non-negative integer written on it. Let's call a triple (u, v, s) interesting, if 1 ≤ u < v ≤ n and there is a path (possibly non-simple, i.e. it can visit the same vertices and edges multiple times) between verti...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; const int mxn = 400005, maxnn = 100005; const int mod = 1e9 + 7; long long ans; int n, m, num, cir, r, cnt; int head[maxnn], que[maxnn]; struct edge { int to, next; long long w; } f[mxn << 2]; long long p[70], circ...
There are n cities in Berland, each of them has a unique id — an integer from 1 to n, the capital is the one with id 1. Now there is a serious problem in Berland with roads — there are no roads. That is why there was a decision to build n - 1 roads so that there will be exactly one simple path between each pair of cit...
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.List;...
Scientists of planet Olympia are conducting an experiment in mutation of primitive organisms. Genome of organism from this planet can be represented as a string of the first K capital English letters. For each pair of types of genes they assigned ai, j — a risk of disease occurence in the organism provided that genes o...
#include <bits/stdc++.h> using namespace std; template <typename T1, typename T2> inline T1 max(T1 a, T2 b) { return a < b ? b : a; } template <typename T1, typename T2> inline T1 min(T1 a, T2 b) { return a < b ? a : b; } const char lf = '\n'; namespace ae86 { const int bufl = 1 << 15; char buf[bufl], *s = buf, *t ...
Oleg the bank client solves an interesting chess problem: place on n × n chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell. Remind that a rook standing in the cell (a, b) beats a rook standing in the cell (x, y) if and only if a = x or b = y. Un...
#include <bits/stdc++.h> using PII = std::pair<int, int>; template <class F = int> class Graph { public: struct Edge { int v; F w; }; Graph(int n) : e(), g(n), d(n), cur(n) {} std::vector<Edge> e; std::vector<std::vector<int>> g; void AddEdge(int x, int y, F z) { g[x].push_back(e.size()), e.pus...
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it? The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which i...
#include <bits/stdc++.h> using namespace std; long long sqr(long long x) { return (x * x); } long long dist(pair<long long, long long> a, pair<long long, long long> b) { return sqr(a.first - b.first) + sqr(a.second - b.second); } long long func(long long i) { if (i < 2 || i & 1) return 1; return -1; } int main() ...