input
stringlengths
29
13k
output
stringlengths
9
73.4k
Example Input 7 4 DEFG FEDA EFGB BGEA AGFD DABC CADE Output ABCDEFG
#include<stdio.h> #include<algorithm> #include<string> #include<set> using namespace std; char in[20][20]; char ret[20]; int used[20]; int t[20]; int n; int m; set<pair<pair<int,int>,string> >S; int calc(int a,string b,int c){ if(S.count(make_pair(make_pair(a,c),b)))return 0; S.insert(make_pair(make_pair(a,c),b)); i...
Big Maze You work in the Jumbo Amusement Garden, a huge amusement park called "JAG" for short. The site of this amusement park is vast, and all the attractions are huge. This time, a new huge maze attraction "Big Maze" will be introduced to JAG. Looking at the plan view, the shape of the Big Maze will be a rectangle ...
# include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(n);i++) typedef long long ll; typedef vector<int> vi; // uf int data[1252]; void init(int n){ REP(i,n)data[i]=-1; } int root(int x){ return data[x]<0?x:(data[x]=root(data[x])); } void unite(int x,int y){ x=root(x); y=root(y); if(...
Problem Statement You are given a positive integer sequence $A$ of length $N$. You can remove any numbers from the sequence to make the sequence “friendly". A sequence is called friendly if there exists an integer $k$ (>1) such that every number in the sequence is a multiple of $k$. Since the empty sequence is friendl...
#include <bits/stdc++.h> #define int long long #define pa pair<int,int> #define mp make_pair #define pb push_back using namespace std; signed main(){ cin.tie(0); ios::sync_with_stdio(false); int n; cin>>n; vector<int> ve(n); for(int i=0;i<n;i++)cin>>ve[i]; map<int,int>ma; for(...
Divide Cake into Five Segtree is a quintuplet tutor. Today is Christmas Eve, so I'm trying to divide the round cake into five equal parts for the quintuplets. The cake is divided into $ N $ pieces from the center in a fan shape, $ i $ th and $ i + 1 $ th ($ 1 \ leq i \ leq N -1 $), $ N $ th and $ 1 $ The second piece...
#include <bits/stdc++.h> using namespace std; int main(){ int N, Y; cin >> N >> Y; vector<int64_t> A(2*N), S(2*N+1); for(int i=0; i<N; i++){ cin >> A[i]; A[i+N] = A[i]; } for(int i=0; i<2*N; i++){ S[i+1] = S[i] + A[i]; } int64_t L = accumulate(A.begin(), A.end(),...
Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E). Constraints * 1 ≤ |V| ≤ 10,000 * 0 ≤ |E| ≤ 100,000 * 0 ≤ wi ≤ 10,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-...
#include<cstdio> #include<vector> #include<queue> #include<algorithm> using namespace std; //Prim struct edge{int to,cost;}; int main(){ int V,E; vector<edge> G[10000]; scanf("%d %d",&V,&E); for(int i=0;i<E;i++){ int s,t,w; scanf("%d %d %d",&s,&t,&w); edge tmp; tmp.cost = w; tmp.to = t; ...
This is a very simple problem. Given the value of N and K, you need to tell us the value of the binomial coefficient C(N,K). You may rest assured that K ≤ N and the maximum value of N is 1,000,000,000,000,000. Since the value may be very large, you need to compute the result modulo 1009. Input The first line of the in...
memo = {} def C(n, r, p): ''' {n choose r} modulo p (p is prime) ''' if r < 0 or r > n: return 0 if r == 0 or r == n: return 1 if n >= p: # Lucas theorem return C(n/p, r/p, p) * C(n%p, r%p, p) % p if (n, r, p) not in memo: memo[n, r, p] = (C(n-1, r-1, p) + C(n-1, r, p...
Little johny was working on the co-ordinate plane.As he is still a novice he calculates the distance between two points P1 and P2 in the wrong way.He calculates the distance between P1(x1,y1) and P2(x2,y2) as : D(P1,P2) = |x1 - x2| + |y1 - y2| His teacher gave him a homework to calculate the area of a circle of radius ...
t=int(raw_input()) for asd in range(t): n=int(raw_input()) print 2*n*n
Presti Digitator, the world-famous magician, is highly dissatisfied with his way of shuffling cards. Just yesterday, a perky guy in the audience demanded that he shuffle the cards once again, and he was aghast to see that the bottom card had not changed. Even though Mr. Digitator pacified the crowd with a few excellent...
shuffle_list=[0,0,1] for i in xrange(3,21): shuffle_list.append((i-1)*(shuffle_list[-1]+shuffle_list[-2])) for i in xrange(input()): print shuffle_list[input()]
Harish has decided to go to Arya's hotel this morning. We all know he is crazy for masala dosas. And as usual he is always hungry. He decided to order all the masala dosas at once. But then he realised that he did not have enough money to buy all of them. So he decided to share the amount with his friend Ozil. But both...
# python3 if __name__ == "__main__": t = int(raw_input()) l = [] i = 0 while(i < t and t <= 10**6): ch = int(raw_input()) if(ch <= 10**18): l.append(ch) i = i + 1 for i in l: if(i % 2 == 0): print "YES" else: print "NO"
Shrija's brother Vaibhav is a very mischievous boy . He has messed a lot of books of Shrija on floor . Now Shrija is very angry . Seeing her sister angry he promises to arrange them on N empty stacks numbered from 1 to N . Shrija also felt that she should help her brother in arranging the books. So she gives Vaibhav a ...
n,m=map(int,raw_input().split()) a=[0]*(n+2) #print a for i in range(m): left,right=map(int,raw_input().split()) a[left]+=1 a[right+1]-=1 for j in range(1,n+1): a[j]+=a[j-1] a=a[:n+1] a.sort() #print a print a[(n/2)+1]
Problem Statement Chef Diablo has set up a stall for selling his famous Modaks in the Trinity fest. He wants to earn as much profit as he can. So he has bought a chemical that increases the taste level of the Modaks. The tastier the Modaks the higher he can price them. This chemical is very costly hence he applies on...
T=input() while T: T-=1 tl,n=[int(x) for x in raw_input().split()] if n==0: n=1 print pow(tl,n,pow(10,9)+7)
You are given two strings s and t, both consisting only of lowercase Latin letters. The substring s[l..r] is the string which is obtained by taking characters s_l, s_{l + 1}, ..., s_r without changing the order. Each of the occurrences of string a in a string b is a position i (1 ≤ i ≤ |b| - |a| + 1) such that b[i..i...
ch=input() l=list(map(int,ch.split())) m=l[0] n=l[1] p=l[2] s=input() t=input() l1=[] for i in range(p): ch=input() l1.append(ch) res=0 l2=[0] for i in range (len(t)-1): l2.append(0) for i in range ((len(t)-1),len(s)): if s[(i-len(t)+1):(i+1)]==t: res+=1 l2.append(re...
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super...
#include <bits/stdc++.h> using namespace std; vector<int> v[102]; bool par[102][102]; bool vis[102]; int cyc = 0; void dfs(int nd, int p) { vis[nd] = true; int z = v[nd].size(); int nx; for (int i = 0; i < z; i++) { nx = v[nd][i]; if (vis[nx]) { if (nx != p && p != 0) { if (par[nx][nd] || ...
JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way. First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he de...
//make sure to make new file! import java.io.*; import java.util.*; public class C520{ public static long MOD = 1000000007L; public static void main(String[] args)throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System...
The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But ...
#include <bits/stdc++.h> using namespace std; long long n, a[1001], cnt = 0; long long s; signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> s; for (int i = 1; i <= n; i++) { cin >> a[i]; } sort(a + 1, a + n + 1); for (int i = 2; i <= n; i++) { cnt += a[i] - a[1]; ...
Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k — your skill in Cardbluff. Each judge has a number a_i — an indicator of uncertainty about ...
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 1000000; int n; long long skill; long long a[MAXN]; int cost[MAXN]; vector<long long> p; long long b[MAXN]; long long c[MAXN]; int nc; vector<int> copt[MAXN]; pair<int, int> ord[...
Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the di...
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int maxn = 2005; long long n, m; long long d[maxn]; int vis[maxn]; vector<long long> g[maxn], w[maxn]; char s[maxn][maxn]; void dfs(int x) { vis[x] = 1; for (int i = 0; i < g[x].size(); i++) { int nxt = g[x][i]; int wgt = w[x][i]; ...
A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her. Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens: * Two numbers i and...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const long long N = 105; long long m; struct node { long long data[N][N]; node operator*(node b) { node t; for (long long i = 0; i <= m; i++) { for (long long j = 0; j <= m; j++) { t.data[i][j] = 0; } } ...
The only difference between easy and hard versions is constraints. Nauuo is a girl who loves random picture websites. One day she made a random picture website by herself which includes n pictures. When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal proba...
#include <bits/stdc++.h> using namespace std; int n, m; int a[55], b[55]; int dp[55][55][55]; const int Mod = 998244353; int nii[5555]; int ksmii(int a, int b) { if (!b) { return 1; } int x = ksmii(a, b >> 1); x = 1LL * x * x % Mod; if (b & 1) { x = 1LL * x * a % Mod; } return x; } int main() { ...
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c...
string = input().split() first = string[0] second = string[1] third = string[2] string.sort(key=lambda x: int(x[0])) if first == second == third or first[1] == second[1] == third[1] and all(int(string[i][0]) == int(string[i - 1][0]) + 1 for i in range(1, 3)): print(0) elif (first == second or second == third or thi...
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the que...
import java.io.*; import java.util.*; import java.math.*; public class P120B { @SuppressWarnings("unchecked") public void run() throws Exception { boolean [] played = new boolean [nextInt()]; int k = nextInt() - 1; for (int i = 0; i < played.length; i++) { played[i] = (nextInt() == 0); } ...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how ...
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import java.util.Queue; import static java.lang.Math.max; import static java.lang.Math.min; public class C implements Runnable{ // SOLUTION!!! // HACK ME PLEASE IF YOU CA...
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2). You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the ...
import java.io.*; import java.util.*; import java.math.*; public class p1251D { public class Emp implements Comparable<Emp>{ public long l; public long r; public long s; public Emp (long l, long r, long s) { this.l = l; this.r = r; this.s = s; } public int compareTo(Emp e) { if(this.l < e....
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of ope...
n=int(input()) s=list(input()) s.append("B") b=s.count("B") w=len(s)-b if b==1 or w==0: print(0) exit(0) s.pop(n) b-=1 if b%2 and w%2: print("-1") exit(0) if b%2==0: p=[] for i in range(s.index('B'),n-1): if s[i]=="W": continue if s[i+1:].count('B')==0: ...
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100)...
import java.io.*; import java.util.*; import java.math.*; public class Main{ public static void main(String[] args) throws Exception { IO io = new IO(); PrintWriter out = new PrintWriter(System.out); Solver sr = new Solver(); sr.solve(io,out); out.flush(); out.close(); } static class Solver { ...
You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible. Input Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). The first line of...
#include <bits/stdc++.h> using namespace std; void err() { cout << endl; } template <class T, class... Ts> void err(const T& arg, const Ts&... args) { cout << arg << ' '; err(args...); } using ll = long long; using db = double; using pII = pair<int, int>; const int INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3...
This is the hard version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved. Chiori loves dolls and now she is going to decorate her bedroom! <image> As a doll collector, Chiori has got n dolls. The i-th doll has a non-negati...
#include <bits/stdc++.h> using namespace std; using LL = long long; namespace _buff { const size_t BUFF = 1 << 19; char ibuf[BUFF], *ib = ibuf, *ie = ibuf; char getc() { if (ib == ie) { ib = ibuf; ie = ibuf + fread(ibuf, 1, BUFF, stdin); } return ib == ie ? -1 : *ib++; } } // namespace _buff LL read() { ...
There are two infinite sources of water: * hot water of temperature h; * cold water of temperature c (c < h). You perform the following procedure of alternating moves: 1. take one cup of the hot water and pour it into an infinitely deep barrel; 2. take one cup of the cold water and pour it into an infin...
# abs((desired*(2*n + 1) - ((n+1)*hot + n*cold))/(2*n + 1)) #EXPERIMENTING WITH LOSS DEFINTION - float ops ko aage peeche kar diya import sys def input(): return sys.stdin.readline().rstrip() testcases = int(input()) answers = [] def loss(two_n_plus_one, hot, cold, desired): n = two_n_plus_one//2 # if n == 0: #...
Ivan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their ...
#include <bits/stdc++.h> using namespace std; typedef struct { char c[15000]; int ipos, len; } st; bool glas(char s) { if (s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u') return true; return false; } int findPos(st* a, int k) { if (a->len == -1) a->len = strlen(a->c); if (a->ipos == -2) return -1;...
Sarah has always been a lover of nature, and a couple of years ago she saved up enough money to travel the world and explore all the things built by nature over its lifetime on earth. During this time she visited some truly special places which were left untouched for centuries, from watching icebergs in freezing weath...
#include <bits/stdc++.h> int n, m, cnt; long long tr[400010], tags[400010], tage[400010]; void addtag(long long s, long long e, int x, int l, int r) { tr[x] += s * (r - l + 1) + 1ll * (r - l) * (r - l + 1) / 2 * e; tags[x] += s, tage[x] += e; } void pushdown(int x, int ls, int rs, int l, int mid, int r) { if (tag...
This is an interactive problem Ginny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a dir...
#include <bits/stdc++.h> using namespace std; const int N = 1e3 + 10; const long long mod = 998244353; const long long Inf = 1e18; int inv[1 << 20], cnt, f[N], val[N], mini, id[N]; vector<int> g[N]; bool vis[N]; void dfs(int u) { vis[u] = 1; for (auto v : g[u]) { if (!vis[v]) dfs(v); val[u] += val[v] * f[v]...
Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3. You have a sequence of n integers [1, 2, ..., n] an...
import java.io.*; import java.util.*; public final class h{ static int T, N, K, M, b[], pfx[]; public static void main(String args[]) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); T = Intege...
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows t...
#include <bits/stdc++.h> #define F first #define S second #define ll long long #define pi acos(-1.0) #define pb push_back #define mp make_pair #define lb printf("\n"); #define INF 1000000000000000000 #define LES -1000000000000000000 using namespace std; //---------------All Solution Functions Start Here--------------/...
Phoenix loves playing with bits — specifically, by using the bitwise operations AND, OR, and XOR. He has n integers a_1, a_2, ..., a_n, and will perform q of the following queries: 1. replace all numbers a_i where l ≤ a_i ≤ r with a_i AND x; 2. replace all numbers a_i where l ≤ a_i ≤ r with a_i OR x; 3. replac...
#include <bits/stdc++.h> using namespace std; const int N = 1e7 + 5, K = 20, W = 1 << K; int n, q, tot; int ls[N], rs[N], sum[N], or0[N], or1[N], tag[N], dep[N]; void pushup(int p) { sum[p] = sum[ls[p]] + sum[rs[p]]; or0[p] = or0[ls[p]] | or0[rs[p]]; or1[p] = or1[ls[p]] | or1[rs[p]]; } void Tag(int p, int k) ...
Welcome to Rockport City! It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet a dollars and Ronnie has bet b dollars. But the fans seem to be disappointed. The excitement of the fans is given by gcd(a,b), where gcd(x, y) denotes the [greatest common divisor (GCD)]...
import java.util.Scanner; /** * * @author Acer */ public class ExcitingBets { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0){ long a = sc.nextLong(); long b = sc.nextLong(); if(a=...
<image> Input The input contains a single integer a (1 ≤ a ≤ 18257). Output Print a single integer output (1 ≤ output ≤ 2·109). Examples Input 2 Output 13
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; if (n == 1) { cout << 1; return 0; } cout << n * (n - 1) * 6 + 1; return 0; }
Berland has managed to repel the flatlanders' attack and is now starting the counter attack. Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we d...
#include <bits/stdc++.h> using namespace std; const int maxn = 5 * 1e5 + 1000; vector<int> G[maxn], ans[maxn]; set<int> s; set<int>::iterator ite; int num[maxn], cnt, res; void bfs(int x) { s.erase(x); queue<int> que; ans[res].push_back(x); que.push(x); cnt = 0; while (que.size()) { int cur = que.front(...
Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into n × n cells (represented as unit squares), each cell has some number. At the beginning of the race Furik stands in a cell with coordinates (1, 1), and Rubik stands in a cell wi...
#include <bits/stdc++.h> using namespace std; const int MAXN = 3e2 + 10; const int INF = 1e8 + 100; int dp[MAXN][MAXN][MAXN]; bool vis[MAXN][MAXN][MAXN]; int a[MAXN][MAXN]; int memo(int r, int d, int R) { if (vis[r][d][R]) return dp[r][d][R]; vis[r][d][R] = true; int D = r + d - R; int &res = dp[r][d][R]; res...
Urpal lives in a big city. He has planned to meet his lover tonight. The city has n junctions numbered from 1 to n. The junctions are connected by m directed streets, all the roads have equal length. Urpal lives in junction a and the date is planned in a restaurant in junction b. He wants to use public transportation...
#include <bits/stdc++.h> using namespace std; inline long long rd() { long long _x = 0; int _ch = getchar(), _f = 1; for (; !isdigit(_ch) && (_ch != '-') && (_ch != EOF); _ch = getchar()) ; if (_ch == '-') { _f = 0; _ch = getchar(); } for (; isdigit(_ch); _ch = getchar()) _x = _x * 10 + _ch - '0...
One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c ar...
#include <bits/stdc++.h> using namespace std; const int MAX = 100005; const int INF = 1 << 28; const double EPS = 1e-7; int N; int v[MAX]; bool mark[MAX]; vector<int> G[MAX]; map<int, set<int> > M; bool fill(int a, int b, int c) { v[0] = a; v[1] = 1; v[2] = b; v[3] = c; for (int i = 1; i <= (N); ++i) mark[i] ...
A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n). A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1. You have integer n. Find some lucky permutation p of size n. Input T...
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; if ((n / 2) % 2 > 0) { cout << -1; return 0; } for (int i = 1; i <= n / 4; i++) { cout << i * 2 << ' ' << n - (i - 1) * 2 << ' '; } if (n % 2 != 0) cout << (n + 1) / 2 << ' '; for (int i = n / 4; i >= 1; i--) { c...
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded. The problem is the follows. Given n points in the plane, find a pair of points between...
n,k = map(int,input().split()) if n*(n-1) <= k*2: print('no solution') else: for i in range(n): print(0,i)
Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets ...
I=lambda:map(int, raw_input().split()) def main(): d={} s = raw_input() l = input() for c in s: d[c] = d.get(c,0) + 1 if len(d) > l: print -1 return lo = 0 hi = 10000 while lo + 1 < hi: mid = (lo + hi) / 2 c = 0 for x in d.itervalues(): ...
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework. The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them...
n = int(input()) lst = list(map(int,input().split())) a = list(zip(lst,lst[1:])) record = [] for x in a: s,e = min(x[0],x[1]),max(x[0],x[1]) for y in record: if y[0]<s<y[1]<e or s<y[0]<e<y[1]: exit(print("yes")) record.append((s,e)) print("no")
Let's assume that we have a sequence of doubles a1, a2, ..., a|a| and a double variable x. You are allowed to perform the following two-staged operation: 1. choose an index of the sequence element i (1 ≤ i ≤ |a|); 2. consecutively perform assignments: <image>. Let's use function g(a, x) to represent the large...
#include <bits/stdc++.h> using namespace std; const int T = 60, maxn = 3e5 + 5; struct node { int id, val; } a[maxn]; int n; int pre[maxn], nxt[maxn]; bool cmp(node a, node b) { return a.val == b.val ? a.id < b.id : a.val < b.val; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a...
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number n, modulo m. Number x is considered close to number n mod...
#include <bits/stdc++.h> using namespace std; template <class T> T abs(T x) { return x > 0 ? x : -x; } long long n; int m; int c[10]; int i[10]; int d[18]; int main() { scanf("%I64d %d", &n, &m); for (int j = 0; j < 10; ++j) c[j] = 0; for (; n > 0; n /= 10) ++c[n % 10]; long long f[c[0] + 1][c[1] + 1][c[2] + ...
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct segments [li, ri] ...
#include <bits/stdc++.h> const int N = 3000000 + 7; int n, m; int l[N], r[N]; int e[N]; std::vector<std::pair<int, int>> g[N]; int t[N]; int ans[N]; void dfs(int s); int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) scanf("%d%d", l + i, r + i), e[i] = l[i], e[i + n] = ++r[i]; std::sort(e + 1, e + n *...
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each...
#include <bits/stdc++.h> using namespace std; int main() { long long q, t, n, k, d1, d2, x, y; cin >> t; while (t--) { cin >> n >> k >> d1 >> d2; q = k; k = n - k; if (k - (d1 + d2) >= 0) { x = (d1 + d2 + q) / 3; y = (q - d1 - d2) / 3; if ((k - (d1 + d2)) % 3 == 0 && (d1 + d2 + q...
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch. Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number...
#include <bits/stdc++.h> int main() { int n; scanf("%d", &n); int ar[n + 1]; for (int i = 1; i <= n; i++) scanf("%d", &ar[i]); int q; ar[0] = 0; scanf("%d", &q); int arr[q]; for (int i = 0; i < q; i++) scanf("%d", &arr[i]); for (int i = 2; i <= n; i++) ar[i] += ar[i - 1]; int mid, st, fi; mid = ...
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the po...
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class Main { static class Reader { BufferedReader r;...
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower le...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 5; const int mod = 1e9 + 9; map<pair<int, int>, int> mp; pair<int, int> p[MAXN]; set<int> st; int num[MAXN]; long long fast_pow(long long x, int n) { long long ret = 1; while (n) { if (n & 1) { ret = ret * x % mod; } x = x * x % ...
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. <image> A group of bears is a non-empty contiguous segment of the line. The size of ...
#include <bits/stdc++.h> using namespace std; long long max(long long a, long long b) { return a > b ? a : b; } long long min(long long a, long long b) { return a < b ? a : b; } void fun(int arr[], int n) { stack<int> s; int left[n + 1]; int right[n + 1]; for (int i = 0; i < n; i++) { left[i] = -1; righ...
Fibonotci sequence is an integer recursive sequence defined by the recurrence relation Fn = sn - 1·Fn - 1 + sn - 2·Fn - 2 with F0 = 0, F1 = 1 Sequence s is an infinite and almost cyclic sequence with a cycle of length N. A sequence s is called almost cyclic with a cycle of length N if <image>, for i ≥ N, except for...
#include <bits/stdc++.h> using namespace std; template <typename type> type beMin(type &a, type b) { return a = (a < b ? a : b); } template <typename type> type beMax(type &a, type b) { return a = (a > b ? a : b); } long long read() { long long a = 0, c = getchar(), s = 0; while (!isdigit(c)) s |= c == '-', c =...
Wilbur the pig really wants to be a beaver, so he decided today to pretend he is a beaver and bite at trees to cut them down. There are n trees located at various positions on a line. Tree i is located at position xi. All the given positions of the trees are distinct. The trees are equal, i.e. each tree has height h....
#include <bits/stdc++.h> using namespace std; int n, i, j, l[2002], r[2002]; long double p, h, x[2002]; bool mark[2002][2002][2][2]; long double dp[2002][2002][2][2], z = 0.5; void rec(int s, int e, int f1, int f2) { if (mark[s][e][f1][f2]) return; long double answ = 0; mark[s][e][f1][f2] = true; rec(s + 1, e, ...
Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1. You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all a...
def answer(n): x=[] while(n!=0): temp=n%2 n//=2 x.append(temp) for i in reversed(range(len(x))): if x[i]==1: print(i+1,end=' ') n=int(input()) answer(n)
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simulta...
#include <bits/stdc++.h> using namespace std; template <class T> inline void rread(T& num) { num = 0; T f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') num = num * 10 + ch - '0', ch = getchar(); num *= f; } inline i...
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know l...
#include <bits/stdc++.h> using namespace std; const int N = 10010; long long t2[N], t3[N]; void solve() { string s; cin >> s; int n = s.size(); s += "#####"; long long res = 0; set<string> suffs; t2[n - 2] = 1; t3[n - 3] = 1; for (int i = n - 1; i >= 5; --i) { if (i + 3 < n) { if (s.substr(i...
Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal t...
#include <bits/stdc++.h> using namespace std; const double EPS = 1e-8; const double INF = 1e100; struct Point { double x, y; Point() {} Point(double x, double y) : x(x), y(y) {} double abs() const { return hypot(x, y); } double arg() const { return atan2(y, x); } Point operator*(double o) const { return Poi...
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y. In a single second, he can modify the length of a single side of the current triangle such th...
#include <bits/stdc++.h> using namespace std; int minim(int a, int b, int c) { if (a <= b and a <= c) return 1; else if (b <= a and b <= c) return 2; else if (c <= a and c <= b) return 3; else return 0; } int main() { int x, y; cin >> x >> y; int side1, side2, side3; side1 = side2 = side...
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg...
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class CodeForces { private final BufferedReader reader; private final PrintWriter writer; private StringTokenizer tokenizer; private void solve() { int n = nextInt(); int[] l = new...
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in t...
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Bit...
Boris really likes numbers and even owns a small shop selling interesting numbers. He has n decimal numbers Bi. Cost of the number in his shop is equal to the sum of costs of its digits. You are given the values cd, where cd is the cost of the digit d. Of course, Boris is interested in that numbers he owns have the max...
#include <bits/stdc++.h> char s[1000][1010], t[1010]; int dp[1010][1001], a[1000], p[1000], f[1000], c[20], n; bool b[1001]; int len[1000], l; inline int cost(int i, int j, int x) { return x || j < len[i] || j < l ? c[x] : 0; } inline void umax(int& m, int u) { u > m && (m = u); } void sort(int d) { static int b[10...
Thanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she...
#include <bits/stdc++.h> using namespace std; struct Node { Node() {} Node(string s, string p) : s(s), p(p) {} string s, p; } a; int i, j, k, n, m; char c; inline Node Solve(int n) { Node Tmp; if (n == 1) { c = 'a'; return Node("a", "a"); } if (n == 2) { c = 'b'; return Node("abb", "ab"); ...
You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters. Suitability of string s is calculated by following metric: Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulti...
from collections import Counter import sys input = sys.stdin.readline s = list(input().rstrip()) t = input().rstrip() cnt1 = Counter(s) cnt2 = Counter(t) if cnt1['?'] == 0: print(*s, sep='') exit() ok, ng = 0, 10**9 while abs(ok - ng) > 1: mid = (ok + ng) // 2 hatena = cnt1['?'] for k, v in cnt2....
Wherever the destination is, whoever we meet, let's render this song together. On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage. On the sides of t...
#include <bits/stdc++.h> using namespace std; const long long MAXN = 200000 + 10; const long long INF = 1000000000 + 9; long long n, h, w; vector<pair<long long, long long>> v; map<pair<long long, long long>, long long> M; long long diag(pair<long long, long long> a) { return a.first + a.second; } int32_t main() { io...
A sequence a0, a1, ... is called a recurrent binary sequence, if each term ai (i = 0, 1, ...) is equal to 0 or 1 and there exist coefficients <image> such that an = c1·an - 1 + c2·an - 2 + ... + ck·an - k (mod 2), for all n ≥ k. Assume that not all of ci are zeros. Note that such a sequence can be uniquely recovere...
#include <bits/stdc++.h> using namespace std; int ans[55] = {0, 0, 3, 3, 3, 15, 3, 3, 29, 17, 255, 5, 83, 4095, 43, 3, 63, 15, 63, 63, 1023, 63, 3, 63, 27, 15, 4095, 39, 4095, ...
Lakhesh loves to make movies, so Nephren helps her run a cinema. We may call it No. 68 Cinema. <image> However, one day, the No. 68 Cinema runs out of changes (they don't have 50-yuan notes currently), but Nephren still wants to start their business. (Assume that yuan is a kind of currency in Regulu Ere.) There are ...
#include <bits/stdc++.h> using namespace std; int n, l, r; long long mod; vector<int> primes; vector<long long> powPrime, modFact[100000 + 1]; long long modPow(long long a, long long pow, long long m) { if (pow == 0) return 1; if (pow & 1) return (a * modPow(a, pow ^ 1, m)) % m; else { long long sqrt = mo...
As we all know, Eleven has special abilities. Thus, Hopper convinced her to close the gate to the Upside Down World with her mind. Upside down monsters like to move between the worlds, so they are going to attack Hopper and Eleven in order to make them stop. The monsters live in the vines. The vines form a tree with n ...
#include <bits/stdc++.h> using namespace std; int n, m, Q, E, cnt, cntpoi, tree[200001], ret[200001]; int to[200001], nex[200001], fir[200001], w[200001], pa[200001]; int st[200001], ed[200001], size[200001], co[200001], dep[200001]; int acori[200001], acrev[200001]; vector<int> vec[200001]; bool vis[200001]; int posor...
Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible. One day, as he was reading the game's forum ...
#include <bits/stdc++.h> using namespace std; long long n; int k; const int maxN = 105; int a[maxN]; const int maxP = 6324554 + 100; long long x[maxP]; int y[maxP]; long long nx[maxP]; int ny[maxP]; long long cx[maxP]; int cy[maxP]; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n; cin ...
In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are l...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a wa...
#include <bits/stdc++.h> using namespace std; int a[100]; int b[100]; map<int, int> mp; int k = 0; set<int> sl[20010], sr[20010], sll, srr; set<int>::iterator it; int main() { ios::sync_with_stdio(false); int n, m; cin >> n >> m; for (int i = 1; i <= n; ++i) cin >> a[i]; for (int i = 1; i <= m; ++i) cin >> b[...
You have a set of n distinct positive numbers. You also have m colors. Your colors are labeled from 1 to m. You're also given a list c with m distinct integers. You paint the numbers according to the following rules: For each i in order from 1 to m, paint numbers divisible by c[i] with color i. If multiple rules apply...
# get number of integers and noumber of colours n, m = map(int, raw_input().split()) # paint integer c = map(int, raw_input().split()) c.insert(0, c[0]) my_ints = map(int, raw_input().split()) result = [] result.append(c[my_ints[0]]) # for every integer in my_ints for integer in range(1, len(my_ints)): # start...
Today, N candies were placed on the table. At any point, for the purpose of clarity, let X represent the number of candies left on the table. Every day, at 9 PM, if the number of candies remaining is divisible by 2, the child will take exactly X/2 candies. Otherwise, he will take (X+1)/2 candies. In addition, every d...
import sys def main(): I=sys.stdin.readlines() x=int(I[0]) for i in xrange(x): n,t=map(int,I[i+1].split()) for j in xrange(t): if(n%2==0): n=n/2 else: n=n-((n+1)/2) n=n-(n//4)...
Hansa is throwing a birthday party. Seeing the extravagant parties thrown by her friends in the past, Hansa too decided to do something unique. Being a Computer Engineer herself, she knew just how to do it. She sent password-protected e-invites to T of her friends. Along with each of those e-invites there would be a nu...
t=input() while t: a=map(str, raw_input("").split()) base=int(a[0]) s=a[1] k=1 ans=0 while len(s)>0: l=s[-1] if ord(l)<59: l=ord(l)-48 else: l=ord(l)-87 ans+=k*l k*=base s=s[:-1] x=str(ans) print sum(int(i) for i in ...
Gazi is a very talented mathematician, recently he discovered the majestic power of the number '9' so he wants to play a game with you. He tells you to pick any real integer [from 10 to 10^200], then subtract sum of digits of this number from the number itself. You will get another number, now omit any digit from this ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' #print 'Hello World!' t=input() while t>0: t-=1 s=raw_input() for i in range(0,9): x=s.replace("_",str(i)) if int(x)%9==0: c=i break if c==0: print "0 or 9" else: pri...
Little Shino is interested in the fighting tournaments. Once she went to watch one of the tournaments. There were N fighters and i^{th} fighter will be represented by i. Each fighter has some distinct strength. Rules of the tournament are: Each fight will have 2 fighters. In a fight, fighter with more strength will w...
N,Q=map(int,raw_input().split()) arrx=map(int,raw_input().split()) winners=[0]*N players=[] for i in xrange(0,N-1,2): if arrx[i]<arrx[i+1]: winners[i]=1 players.append(i+1) else: winners[i+1]=1 players.append(i) if N%2==1: players.append(N-1) winners[N-1]-=1 numround=2 while len(players)>1: ...
Solve the mystery HINT : Digital Display Input : First line has an integer T. Next T lines has an integer N in each line. It is guaranteed that N never starts with 0 unless value is equal to zero. Output : Print the output for each test case in new line. Constraints : 1 ≤ T ≤ 1000 0 ≤ |N| ≤ 1000 |N| is number of dig...
def digital(t): dc = 0 while dc < t: dic = {'0':6, '1':2, '2':5, '3':5, '4':4, '5':5, '6':6, '7':3, '8':7, '9':6} s = raw_input() sum = 0 for e in s: sum = sum + dic[e] print sum dc += 1 t = int(raw_input()) digital(t)
The arrival times of N trains are given in the format hours : minutes : seconds. However for the sake of simplicity the time is considered only in seconds format i.e., 3600hours + 60minutes + seconds (Let's say this x). Now if x is a prime number, the halt for the train at the station is 5 minutes, if it's an odd numbe...
def primes(n): if n==2: return[2] elif n<2: return [] s=range(3,n+1,2) mroot=n**0.5 half=(n+1)/2 -1 i=0 m=3 while (m<=mroot): if s[i]: j=(m*m-3)/2 s[j]=0 while(j<half): s[j]=0 j+=m i+=1 m=2*i+3 return [2]+[x for x in s if x] p=set(primes(100000)) n=int(raw_input()) arr=[] dep=[] for i i...
Gandalf the Grey is in trouble as Saurons eye Rearrived in the middle world. Now he has to prepare for the war, But in order to defeat Sauron he has to know the power of saurons eye on the day in which he wants to attack. According to the Elves(Good Friends of Gandalf),Gandalf came to know that ...
import sys M = 10 ** 9 + 7 MAX_T = 10000 MAX_N = 10**12 _CUTOFF = 1536 cache = {} results = [] def do_calc(n): if n in cache: return cache[n] the_matrix = [3, 1, -1, 0] result = power(the_matrix, n)[1] if n not in cache: cache[n] = result return result def power(matrix, n): result = [1, 0, 0, ...
Sherlock and Watson are playing swapping game. Watson gives to Sherlock a string S on which he has performed K swaps. You need to help Sherlock in finding the original string. One swap on a string is performed in this way: Assuming 1 indexing, the i'th letter from the end is inserted between i'th and (i+1)'th l...
k = int(raw_input()) s = raw_input() l = len(s) def swap(s): j = l - 1 while j: if not j % 2 == 0: e = s[j] s = s[:j] + s[j + 1:] + e j -= 1 return s c = s count = 0 itr = "" while itr != s: itr = swap(c) c = itr count += 1 count = k % count for i in range(count): s = swap(s) print s
You are on a game show "Who Wants to Be a Millionaire".The host presents you "N" number of closed doors.There is huge prize behind one door while there are sumo wrestlers behind rest of the doors.Initially you are asked to choose a door.After that the host opens (N-2) doors,revealing sumo wrestlers.The host is omniscie...
for i in range(int(raw_input())): n=int(raw_input()) print ( '%.6f' %(float(n-1)/n))
1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows: * the dogs numbered 1,2,\cdots,26 were respectively given the names `a`, `b`, ..., `z`; * the dogs numbered 27,28,29,\...
n = int(input()) s = '' while n > 0: n -= 1 s = chr(ord('a') + n % 26) + s n //= 26 print(s)
We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}. The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet. Determine whether we will have a bi...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String... args) { Scanner scan = new Scanner(System.in); int[] a = new int[9]; for (int i = 0; i < 9; i++) { a[i] = scan.nextInt(); } int n = scan.nextInt(); List<Integer> b = new Ar...
There are 2N points generally positioned on the circumference of a circle, numbered 1,\dots,2N in counterclockwise order. Here, a set of points is said to be generally positioned if, for any six distinct points U, V, W, X, Y, and Z among them, the segments UV, WX, and YZ do not intersect at the same point. Additionally...
/* `-:://:::- `//:-------:/:` ...
You have decided to write a book introducing good restaurants. There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i. No two restaurants have the same score. You want to in...
n = int(input()) SP = [] for i in range(n): s,p = input().split() SP.append((s,-int(p),i+1)) SP.sort() for s,p,i in SP: print(i)
Taro and Jiro will play the following game against each other. Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a becomes empty, the two players perform the following operation alternately, starting from Taro: * Remove the element at the beginning or the end of a. The player earns x points, whe...
N=int(raw_input()) A=[int(x) for x in raw_input().split()] B=[[0 for x in range(N+1)] for y in range(N)] for i in range(N): B[i][i+1]=A[i] for l in range(1,N): for i in range( N-l): B[i][i+l+1]=max(A[i]-B[i+1][i+l+1], A[i+l] - B[i][i+l] ) print B[0][N] #for ll in B: # print ll
There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N. On this sequence, Snuke can perform the following operation: * Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements....
import math n, k = map(int, input().split()) print(math.ceil((n-k) / (k - 1) + 1))
How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December? Constraints * 1≤M≤23 * M is an integer. Input Input is given from Standard Input in the following format: M Output If we have x hours until New Year at M o'clock on 30th, December, print x. Examples Input 21 Output...
l = int(raw_input()) print 48 - l
The word `internationalization` is sometimes abbreviated to `i18n`. This comes from the fact that there are 18 letters between the first `i` and the last `n`. You are given a string s of length at least 3 consisting of lowercase English letters. Abbreviate s in the same way. Constraints * 3 ≤ |s| ≤ 100 (|s| denotes ...
import java.util.*; class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); System.out.println(str.charAt(0)+""+(str.length()-2)+str.charAt(str.length()-1)); } }
You are developing a robot that processes strings. When the robot is given a string t consisting of lowercase English letters, it processes the string by following the procedure below: 1. Let i be the smallest index such that t_i = t_{i + 1}. If such an index does not exist, terminate the procedure. 2. If t_i is `z`, ...
#include <bits/stdc++.h> #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i<int(b);++i) #define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__) #define _rrep(i,n) _rrange(i,n,0) #define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i) #define r...
AtCoDeer the deer recently bought three paint cans. The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c. Here, the color of each paint can is represented by an integer between 1 and 100, inclusive. Since he is forgetful, he migh...
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int result = 0; int a = sc.nextInt(),b = sc.nextInt(),c = sc.nextInt(); if(a != b) result++; if(a != c) result++; if(b != c) result++; if(a == b && b == c) result++; System.out....
Let p (i) be the i-th prime number from the smallest. For example, 7 is the fourth prime number from the smallest, 2, 3, 5, 7, so p (4) = 7. Given n, the sum of p (i) from i = 1 to n s s = p (1) + p (2) + .... + p (n) Create a program that outputs. For example, when n = 9, s = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 ...
num = 200000 L = [True] * (num+1) L[0] = False L[1] = False for i in range( 2, int(num**0.5)+ 2 ): if not L[i]: continue for j in range(i*2, num+1, i): L[j] = False p = [ x for x in range(num+1) if L[x] ] while True: n = int(input()) if n == 0: break print(sum(p[0:n]))
Consider a tic-tac-toe on a 3x3 board. Tic-tac-toe is a two-player battle game. Decide the first attack and the second attack, one hits Kuroishi and one hits Shiraishi. The winner is the person who puts stones one by one on the board alternately and arranges three of his own stones first in either the vertical, horizon...
#include <iostream> #include <string> using namespace std; int main(){ char d[9]; string m[8]={"012","345","678","036","147","258","048","246"}; int f; while(cin>>d[0],d[0]!='0'){ for(int i=1;i<=8;i++)cin>>d[i]; f=1; for(int i=0;i<8;i++){ if(d[m[i][0]-'0']==d[m[i][1]-'0']&&d[m[i][1]-'0']==d[m[i][2]-'0']&&...
You found an old board game in your programming department's room. It looks interesting so I decided to play with it. This game consists of M events and you must capture event i at time ti. However, at that time your strength must be si or better, and if you can't be si or better, the game is over. Your strength is 0 ...
#include <bits/stdc++.h> using namespace std; #define INF 0x7fffffffffff typedef long long int LLI; int N; int M; LLI ts[1145]; LLI ss[1145]; LLI vs[3145]; LLI hs[3145]; LLI dp[1145][3145]; int main() { scanf("%d%d", &N, &M); for (int i=1; i<=N; i++) { scanf("%lld%lld", &vs[i], &hs[i]); } for (int i=1;...
Bubble Sort Bubble sort is one of the algorithms for sorting columns. Suppose you want to sort the sequence A of length N in ascending order. Bubble sort exchanges the positions of two adjacent numbers if the magnitude relationship is broken. This is done while scanning the sequence from the front. That is, if there i...
#include <bits/stdc++.h> #define int long long #define mp make_pair #define INF 2e+9 using namespace std; typedef pair<int,int> P; typedef pair<int,P> PP; int siz,segMax[300000],segAdd[300000],bit[300010]; void b_add(int i,int x){ while(i <= siz){ bit[i] += x; i += i & -i; } } int sum(int i){ int s = 0; whi...
Ordinary Jigsaw puzzles are solved with visual hints; players solve a puzzle with the picture which the puzzle shows on finish, and the diverse patterns of pieces. Such Jigsaw puzzles may be suitable for human players, because they require abilities of pattern recognition and imagination. On the other hand, "Jigsaw pu...
#include <iostream> #include <fstream> #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <iomanip> #include <map> #include <numeric> #include <queue> #include ...
There are several colored cubes. All of them are of the same size but they may be colored differently. Each face of these cubes has a single color. Colors of distinct faces of a cube may or may not be the same. Two cubes are said to be identically colored if some suitable rotations of one of the cubes give identical l...
#include <bits/stdc++.h> #include <unordered_map> using namespace std; using VS = vector<string>; using LL = long long; using VI = vector<int>; using VVI = vector<VI>; using PII = pair<int, int>; using PLL = pair<LL, LL>; using VL = vector<LL>; using VVL = vector<VL>; #define ALL(a) begin((a)),end(...
Emergency Evacuation The Japanese government plans to increase the number of inbound tourists to forty million in the year 2020, and sixty million in 2030. Not only increasing touristic appeal but also developing tourism infrastructure further is indispensable to accomplish such numbers. One possible enhancement on t...
#include <bits/stdc++.h> using namespace std; #define pb push_back #define mp make_pair #define rep(i,n) for(int i=0;i<n;i++) #define repn(i,n) for(int i=1;i<=n;i++) #define fi first #define sc second vector<int>vec; int n,m,x; int main(){ cin >> n >> m >> x; rep(i,x){ int a,b; cin >> a >> b; a = n+1-a; if(b <=...
Almost Identical Programs The programming contest named Concours de Programmation Comtemporaine Interuniversitaire (CPCI) has a judging system similar to that of ICPC; contestants have to submit correct outputs for two different inputs to be accepted as a correct solution. Each of the submissions should include the pr...
#include <stdio.h> #include <iostream> #include <vector> #include <string> using namespace std; string s; string tt; int ans; int ff,fff; int main(){ cin >> s; while(s!="."){ ans=0; ff=0; fff=0; int i=0; int j=0; cin >> tt; for(;i<int(s.size())&&j<int(tt.size());){ if(s[i]==tt[j]...