input
stringlengths
29
13k
output
stringlengths
9
73.4k
Mr. Dango's family has extremely huge number of members. Once it had about 100 members, and now it has as many as population of a city. It is jokingly guessed that the member might fill this planet in near future. They all have warm and gracious personality and are close each other. They usually communicate by a phone...
#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include <math.h> #include <assert.h> #include <vector> using namespace std; typedef long long ll; static const double EPS = 1e-9; static const double PI = acos(-1.0); static const ll MOD = 10007; #define REP(i, n) for (int i = 0; i < (in...
An arithmetic pipeline is designed to process more than one task simultaneously in an overlapping manner. It includes function units and data paths among them. Tasks are processed by pipelining: at each clock, one or more units are dedicated to a task and the output produced for the task at the clock is cascading to th...
#include <iostream> #include <algorithm> #include <numeric> #include <vector> #include <string> #include <memory.h> #include <queue> #include <cstdio> #include <cstdlib> #include <set> #include <map> #include <cctype> #include <iomanip> #include <sstream> #include <cctype> #include <fstream> #include <cmath> using name...
We have an analog clock whose three hands (the second hand, the minute hand and the hour hand) rotate quite smoothly. You can measure two angles between the second hand and two other hands. Write a program to find the time at which "No two hands overlap each other" and "Two angles between the second hand and two other...
#include<iostream> using namespace std; long gcd(long a,long b){return b?gcd(b,a%b):a;} int H,h,m,s; bool check(long H,long h,long m,long s) { for(int r=-1;r<=1;r++) { long A=r*360*10*H+60*m*(H+1)+3600*h; long B=119*H-1; long d=gcd(A,B); A/=d; B/=d; if(!(A>=60*B||...
Problem Given the string S, which consists of lowercase letters and numbers. Follow the steps below to compress the length of string S. 1. Change the order of the characters in the character string to any order. Example: "0ig3he12fz99"-> "efghiz012399" 2. Perform the following operations any number of times. * Sele...
#include <algorithm> #include <iostream> #include <map> #include <numeric> #include <set> #include <vector> #define unless(c) if (!(c)) #define each(i, c) for (auto& i: c) using namespace std; int main(void) { const int N = 300; string s; while (cin >> s) { sort(s.begin(), s.end()); int cnt[N]; fil...
Steve runs a small restaurant in a city. Also, as he is the only cook in his restaurant, he cooks everything ordered by customers. Basically he attends to orders by first-come-first-served principle. He takes some prescribed time to prepare each dish. As a customer can order more than one dish at a time, Steve starts ...
#include <iostream> #include <string> #include <map> #include <queue> #include <algorithm> using namespace std; enum EVENT{ORDER, COOKED}; class Event { public: int c,t,s,id; EVENT e; Event(int c, int t, int s, int id, EVENT e) :c(c),t(t),e(e),s(s),id(id) {} bool operator<(const Event& a) const { if(t!=a...
ACM countries have rivers that flow from east to west in the center. This river flows from the neighboring country in the west through the neighboring country in ACM to the neighboring country in the east, and the total length in ACM is K km. It is planned to install several locks on this river and use it as a canal. ...
#include <algorithm> #include <cstdio> using namespace std; int main() { int N,S,K,X,UD; double L,F,D,V; while(scanf("%d%d%d",&N,&S,&K), N||S||K) { double T[4][1500]={0}; for(int i=0; i<N; i++) { scanf("%d%lf%lf%lf%d",&X,&L,&F,&D,&UD); X+=100; T[1][X] = L/F; T[2][X] = L/D; if(UD) ...
Example Input 8 5 1 2 6 5 6 4 1 3 4 7 Output 11
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll,ll> P; vector<int> v[111111]; vector<P> p; int u[111111][2],c[2]; void dfs(int x,int t) { if(u[x][t]) return; c[t]++; u[x][t]=1; for(int i=0; i<v[x].size(); i++) dfs(v[x][i],t^1); } bitset<100001> t; int main() { int n...
Problem Statement You have a billiard table. The playing area of the table is rectangular. This billiard table is special as it has no pockets, and the playing area is completely surrounded with a cushion. You succeeded in producing a ultra-precision billiards playing robot. When you put some balls on the table, the ...
#include <array> #include <climits> #include <cmath> #include <cstdlib> #include <iostream> #include <vector> using namespace std; constexpr double EPS = 1e-9; struct point { double x, y; explicit point(double x_ = 0.0, double y_ = 0.0):x(x_), y(y_) {} point(const point &p):x(p.x), y(p.y) {} point operator+(cons...
Example Input 100 100 0 1 Output 1.16699564
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<bitset> #include<stack> #include<unordered_map> #include<utility> #include<cassert> #in...
problem Dimension exists from $ 1 $ dimension to $ N $ dimension. AOR Ika can move between dimensions. Specifically, when AOR Ika is in the $ i $ dimension, she can move freely to the $ j $ dimension ($ i> j $), but in the $ k $ dimension ($ i <k $). You need to use magic to move to. AOR Ika can use $ M $ types of ma...
#include <bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) #define int long long using namespace std; typedef pair<int,int>P; int s,t,n,m,a[100009],d[100009]; priority_queue<P,vector<P>,greater<P> >q; vector<P>v[100009]; signed main(){ r(i,100009)d[i]=1e15; cin>>n>>m>>s>>t; s--; t--; r(i,n)cin>>a[i]; r(i,n-...
Problem Statement In A.D. 2101, war was beginning. The enemy has taken over all of our bases. To recapture the bases, we decided to set up a headquarters. We need to define the location of the headquarters so that all bases are not so far away from the headquarters. Therefore, we decided to choose the location to mini...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll, ll> P; #define fi first #define se second #define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++) #define rep(i,n) repl(i,0,n) #define all(x) (x).begin(),(x).end() #define dbg(x) cout<<#x"="<<x<<endl #defi...
Problem statement Given the integers $ N $ and $ X $. Find the remainder by dividing the number of sequences of length $ N $ that satisfy the following conditions by $ 998244353 $. * The sequence is a monotonous increase in a broad sense. * Each element of the sequence is greater than or equal to $ 0 $ and less than ...
#include <iostream> #include <vector> using namespace std; int main() { int N, X; cin >> N >> X; int x = X, L = 0; while (x > 0) { x >>= 1; L += 1; } L = 1<<L; vector< vector<int>> dp0(L, vector<int>(X+1, 0)); vector< vector<int>> dp1(L, vector<int>(X+1, 0)); int mod = 998244353; for (int i =...
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable. Constraints * 1 ≤ |V| ≤ 10,000 * 0 ≤ |E| ≤ 30,000 * 1 ≤ Q ≤ 100,000 Input A directed graph G(V, E) and a sequence of...
#include <bits/stdc++.h> #define rep(i, a, n) for(int i = a; i < n; i++) #define repb(i, a, b) for(int i = a; i >= b; i--) #define all(a) a.begin(), a.end() #define o(a) cout << a << endl #define int long long #define fi first #define se second using namespace std; typedef pair<int, int> P; const int MAX_V = 100010; i...
Walter white wants to buy a car, he does not care much about the type of car (sedan/hatchback/SUV) nor the power that the car has, all he cares about is how much the car will cost him, since he has loads of money , he wants to buy the most expensive car available in the market, but there is a catch! The tax percentages...
def maxim(lis,n): i=0 maxi=-1000 maxib=-100 coord=0 while i<n: t=lis[i][0]+lis[i][0]*lis[i][1]/100 if(t==maxi): if(lis[i][0]>maxib): maxi=t maxib=lis[i][0] coord=i elif(t>maxi): maxi=t maxib=l...
Little Elephant was fond of inventing new games. After a lot of research, Little Elephant came to know that most of the animals in the forest were showing less interest to play the multi-player games.Little Elephant had started to invent single player games, and succeeded in inventing the new single player game named C...
for i in range(int(raw_input())): for j in range(int(raw_input())): i,n,q = map(int,raw_input().split()) if n % 2 == 0: print n/2 else: if i == q: print n/2 else: print n/2 + 1
Problem Statement One day Chef is waiting his girlfriend on the bus station. The girlfriend said that she will be at time1. Chef went to the bus station at time2. When Chef has reached the bus station he realized that he forgot a gift for his better half in his home. Chef knows that someone can reach his home in dist m...
#!/usr/bin/python t=input() for i in range(t): gh,gm=map(int,raw_input().split(':')) ch,cm=map(int,raw_input().split(':')) gh=gh*60+gm; ch=ch*60+cm; dist=input() if(2*dist<=(gh-ch)) : print float(gh-ch+dist) ,float(gh-ch); else: print float(gh-ch+dist), float(gh-ch+2*dist)/2
Chef's new hobby is painting, but he learned the fact that it's not easy to paint 2D pictures in a hard way, after wasting a lot of canvas paper, paint and of course time. From now on, he decided to paint 1D pictures only. Chef's canvas is N millimeters long and is initially all white. For simplicity, colors will be re...
for _ in range(int(raw_input())): n = int(raw_input()) a = map(int, raw_input().split()) ans = "No" c = 1 p = a[0] for i in a[1:]: if i == p: c += 1 if c == 3: ans = "Yes" break else: p = i c = 1 ...
In the fest of Paradigm, every organiser is given a special kind of pager. The pager consists of a screen and a single big red button. To type a message in it, one has to push the red button that many time at which the alphabet occurs in the alphabetical order. For example for typing D, one needs to push button 4 times...
n=int(input()) l=[] for i in range(0,n): x=raw_input() val=0 for char in x: val=val+ord(char)-64 l.append(val) for i in l: print i
Chef is sitting in a very boring lecture, waiting for it to end. He has recently asked his friend about the time, and instead of the straightforward answer, his friend, being an absolute jerk, told him the absolute value of angle between hour and minute hands. But that is obviously not what he wanted to know, so he a...
from collections import defaultdict as dd def pre_times(): rs=dd(list) for h in xrange(12): ha=0.0+h*30 ma=0.0 for m in xrange(60): calculated_angle=min(abs(ha-ma),360-abs(ha-ma)) index=int(calculated_angle) rs[index].append({calculated_angle:[h,m]}) ha+=0.5 ma+=6.0 return rs def get_a...
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes. Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x...
n = int(input()) a = [int(x) for x in input().split()] a.sort() top = [a[0], a[-1]] right = [a[n - 1], a[n]] case2 = abs((top[0] - right[0])*(top[1] - right[1])) case1 = top[-1] - top[0] mny = 10000000000 for i in range(1, n): mny = min(mny, abs(a[i] - a[i + n-1])) #print(mny) case1 *= mny print(min(abs(cas...
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase. A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD...
#include <bits/stdc++.h> using namespace std; vector<int> a(27); int main() { int n, k; cin >> n >> k; for (int i = 0; i < n; i++) { char r; cin >> r; a[r - 64]++; } int res = 1e7; for (int i = 1; i <= k; i++) { res = min(a[i], res); } cout << res * k; }
Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at nigh...
#include <bits/stdc++.h> using namespace std; int n, cnt = 0; struct node { int to, nxt; } e[400010]; long long siz[200010], dep[200010]; long long ans = 0, ji = 0; int head[200010]; void add(int u, int v) { e[++cnt].to = v; e[cnt].nxt = head[u]; head[u] = cnt; e[++cnt].to = u; e[cnt].nxt = head[v]; head[...
A multi-subject competition is coming! The competition has m different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has n candidates. For the i-th person he knows subject s_i the candidate specializes in and r_i — a skill level in his s...
import sys input=sys.stdin.readline n, m = map(int, input().split()) s = [[] for _ in range(m)] size = [0]*m for _ in range(n): si, ri = map(int, input().split()) s[si-1].append(ri) size[si-1] += 1 # print(s) # print(size) sa = max(size) # print(sa) i = 0 ans = [0]*sa # print("ans",ans) for i in range(m)...
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). ...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cerr.tie(0); int q; cin >> q; int x, y, cx = 0, cy = 0; char c; for (int(i) = (0); (i) < (q); ++(i)) { cin >> c >> x >> y; if (x < y) swap(x, y); if (c == '+') { if (cx <...
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: * a12 + a22 + ... + an2 ≥ x * a1 + a2 + ... + an ≤ y Input The first line contains three space-separated integers n, x and y (1 ≤ n ≤ 105, 1 ≤ x ≤ 1012, 1 ≤ y ≤ 106). Please d...
import math n, x, y = map(int, raw_input().split()) tmp = y - n + 1 if tmp > 0 and pow(tmp, 2) + (n - 1) >= x: print tmp for i in range (n - 1): print 1 else: print -1
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings...
#include <bits/stdc++.h> using namespace std; const int N = 2002; int n; string t, s_beg, s_end; long long pw[N], h[N]; void pre() { pw[0] = 1; for (int i = 1; i < N; ++i) { pw[i] = pw[i - 1] * 31; } for (int i = 0; t[i]; ++i) { h[i + 1] = h[i] + (t[i] - 'a' + 1) * pw[i]; } } int main() { ios::sync_...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
s=input() s=s.lower() for i in range(len(s)): if not(s[i]=='a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u' or s[i]=='y'): print('.{0}'.format(s[i]),end="")
You are given a tree of n nodes. The tree is rooted at node 1, which is not considered as a leaf regardless of its degree. Each leaf of the tree has one of the two colors: red or blue. Leaf node v initially has color s_{v}. The color of each of the internal nodes (including the root) is determined as follows. * L...
#include <bits/stdc++.h> using namespace std; inline int read() { char c = getchar(); int x = 0; bool f = 0; for (; !isdigit(c); c = getchar()) f ^= !(c ^ 45); for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48); if (f) x = -x; return x; } mt19937 Rand(std::chrono::steady_clock::now().tim...
Your program fails again. This time it gets "Wrong answer on test 233" . This is the harder version of the problem. In this version, 1 ≤ n ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems. The problem is to finish n one-choice-questions. Eac...
#include <bits/stdc++.h> using namespace std; long long int F[1000001], RF[1000001]; long long int delta = 998244353; long long int POW(long long int a, long long int b) { long long int ans = 1; if (b == 0) { return 1; } if (b == 1) { ans = ans * a % delta; } else { ans = POW(a, b / 2) % delta; ...
Fibonacci numbers have the following form: F1 = 1, F2 = 2, Fi = Fi - 1 + Fi - 2, i > 2. Let's consider some non-empty set S = {s1, s2, ..., sk}, consisting of different Fibonacci numbers. Let's find the sum of values of this set's elements: <image> Let's call the set S a number n's decomposition into Fibonacci su...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 100, maxc = 115, inf = 1e9 + 10; long long t, n, f[100], dp1[100], dp2[100]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); f[0] = f[1] = 1; for (int i = 2; f[i - 1] < (long long)1e18; i++) f[i] = f[i - 1] + f[i - 2]; ...
[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; int n; struct edge { int y, next; } e[3010 << 1]; int first[3010], len = 0; void buildroad(int x, int y) { e[++len] = (edge){y, first[x]}; first[x] = len; } int fa[3010][3010], sz[3010][3010]; void init(int x, int p) { sz[p][x] = 1; for (int i = first[x]; i; i = e...
Your task is to calculate the number of arrays such that: * each array contains n elements; * each element is an integer from 1 to m; * for each array, there is exactly one pair of equal elements; * for each array a, there exists an index i such that the array is strictly ascending before the i-th element a...
import java.io.*; import java.util.*; import java.math.*; public class S { static class Pair implements Comparable<Pair> { int a; int b; public Pair(int x,int y){a=x;b=y;} public Pair(){} public int compareTo(Pair p1){ return a+b-p1.a-p1.b; } @Override public int hashCode() { final int p...
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
test = int(input()) for t in range(test): c = int(input()) if c == 0 or c == 1 or c == 2: print(0) elif c % 2 == 0: print((c//2)-1) else: print(c//2)
Like any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A ≤ B ≤ C ≤ D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A ≤ x ≤ B ≤ y ≤ C ≤ z ≤ D holds? Yuri is preparing problems for a new contest now, so he is v...
#include <bits/stdc++.h> using namespace std; long long pref[2000005]; void solve() { long long a, b, c, d; cin >> a >> b >> c >> d; long long mini = a + b, maxi = b + c, ans = 0; memset(pref, (0), sizeof(pref)); for (int i = a; i <= b; i++) { pref[i + b]++; pref[i + c + 1]--; } for (int i = 1; i ...
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the...
def possible(n, m): f = True for i in range(n): row = list(map(int, input().split())) if i == 0 or i == n-1: for j in range(m): if j == 0 or j == m-1: if row[j] > 2: f = False else: if row...
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells. There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be ca...
import java.io.*; import java.util.*; public class TaskE { static FastIO io = new FastIO("in.txt"); static int N; static int[][] P; static BIT cnt0, cnt1, sum; static HashMap<Integer, Integer> idxs = new HashMap<>(); static TreeSet<Integer> idxsList = new TreeSet<>(); static long query(int...
Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths a, b, and c. Now he needs to find out some possible integer length d of the fourth straight fence segment so that he can build the fence using these four...
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { long long a, b, c; cin >> a >> b >> c; long long d = max(c, max(a, b)); if (a + b + c == d) { d--; } cout << d << "\n"; } return 0; }
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse. He's got problems wi...
#include <bits/stdc++.h> int xx[4][5] = { {0, 0, 0, 1, 2}, {0, 1, 1, 1, 2}, {0, 1, 2, 2, 2}, {0, 1, 1, 1, 2}}; int yy[4][5] = { {0, 1, 2, 1, 1}, {2, 0, 1, 2, 2}, {1, 1, 0, 1, 2}, {0, 0, 1, 2, 0}}; int n, i, m, j, k, ans; int a[20][20]; int best[20][20]; char out[20][20]; void make() { for (i = 1; i <= n; i++)...
There are n digital panels placed in a straight line. Each panel can show any digit from 0 to 9. Initially, all panels show 0. Every second, the digit shown by each panel increases by 1. In other words, at the end of every second, a panel that showed 9 would now show 0, a panel that showed 0 would now show 1, a panel ...
for _ in range(int(input())): n=int(input()) if(n==1): print(9) elif(n==2): print(98) else: print(989, end='') a=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for i in range(n-3): print(a[i%10], end='') print('')
There is a new attraction in Singapore Zoo: The Infinite Zoo. The Infinite Zoo can be represented by a graph with an infinite number of vertices labeled 1,2,3,…. There is a directed edge from vertex u to vertex u+v if and only if u\&v=v, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwis...
import sys readline = sys.stdin.readline T = int(readline()) Ans = ['NO']*T limit = 33 for qu in range(T): u, v = map(int, readline().split()) if u <= v: p = 0 for k in range(limit): if (1<<k)&u == (1<<k)&v: continue if (1<<k)&u == 0: p -...
Given an array a of length n, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square. A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Input The first line contains an integer t (1 ≤ t ≤ 100) — the...
import java.util.*; import java.io.*; public class B{ public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); for(int tt=0;tt<t;tt++) { int n = fs.nextInt(); int[] arr = fs.readArray(n); boolean flag = false; ...
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat ...
t = int(input()) for j in range(t): n = int(input()) a = [int(i) for i in range(1, n + 1)] if n % 2 == 0: for i in range(0, n, 2): a[i], a[i + 1] = a[i + 1], a[i] else: for i in range(0, n - 1, 2): a[i], a[i + 1] = a[i + 1], a[i] a[-2], a[-1] = a[-1], a[-2...
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — a and b. The order of the numbers is not important. Let's consider a ≤ b for the sake of definiteness. The players can cast one of the two spells in turns: * Replace b with b - ak. Number k can be chosen by...
#include <bits/stdc++.h> using namespace std; bool win(long long a, long long b) { if (a == 0) return false; if (!win(b % a, a)) return true; return !(((b / a) % (a + 1)) % 2); } int main() { ios::sync_with_stdio(false); int i, n; long long a, b; cin >> n; for ((i) = 0; (i) < (n); (i)++) { cin >> a ...
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot. One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the perm...
#include <bits/stdc++.h> using namespace std; long long labs(long long a) { return a < 0 ? (-a) : a; } vector<int> v, v1; int main() { int n; cin >> n; v.resize(n); v1.resize(n); for (int(i) = 0; (i) < (n); (i)++) { cin >> v[i]; v[i]--; } for (int(i) = 0; (i) < (n); (i)++) { int a; cin >> ...
A very tense moment: n cowboys stand in a circle and each one points his colt at a neighbor. Each cowboy can point the colt to the person who follows or precedes him in clockwise direction. Human life is worthless, just like in any real western. The picture changes each second! Every second the cowboys analyse the sit...
#include <bits/stdc++.h> using namespace std; const int MOD = 1000000007; template <class T> typename T::value_type arr_sum(const T& v, int n) { typename T::value_type sum = 0; for (int i = (0); i < (n); ++i) sum += v[i]; return sum; } struct Sync_stdio { Sync_stdio() { cin.tie(NULL); ios_base::sync_wit...
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find th...
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...
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems. There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the term...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class P_261A { static final FS sc = new FS(); static final PrintWriter pw = new PrintWriter(System.out); public st...
Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn. The decreasing coefficient of permutation p1, p2, ...,...
#include <bits/stdc++.h> using namespace std; int encode(const string &s, int dig) { int x = 0, k = dig; for (int i = 0; i < dig; i++) { x = k * x; for (int j = i + 1; j < dig; j++) if (s[j] < s[i]) x++; k--; } return x; } int main() { int n, k; scanf("%d", &n); ; scanf("%d", &k); ; ...
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a l...
import java.util.Scanner; public class Main { /** * @param args */ public static void main(String[] args) { Scanner s = new Scanner(System.in); while(s.hasNext()) { // A * pow(X, n) = B boolean ok = false; int a = s.nextInt(), b = s.nextInt(), n = s.nextInt(); for(int x=-5000...
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages ar...
#include <bits/stdc++.h> using namespace std; int N, K, cntEdge[2010]; long long sumEdge[2010]; int main() { scanf("%d%d", &N, &K); int i, j; for (i = 1; i <= N; i++) sumEdge[i] = cntEdge[i] = 0; for (i = 1; i <= N; i++) for (j = i + 1; j <= N; j++) { int u; scanf("%d", &u); if (u != -1) {...
Given an n × n table T consisting of lowercase English letters. We'll consider some string s good if the table contains a correct path corresponding to the given string. In other words, good strings are all strings we can obtain by moving from the left upper cell of the table only to the right and down. Here's the form...
#include <bits/stdc++.h> using namespace std; const int inf = 2000000000; static inline int Rint() { struct X { int dig[256]; X() { for (int i = '0'; i <= '9'; ++i) dig[i] = 1; dig['-'] = 1; } }; static X fuck; int s = 1, v = 0, c; for (; !fuck.dig[c = getchar()];) ; if (c == '-'...
Due to atheistic Soviet past, Christmas wasn't officially celebrated in Russia for most of the twentieth century. As a result, the Russian traditions for Christmas and New Year mixed into one event celebrated on the New Year but including the tree, a Santa-like 'Grandfather Frost', presents and huge family reunions and...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:102400000,102400000") using namespace std; const int inf = 1e9 + 7; const long long linf = 1e18; int a[13333]; inline int fastmax(int x, int y) { return (((y - x) >> (31)) & (x ^ y)) ^ y; } int v[333][333]; double ans[333]; const int D = 2500; int main() { ios:...
The king is left alone on the chessboard. In spite of this loneliness, he doesn't lose heart, because he has business of national importance. For example, he has to pay an official visit to square t. As the king is not in habit of wasting his time, he wants to get from his current position s to square t in the least nu...
import java.io.*; import java.util.*; public class A { void run() throws IOException { char[] z = new char[6]; br.read(z); int s_x = (int) z[0]; int s_y = (int) z[1]; int t_x = (int) z[4]; int t_y = (int) z[5]; int[] mov = new int[8]; if (s_x > t_x) mov[6] = s_x - t_x; if (s_x < t_x) mov[2] =...
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation: <image> A swap operation is the following sequence of actions: * choose two indexes i, j (i ≠ j); * perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Serej...
#include <bits/stdc++.h> using namespace std; long long power(long long x, long long y, long long p) { long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } const int N = 2e2 + 7; const int xinc[] = {0, 0, 1, -1}; const int yinc[...
Anfisa the monkey got disappointed in word processors as they aren't good enough at reflecting all the range of her emotions, that's why she decided to switch to graphics editors. Having opened the BerPaint, she saw a white rectangle W × H in size which can be painted on. First Anfisa learnt to navigate the drawing too...
#include <bits/stdc++.h> const int N = 100 + 4; const double EPS = 1e-8; int signum(double x, double eps = EPS) { return x < -eps ? -1 : x > eps; } struct Point { double x, y; Point() : x(0), y(0) {} Point(double x, double y) : x(x), y(y) {} Point &operator+=(const Point &o) { x += o.x; y += o.y; re...
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order...
/*BY:-PRASANG*/ import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class ImportantThings { static int[] a,b,c; static int temp,n,temp1,count; public static void main(String[]args)throws NumberFormatException,IOException { try{ Scanner sc=new Scanner(Sys...
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the ...
#include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.writ...
Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throu...
// Problem: A. Fancy Fence // Contest: Codeforces - Codeforces Round #165 (Div. 2) // URL: https://codeforces.com/problemset/problem/270/A // Memory Limit: 256 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org) import java.util.*; import java.io.*; import java.lang.*; public class Main { publ...
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the secon...
n=int(input());k=0 if n==1:print(0);exit() a=list(map(int,input().split()));b=[];c=[] for i in range(n*n):b.append(0) for i in range(n): if b[a[i]]==0:b[a[i]]=a[i] else:c.append(a[i]) for i in range(len(c)): for j in range(c[i],len(b)): if b[j]==0:k+=b[j-1]-c[i]+1;b[j]=j;break print(k)
You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n. You need to permute the array elements so that value <image> became minimal possible. In particular, it is allowed not to change order of elements at all. Input The first line contains two integers n,...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 5; const long long INF = 1e18; const int MOD = 1e9 + 7; const double eps = 1e-4; int n, k; long long dp[5005][5005], a[N]; int main() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) scanf("%I64d", &a[i]); sort(a + 1, a + 1 + n); for (int i ...
For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions. He knows that this year n competitions will take place. During the i-th competition the participant must as quickly as possible complete a ride along a straight lin...
#include <bits/stdc++.h> using namespace std; int N; double R, V, W; double s, f; int main() { scanf("%d%lf%lf", &N, &R, &V); W = V / R; for (int i = 0; i < N; i++) { cin >> s >> f; double x = (f - s) / 2; double lb = (x - R) / V, rb = (x + R) / V; for (int j = 0; j < 60; j++) { double mb = ...
Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined: <image> <image> Ayrat is searching through the field. He started at point (...
#include <bits/stdc++.h> using namespace std; const int dx[6] = {-1, -2, -1, 1, 2, 1}, dy[6] = {-2, 0, 2, 2, 0, -2}; int main() { long long n; cin >> n; long long k = max(0LL, (long long)sqrt(n / 3.0) - 1); while (!(3 * k * (k + 1) >= n)) k++; long long ind = 3 * k * (k + 1) - n; long long nowx = 2 * k, now...
Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count ...
#include <bits/stdc++.h> using namespace std; int a[15][15]; int main() { ios::sync_with_stdio(0); memset(a, 0, sizeof(a)); int r, c, n, k; cin >> r >> c >> n >> k; int ann = 0; for (int j = 0; j < n; j++) { int x, y; cin >> x >> y; x--; y--; a[x][y] = 1; } for (int i = 0; i < r; i++...
You are given a table consisting of n rows and m columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa. What is the minimum number of cells with value 1 you can get after applying some number of o...
#include <bits/stdc++.h> using namespace std; const int maxn = (1 << 20) + 10; int n, m, a[maxn], dp[21][maxn]; char ch[maxn]; int main() { scanf("%d%d", &n, &m); memset(a, 0, sizeof(a)); memset(dp, 0, sizeof(dp)); for (int i = 1; i <= n; ++i) { scanf("%s", ch); for (int j = 0; j < m; ++j) a[j + 1] = a[...
Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting. Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. <image> or <image>...
n,m=map(int,input().split()) flag=False f=[0]*100001 E=[[] for i in range(n+1)] e=[tuple(map(int,input().split())) for _ in range(m)] for u,v in sorted(e): E[u]+=[v]; E[v]+=[u] def bfs(nom,col): ch=[(nom,col)] while ch: v,c=ch.pop() if f[v]==0: f[v]=c for u in E[v]: if f[...
You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal. Input The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n ...
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.*; public class MainA { static double eps=(double)1e-6; static int mod=(int)1e9+7; public static void main(String args[]){ InputReader...
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; public class Check2 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new ...
PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the followi...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSe...
The Holmes children are fighting over who amongst them is the cleverest. Mycroft asked Sherlock and Eurus to find value of f(n), where f(1) = 1 and for n ≥ 2, f(n) is the number of distinct ordered positive integer pairs (x, y) that satisfy x + y = n and gcd(x, y) = 1. The integer gcd(a, b) is the greatest common divi...
#include <bits/stdc++.h> using namespace std; int nxi() { int a; cin >> a; return a; } vector<long long> a; void inc(int i, int v) { for (; i < a.size(); i |= i + 1) { a[i] += v; } } long long get(int r) { long long ans = 0; for (; r >= 0; r = (r & (r + 1)) - 1) { ans += a[r]; } return ans; } ...
Tonio has a keyboard with only two letters, "V" and "K". One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximu...
#include <bits/stdc++.h> using namespace std; int main() { char s[105]; int book[105], sum = 0, su = 0; while (cin.getline(s, 105)) { memset(book, 0, sizeof(book)); int len = strlen(s); for (int i = 0; i < len - 1; i++) { if (s[i] == 'V' && s[i + 1] == 'K' && book[i] == 0 && book[i + 1] == 0) { ...
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack. Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and thr...
#include <bits/stdc++.h> using namespace std; const int maxn = 3e5 + 10; int s[maxn]; int flag[maxn]; int main() { int n, i, j; scanf("%d", &n); int k = n * 2, ans = 0, e = 0, num = 0; for (i = 0; i < k; i++) { char c[10]; scanf("%s", c); if (c[0] == 'a') { int x; scanf("%d", &x); ...
Recall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the foll...
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import Counter from bisect import * from math import gcd from itertools import permutations,combinations from math import sqrt,ceil,floor def main(): n,k=map(int,input().split()) ...
You are given a tree (a connected non-oriented graph without cycles) with vertices numbered from 1 to n, and the length of the i-th edge is wi. In the vertex s there is a policeman, in the vertices x1, x2, ..., xm (xj ≠ s) m criminals are located. The policeman can walk along the edges with speed 1, the criminals can ...
#include <bits/stdc++.h> using namespace std; const int maxn = 60, maxc = 1 << 29; int n, s, m; int dp[maxn][maxn][maxn][maxn], x[maxn]; map<int, int> dt[maxn]; vector<pair<int, int> > e[maxn]; int dfs(int u, int par) { int res = x[u]; for (auto [v, w] : e[u]) { if (v == par) continue; res += dfs(v, u); }...
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or...
from sys import stdin n,m,k = map(int,stdin.readline().split()) if n > m: x = n n = m m = x ans = 0 if n==1: if k==1: ans = 1 else: ans = m%2 else: rem = (n-1) * (m-1) ans = pow(2,rem,10**9+7) if k==-1 and (n+m)%2==1: ans = 0 print ans
This year Alex has finished school, and now he is a first-year student of Berland State University. For him it was a total surprise that even though he studies programming, he still has to attend physical education lessons. The end of the term is very soon, but, unfortunately, Alex still hasn't attended a single lesson...
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; set<pair<int, int> > S; inline int query(int l, int r, int k) { auto lit = S.upper_bound(pair<int, int>(l, 0)); if (lit == S.end() || lit->second > r) { if (k == 1) { S.emplace(r, l); return r - l + 1; } else return 0; ...
You are given a string s, initially consisting of n lowercase Latin letters. After that, you perform k operations with it, where <image>. During i-th operation you must erase some substring of length exactly 2i - 1 from s. Print the lexicographically minimal string you may obtain after performing k such operations. I...
#include <bits/stdc++.h> using namespace std; int N, K; string S; int vis[5050][5050]; vector<pair<int, int>> nex[26]; void dfs(int cur, int mask) { if (vis[cur][mask] || cur + 1 + mask > N) return; vis[cur][mask] = 1; int i; nex[S[cur] - 'a'].push_back({cur + 1, mask}); for (i = 0; i < (K); i++) if (mask...
Let's define a split of n as a nonincreasing sequence of positive integers, the sum of which is n. For example, the following sequences are splits of 8: [4, 4], [3, 3, 2], [2, 2, 1, 1, 1, 1], [5, 2, 1]. The following sequences aren't splits of 8: [1, 7], [5, 4], [11, -3], [1, 1, 4, 1, 1]. The weight of a split is t...
from collections import deque import math import os import random import re import sys #n=list(map(int, input().split())) #n=map(int, input().split()) def main(): n=int(input()) ans=n//2+1 print(ans) main()
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that...
import java.util.Arrays; import java.util.Scanner; public class GettinganA { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; long sum = 0; for(int i=0;i<n;++i) { arr[i] = sc.nextInt()...
Kritika visits a aquarium and is astonished to find that the sections of aquarium are numbered in a different way. First Section : -1 Second Section : 1 Third Section : 16 Fourth Section : 60 She realized that there is a pattern in the numbering. Help her in guessing the number of "nth" section. ** Input :**...
print 5170862977916541521
Chandu is weak in maths. His teacher gave him homework to find maximum possible pair XOR in a matrix of size N x M with some conditions. Condition imposed is that, the pair can be formed between sum of elements in a column and sum of elements in a row. See sample explanation for more details. Input: First line consis...
def XOR(a,b): return a ^ b def chandu_xor(matrix): sumN = [] sumM = [] for i in range(0,N): sum_ = 0 for j in range(0,M): sum_ = sum_ + matrix[i][j] sumN.append(sum_) for i in range(0,M): sum_ = 0 for j in range(0,N): sum_ = sum_ + matr...
Stannis borathean is attacking kings landing from three gates.To defend the city Tyrion again comes up with a fair solution. Tyrion has N soldier troops with given strengths. Tyrion wants to divide army into 3 sets such that the sum of strengths in these three sets are as equal as possible. In other words he wants to m...
import itertools,sys t=input() tn=t l=[] while t>0: n=input() l.append(n) t=t-1 li=range(0,tn) tsm=sum(l) rt=[] mdiff=99999 for i in xrange(1,tn-1): for j in itertools.combinations(li,i): diff=list(set(li)-set(j)) #print list(diff)[0] d={0:0} td={0:0} for k ...
Description In a particular language words are written using only two symbols: ones(1) and zeroes(0). A given word N is called “good” if it can be written in the form of concatenation of several(two or more than two) copies of some shorter word, and is called bad otherwise. For example the words 100, 1100, 0010 are “...
dc = dict() def desfac(n): for i in range(2,n): if n%i == 0: dc[i] = 0 def gcd(a, b): while b: a, b = b, a%b return a def fac(a): s = 1 for i in range(2,a+1): s *= i return s zer = int(input()) one = int(input()) md = 10**7+1 span = zer+one ans = 0 for i in range(1, span+1): # all allowe...
Little Deepu and Little Kuldeep are the two best warriors in the realm of Westeros. But, their priorities and their loyalties are very much divided. Little Kuldeep fights for the right, just while Little Deepu fights for the wrong reasons, and supports the wrong ones in the kingdom. Everyone's scared of these two warr...
M=10**9+7 a=[1]*2000001 for i in range(1,2000001): a[i]=(a[i-1]*i)%M for t in range(input()): n=input() print (a[n<<1]*pow(a[n+1],M-2,M)*pow(a[n],M-2,M))%M
Some people are just moody, you just cannot reason with them. Same goes with Natural Numbers. Some of them ultimely want to become 1 or 4 and will evolve infinite times if they have to, to become what they want to. To evolve, they use a function F such that N = F(N). Function F(N) is defined as : F(N) = sum_of_digits(...
mem={} def sum_digits3(n): n=n**2 r = 0 while n: r, n = r + n % 10, n // 10 return r def findnature(n): if(mem.has_key(n)):return mem[n] if(n==1 or n==4): return 1 if(n==9 or n==13): return -1 ans=findnature(sum_digits3(n)) mem[n]=ans return ans for t in range(int(raw_input(...
Little Jhool is friend with the magical creature from Koi Mil Gaya as we all know, called Jaadu. Now, Jhool is learning Mathematics from Jaadu; he wants to know about the Mathematics of the other planet, too. In Jaadu's planet, the sequence of powers of two are called the: The JP. (Jaadu power!) That is, 2^1, 2^2...
import math t = input() for k in range(t): n=input() srt = int(math.sqrt(n)) r=0 for i in range(1,srt+1): r += n/i print 2*r - srt**2 -n
There is a sale in the market on clothes , so as usual N girls gathered there to grab great deals.But due to huge popularity of sale crowd has gone uncontrollable. You being head of management team of the mall has been assigned the task to make them form a queue so that everyone can shop turn-wise. Since queue is going...
def dfs(i, parent): global res, visited if visited[i]: res = False return visited[i] = True for adj in G[i]: if adj != parent: dfs(adj, i) for tc in xrange(input()): V, E = map(int, raw_input().split()) G = [[] for i in xrange(V + 1)] res = True for e in xrange(E): a, b = map(int, raw_input().spl...
Dark with his love for the prime numbers wanted to do some arithmetic so he decided to do some additions. He wants to generate all prime numbers between two given numbers and add them up and decide whether that addition of numbers is a prime number or not? Confused, Simply print "YES"(without quotes) if the sum of pr...
# Sum of prime number # import time import sys # import os import math PRIME_NUMS = [2] def check_prime(n): limit = int(math.sqrt(n)) idx = 0 while(PRIME_NUMS[idx] <= limit): if n % PRIME_NUMS[idx] == 0: return(False) idx += 1 return(True) def main(): m_list = [] n_list = [] no_case = int(sys.stdin.re...
Given a string S which contains only lowercase characters ['a'-'z'] and an integer K you have to find number of substrings having weight equal to K. Weight of characters is defined as : Weight['a']=1 Weight['b']=2 Weight['c']=3 Weight['d']=4 Weight['e']=5 Weight['f']=6 Weight['g']=7 Weight['h']=8 Weight['i']=9 W...
def binary_search(ar, key): lo, hi = 0, len(ar) - 1 while lo<=hi: mid = (lo + hi) >> 1 if ar[mid] == key: return True elif ar[mid]<key: lo = mid + 1 else: hi = mid - 1 return False T = int(raw_input()) for _ in range(T): K = int(raw_input()) ar = [ord(i) - 97 + 1 for i in raw_input()] #print ar cum = [0...
We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i. For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows: * Let S be the set of the vertices numbered L through R. f(L, R) represents the number ...
#include<bits/stdc++.h> using namespace std; const int N=2e5+5; typedef long long ll; int n; int main() { scanf("%d",&n); ll ans=0; for(int i=1;i<n;i++) { int x,y;scanf("%d%d",&x,&y); if(x>y) swap(x,y); ans+=(ll)x*(n-y+1); } ll res=0; for(int i=1;i<=n;i++) res...
You are visiting a large electronics store to buy a refrigerator and a microwave. The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen. You have M discount tic...
#include<bits/stdc++.h> using namespace std; int aa,bb,mm; int a[100100],b[100100],ans=999999999,mna=999999999,mnb=999999999; int main() { scanf("%d%d%d",&aa,&bb,&mm); int i=1; while(i<=aa) { scanf("%d",&a[i]); mna=min(mna,a[i]); ++i; } i=1; while(i<=bb) { scanf("%d",&b[i]); mnb=min(mnb,b[i]); ++i; ...
Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i. In the contest, N foods numbered 1 through N will be presented, and the difficulty of ...
#include <iostream> #include <cstdio> #include <algorithm> #define N 200005 using namespace std; typedef long long ll; ll n, k, l, r = 1e18, m, a[N], b[N]; bool f(ll p) { ll i, t = k; for (i = 0; i < n; i++) { t -= max(0LL, (a[i] * b[i] - p + b[i] - 1) / b[i]); if (t < 0) return 0; } return 1; } int main() {...
You are given a string s consisting of `A`, `B` and `C`. Snuke wants to perform the following operation on s as many times as possible: * Choose a contiguous substring of s that reads `ABC` and replace it with `BCA`. Find the maximum possible number of operations. Constraints * 1 \leq |s| \leq 200000 * Each char...
#include<cstdio> using namespace std; const int _ = 200007; char s[_]; int main() { fread(s,1,_,stdin); long long ans=0,cnta=0; for(int i=0;s[i];i++) { if(s[i]=='A')cnta++; else if(s[i]=='B' && s[i+1]=='C')ans+=cnta,i++; else cnta=0; } printf("%lld\n",ans); return 0; }
There are N cards. The i-th card has an integer A_i written on it. For any two cards, the integers on those cards are different. Using these cards, Takahashi and Aoki will play the following game: * Aoki chooses an integer x. * Starting from Takahashi, the two players alternately take a card. The card should be chose...
import sys input = sys.stdin.readline from itertools import accumulate import bisect n,q = map(int,input().split()) if n%2: a = [0]+list(map(int,input().split())) n += 1 else: a = list(map(int,input().split())) fs = [a[i] if i%2 else 0 for i in range(n)] accss = [0]*n accff = list(accumulate(a)) accfs = list(accu...
There are N boxes arranged in a row from left to right. The i-th box from the left contains a_i manju (buns stuffed with bean paste). Sugim and Sigma play a game using these boxes. They alternately perform the following operation. Sugim goes first, and the game ends when a total of N operations are performed. * Choose...
#include <cstdio> #include <algorithm> using namespace std; const int MAXN = 300000; const int INF = (1 << 30); int s[2], sum[MAXN + 5], a[MAXN + 5], N; bool check(int x) { int k = 0; for(int i=2;i<=N;i+=2) { if( sum[i-1] - k >= x ) k = min(k, sum[i]); } return sum[N] - k >= x; } int main() { scanf("%d", &...
AtCoDeer the deer wants a directed graph that satisfies the following conditions: * The number of vertices, N, is at most 300. * There must not be self-loops or multiple edges. * The vertices are numbered from 1 through N. * Each edge has either an integer weight between 0 and 100 (inclusive), or a label `X` or `Y`. *...
#include<bits/stdc++.h> using namespace std; #define REP(i,st,ed) for(int i=(int)(st),i##end=(int)(ed);i<=i##end;++i) #define DREP(i,st,ed) for(int i=(int)(st),i##end=(int)(ed);i>=i##end;--i) template<typename T>bool chkmin(T &x,const T &y){return x>y?x=y,1:0;} template<typename T>bool chkmax(T &x,const T &y){return x<...
You have two strings A = A_1 A_2 ... A_n and B = B_1 B_2 ... B_n of the same length consisting of 0 and 1. You can transform A using the following operations in any order and as many times as you want: * Shift A by one character to the left (i.e., if A = A_1 A_2 ... A_n, replace A with A_2 A_3 ... A_n A_1). * Shift A...
#include<bits/stdc++.h> using namespace std; template <typename T> void chmax(T &x,const T &y) { if(x<y)x=y; } template <typename T> void chmin(T &x,const T &y) { if(x>y)x=y; } #define rep(i,l,r) for(int i=l;i<=r;++i) #define per(i,r,l) for(int i=r;i>=l;--i) const int N=2000+5,inf=N*10; char qa[N*2],*a=qa+N,b[N]; in...
AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W. If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the ho...
#include <iostream> using namespace std; int main(){ int w, a, b; cin >> w >> a >> b; if(abs(a-b)<=w) cout << 0 << endl; else cout << abs(a-b)-w << endl; return 0; }
We have a tree with N vertices. The vertices are numbered 1, 2, ..., N. The i-th (1 ≦ i ≦ N - 1) edge connects the two vertices A_i and B_i. Takahashi wrote integers into K of the vertices. Specifically, for each 1 ≦ j ≦ K, he wrote the integer P_j into vertex V_j. The remaining vertices are left empty. After that, he...
#include <bits/stdc++.h> using namespace std; const int N = 100005; const int inf = 1e6; int n, k; vector<int> G[N]; int L[N], R[N], a[N]; int parity[N]; void dfs(int u, int p) { L[u] = -inf, R[u] = inf; if (a[u] != -1) L[u] = R[u] = a[u], parity[u] = (a[u] & 1); for (int v : G[u]) if (v != p) { dfs(v, u); if...
Counting was a difficult task in ancient Rome. The Arabic numerals 0,1,2,3,…, 9 have not yet been disseminated. Instead, the following symbols were used: Arabic numerals | Roman numerals | Arabic numerals | Roman numerals | Arabic numerals | Roman numerals --- | --- | --- | --- | --- | --- 1 | I | 11 | XI | 30 | XXX |...
import sys r={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000} for e in sys.stdin: a=0 n=[r[c]for c in e.strip()] for i in range(len(n)): if i+1<len(n)and n[i]<n[i+1]:a-=n[i] else:a+=n[i] print(a)
There is a dice with one letter of the alphabet (a ~ z, A ~ Z) drawn on each side. <image> Consider combining eight such dice to make a 2 x 2 x 2 cube. <image> There are conditions on how to combine the dice, and the facing faces of each dice must have the same alphabet, one in lowercase and the other in upperc...
#include <bits/stdc++.h> using namespace std; template <typename T> struct Dice { vector<T> val; Dice(){ val.resize(6); } Dice(vector<T> &v) { val = v; } bool operator == (const Dice &t) const { return val == t.val; } bool operator != (const Dice &t) const { return val != t.val; } bool operator < (const Di...