input
stringlengths
29
13k
output
stringlengths
9
73.4k
A student, Kita_masa, is taking an English examination. In this examination, he has to write a sentence of length m. Since he completely forgot the English grammar, he decided to consider all sentences of length m constructed by concatenating the words he knows and write the K-th sentence among the candidates sorted i...
import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; class Main { public static void main(String[] args) throws IOException { new Main().run(); } long INF = (long) (1e19); void run() { Scanner s...
One Problem Statement A beautiful mountain range can be seen from the train window. The window is a rectangle with the coordinates of the lower left corner (0, 0) and the coordinates of the upper right corner (W, H). N peaks can be seen from the window, and the i-th peak has the shape of an upwardly convex parabola y...
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import static java.lang.Math.*; import static java.util.Arrays.*; import static java.util.Collections.*; public class Main{ Scanner sc=new Scanner(System.in); int INF=1<<28; int w, h, n; double[] as, ps, qs; void run(){ w=sc.nextI...
Problem statement You are a hero. The world in which the hero is traveling consists of N cities and M roads connecting different cities. Road i connects town a_i and town b_i and can move in both directions. The purpose of the brave is to start from town S and move to town T. S and T are different cities. The hero ca...
#include<bits/stdc++.h> #define r(i,n) for(int i=0;i<n;i++) using namespace std; typedef pair<int,int>P; typedef pair<P,P>P2; int dp[111][111][1<<5]; int n,m,e,s,t,r; vector<P>v[100000]; signed main(){ r(i,111)r(j,1<<5)r(k,111)dp[i][k][j]=1e9; cin>>n>>m>>e>>s>>t>>r; r(i,m){ int a,b; cin>>a>>b; v[a...
G: Minimum Enclosing Rectangle-Minimum Enclosing Rectangle- story Hello everyone! It's Airi Aiza from the Hachimori Naka Prokon Club. Suddenly, I want everyone to solve the problem that Airi couldn't solve before. I solved the A problem of ICPC2010 in this front activity, but the problem at that time was difficult. ...
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <string> #include <algorithm> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <cassert> typedef long long ll; using namespace std; #define debug(x) c...
problem Given a sequence $ A $ of length $ N $. You can swap the $ i $ th and $ j $ th ($ 0 \ leq i, j \ leq N-1 $) elements of a sequence up to $ M $ times. Find the maximum value of $ \ sum_ {i = 0} ^ {N -1} abs (A_i --i) $ in the sequence created by the operation. output Find the maximum value of $ \ sum_ {i =...
#include<iomanip> #include<limits> #include<thread> #include<utility> #include<iostream> #include<string> #include<algorithm> #include<set> #include<map> #include<vector> #include<stack> #include<queue> #include<cmath> #include<numeric> #include<cassert> #include<random> #include<chrono> #include<unordered_set> #includ...
D: Many Decimal Integers problem Given a string S consisting only of numbers (0-9) and a string T consisting only of numbers and `?`. S and T are the same length. Consider changing each `?` That exists in T to one of the numbers from 0 to 9 to create the string T'consisting of only numbers. At this time, it must be ...
#include <bits/stdc++.h> using namespace std; const int MOD=1e9+7; //const int MOD=998244353; const int INF=1e9; const long long LINF=1e18; #define int long long //template template <typename T> void fin(T a){ cout<<a<<endl; exit(0); } int pw(int n,int k){ if(k<0)return pw(n,k+MOD-1); int res=1; while(k){ ...
Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s. Constraints * 1 ≤ H, W ≤ 1,400 Input H W c1,1 c1,2 ... c1,W c2,1 c2,2 ... c2,W : cH,1 cH,2 ... cH,W In the first line, two integers H and W separated by a space character are given. In the following...
#include<bits/stdc++.h> const static int MAX = 1400; int H, W; int buffer[MAX][MAX]; int T[MAX][MAX]; struct Rectangle{ int height; int pos; }; int getLargestRectangle(int size, int buffer[]){ std::stack<Rectangle> S; int maxv = 0; buffer[size] = 0; for(int i = 0; i <= size; i++){ Re...
Addition of Big Integers Given two integers $A$ and $B$, compute the sum, $A + B$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the sum in a line. Constraints * $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$ Sample Input 1 5 8 Sample Output 1 13 S...
#include<stdio.h> #include<cmath> #include<string.h> #include<algorithm> #include<vector> #include<iostream> using namespace std; #define MAX 3000000 #define MAXN 9999 #define MAXSIZE (100005/2) #define DLEN 4 class BigNum{ public: int a[100005/2]; int len; BigNum(){len=1,memset(a,0,sizeof(a));} BigN...
The much anticipated video game "BiCo Grid" has been released. The rules of "Bico Grid" are very simple. The game field is a 100x100 matrix, where each cell is either a blocked cell, or a cell with some number of coins. For a regular player the look of the field seems pretty random, but the programmer in you recognizes...
C = [[0 for x in xrange(100)] for x in xrange(100)] def dp(): for i in range(100): for j in range(min(99, i)): if j == 0 or j == i: C[i][j] = 1 else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; def work(r, c, g): maxUsed = -1 ans = [] x = r ...
In the country of Numberia, there is a city called Primeland. Sherry is one of the rich inhabitants of the city, who likes to collect coins of various denominations. Coins in primeland are little strange , they are only available in prime denominations (i.e as coins of value 2,3,5 etc.).Sherry is taking a tour of the c...
t=int(raw_input()) for i in range (t): c,d=map(int,raw_input().split()) print (c*d-c-d)
Forgotten languages (also known as extinct languages) are languages that are no longer in use. Such languages were, probably, widely used before and no one could have ever imagined that they will become extinct at some point. Unfortunately, that is what happened to them. On the happy side of things, a language may be d...
for i in range(input()): NK = map(int, raw_input().split()) strings = map(str, raw_input().split()) phrases = [] for j in range(NK[1]): phrases.append(map(str, raw_input().split())) for j in strings: out = "NO" for k in phrases: if j in k: out = "...
The Head Chef is studying the motivation and satisfaction level of his chefs . The motivation and satisfaction of a Chef can be represented as an integer . The Head Chef wants to know the N th smallest sum of one satisfaction value and one motivation value for various values of N . The satisfaction and motivation v...
def solve(a,b,num): # temp=[w for w in c] # heapify(temp) # for i in xrange(num): # ans=heappop(temp) # heapify(temp) # return ans while(len(a)*len(b)>num): if len(a)==1 or len(b)==1: break if a[-1]>b[-1]: a.pop() else: b.pop() p=[] for i in xrange(len(a)): for j in xrange(len(b)): p.app...
Shridhar wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers. Input The first line contains t, the number of test cases (less then or equal to 10). Followed by t lines which contain two numbers m and n (1 ≤ m ≤ n ≤ 1000000000, n-...
import sys import math def prime_gen(n1,n2): primes = [] notprimes=[0]*(n2-n1+1) l=int(math.sqrt(n2)) for i in xrange(2,l+1): j=n1//i while j*i<=n2: if j > 1 and j*i >= n1 : notprimes[j*i-n1] = 1 j=j+1 for i in xrange(n1,n2+1): if notpr...
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish. For the given positive integer N, your ta...
from sys import stdin from math import ceil MOD=1000000007 inv25=pow(25,MOD-2,MOD) t=int(stdin.readline()) for i in range(0,t): n=int(stdin.readline()) k=(n+1)/2 p26=pow(26,k,MOD) ans = 52 * (p26-1) % MOD * inv25%MOD if n&1: ans = (ans + MOD - p26)%MOD print ans
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages. There are n stages available. The rock...
n,k = list(map(int,input().split())) data = sorted(list(input())) data = list(map(lambda x:ord(x)-ord('a')+1,data)) result = 0 used = 0 idx =0 prev = -2 # print(data) for d in data: if d > prev+1: result+= d prev = d used += 1 if used == k: break if used < k: print(-...
Mikhail walks on a Cartesian plane. He starts at the point (0, 0), and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point (0, 0), he can go to any of the following points in one move: * (1, 0); * (1, 1); * (0, 1); * (-1, 1); * (-1, 0); * (-1, -1);...
#include <bits/stdc++.h> using namespace std; int main() { int q; long long int n, m, k, i, bar, left, diag; scanf("%d", &q); while (q--) { scanf("%lld %lld %lld", &n, &m, &k); if (n < m) { i = n; n = m; m = i; } if (n > k) { printf("-1\n"); continue; } else { ...
Vasya has recently got a job as a cashier at a local store. His day at work is L minutes long. Vasya has already memorized n regular customers, the i-th of which comes after t_{i} minutes after the beginning of the day, and his service consumes l_{i} minutes. It is guaranteed that no customer will arrive while Vasya is...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.io.IOException; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import j...
Recently, Masha was presented with a chessboard with a height of n and a width of m. The rows on the chessboard are numbered from 1 to n from bottom to top. The columns are numbered from 1 to m from left to right. Therefore, each cell can be specified with the coordinates (x,y), where x is the column number, and y is ...
#include <bits/stdc++.h> using namespace std; long long calc(long long x1, long long y1, long long x2, long long y2) { if ((x2 - x1 + 1) * (y2 - y1 + 1) % 2 == 0) return 1; return 2; } int main() { long long t; cin >> t; while (t--) { long long n, m; cin >> n >> m; long long x1, y1, x2, y2; ci...
All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the respon...
#include <bits/stdc++.h> using namespace std; int n, k; int a[100][100]; int xc, yc; int lolol(int x, int y) { return abs(x - xc) + abs(y - yc); } int main() { cin >> n >> k; xc = (k + 1) / 2; yc = (k + 1) / 2; for (int asdasd = 0; asdasd < n; asdasd++) { int m; cin >> m; int ans = 999999999; in...
Everybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates. There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. ...
n,m,k=map(int,input().split()) p=list(map(int,input().split())) s=list(map(int,input().split())) c=set(map(int,input().split())) d={} for i in range(n): if s[i] not in d: d[s[i]]=[-1] if p[i]>d[s[i]][0]: d[s[i]]=(p[i],i) st=set() for i in d: st.add(d[i][1]+1) #print(c,st) c=c.difference(st) ...
You are given a permutation p of integers from 1 to n, where n is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: * take two indices i and j such that 2 ⋅ |i - j| ≥ n and swap p_i and p_j. There is no need to minimize the number of...
#include <bits/stdc++.h> using namespace std; const long long maxn = (long long)3e5 + 7; long long a[maxn]; long long b[maxn]; long long pos[maxn]; struct node { long long x, y; } ans[maxn * 5]; signed main() { ios::sync_with_stdio(false); long long n; cin >> n; for (long long i = 1; i <= n; i++) cin >> a[i];...
Toad Pimple has an array of integers a_1, a_2, …, a_n. We say that y is reachable from x if x<y and there exists an integer array p such that x = p_1 < p_2 < … < p_k=y, and a_{p_i} \& a_{p_{i+1}} > 0 for all integers i such that 1 ≤ i < k. Here \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bi...
#include <bits/stdc++.h> struct node { int next[19] = {}; }; int n, q; int a[300005]; node nodes[300005]; bool isReachable(int curr, int end) { for (int i = 0; i < 19; i++) { if ((a[end] & (1 << i)) && nodes[curr].next[i] && nodes[curr].next[i] <= end) { return true; } } return false; } in...
The leader of some very secretive organization has decided to invite all other members to a meeting. All members of the organization live in the same town which can be represented as n crossroads connected by m two-directional streets. The meeting will be held in the leader's house near the crossroad 1. There are k mem...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int maxm = 5e3 + 10; const int inf = 0x3f3f3f3f; namespace io { const int SIZE = (1 << 21) + 1; char ibuf[SIZE], *iS, *iT, obuf[SIZE], *oS = obuf, *oT = oS + SIZE - 1, c, qu[55]; int f, qr; inline void fl...
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied: For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from ...
#include <bits/stdc++.h> using namespace std; const int N = 1010; struct Edge { int to, next; } e[N * 2]; int lst[N], d; void add(int x, int y) { e[d].to = y, e[d].next = lst[x], lst[x] = d++; } int fa[N], n, sz[N]; int read() { int w = 0, f = 0; char c = getchar(); while ((c < '0' || c > '9') && c != '-') c = ...
The only difference between easy and hard versions is constraints. The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ k), where a_i is the show, the episode of which will be shown in i-th day. The...
x = int(input()) for i in range(x): n, k, d = map(int, input().split(' ')) l = map(int, input().split(' ')) l = list(l) ar = [] for j in range(n-d+1): ar.append(len(set(l[j:(j+d)]))) print(min(ar))
The only difference between easy and hard versions is constraints. You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i. The integer point is called bad...
import java.util.*; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; public class r558p4{ private static InputReader sc; private static PrintWriter pw; static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]...
Lucy likes letters. She studied the definition of the lexicographical order at school and plays with it. At first, she tried to construct the lexicographically smallest word out of given letters. It was so easy! Then she tried to build multiple words and minimize one of them. This was much harder! Formally, Lucy want...
#include <bits/stdc++.h> char S[1000002]; char D[1000002]; char R[1002][1002]; void mS(char s[], char d[], int o, int t) { int i, j, k; int c = o + t >> 1; if (o < c) { mS(d, s, o, c); } if (c + 1 < t) { mS(d, s, c + 1, t); } i = o; j = c + 1; k = o; while (i <= c && j <= t) { if (s[i] <...
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h...
t = int(input()) for _ in range(t): ans = 0 n, pos, control = map(int, input().split()) control = min(control, pos - 1) not_control = pos - control - 1 num = n - control - not_control a = list(map(int, input().split())) for i in range(control + 1): tmp = 10 ** 10 + 1 for j in...
The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. 2^n teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from 1 to 2^n and will play games one-on-o...
#include <bits/stdc++.h> inline long long read() { long long x = 0, f = 1; char c = getchar(); for (; c > '9' || c < '0'; c = getchar()) { if (c == '-') f = -1; } for (; c >= '0' && c <= '9'; c = getchar()) { x = x * 10 + c - '0'; } return x * f; } int dp[18][(1 << 18)][2][2]; bool fan[200005]; in...
Given a sequence of integers a of length n, a tuple (i,j,k) is called monotone triples if * 1 ≤ i<j<k≤ n; * a_i ≤ a_j ≤ a_k or a_i ≥ a_j ≥ a_k is satisfied. For example, a=[5,3,4,5], then (2,3,4) is monotone triples for sequence a while (1,3,4) is not. Bob is given a sequence of integers a of length n in a ...
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5; int a[maxn + 11], lmin[maxn + 11], lmax[maxn + 11], rmin[maxn + 11], rmax[maxn + 11]; int ans3[maxn + 11][5], ans4[maxn + 11][5]; set<int>::iterator it; vector<int> v[maxn + 11]; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);...
You are given a board of size n × n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
I = input for _ in range(int(I())): n = int(I())+1 s = 0 for i in range(1,n//2): s += 8*i*i print(s)
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
from sys import stdin,stdout t=int(stdin.readline().strip()) for _ in range(t): s=stdin.readline().strip() stdout.write(("NET","DA")[min(s.count('0'),s.count('1')) % 2]+"\n")
You are given an array a of n integers. You want to make all elements of a equal to zero by doing the following operation exactly three times: * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can...
//package codeforces.D666; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.StringTokenizer; /** * @author muhossain * @since 2020-08-1...
In the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai — how many people who are taller than him/her and stand in queue in front of him. After a while the cashier has a lunch break and t...
import java.io.*; import java.util.*; public class Ochered implements Runnable { public static void main(String[] args) { new Thread(new Ochered()).run(); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer in; PrintWriter...
Artem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells c...
// package T800; import java.io.PrintWriter; import java.util.HashSet; import java.util.Scanner; public class GERGOVIA { public static PrintWriter out = new PrintWriter(System.out); public static Scanner in = new Scanner(System.in); public static void main(String[] args) { int n = ni(); while (n-- > 0...
You are given an array [a_1, a_2, ..., a_n] such that 1 ≤ a_i ≤ 10^9. Let S be the sum of all elements of the array a. Let's call an array b of n integers beautiful if: * 1 ≤ b_i ≤ 10^9 for each i from 1 to n; * for every pair of adjacent integers from the array (b_i, b_{i + 1}), either b_i divides b_{i + 1}, or...
for _ in range(int(input())): n = map(int, input().split()) a = list(map(int, input().split())) c = 1 i = 0 while c <= 1000000000: d = 2 * c if c <= a[i] <= d: print(c, end=" ") i += 1 d = 1 if i == len(a): break c = d ...
The princess is going to escape the dragon's cave, and she needs to plan it carefully. The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess ...
i=input p,d,t,f,c=i(),i(),i(),i(),i() r=0 T=t x=t*p*1./(d-p) if d > p else c / p c -= t*p while True: c -= x*p T+=x if c > 0: r += 1 else: break x=(2*T*p + f*d)*1./(d - p) print r
A chainword is a special type of crossword. As most of the crosswords do, it has cells that you put the letters in and some sort of hints to what these letters should be. The letter cells in a chainword are put in a single row. We will consider chainwords of length m in this task. A hint to a chainword is a sequence ...
#include <cstdlib> #include <iostream> #include <cstdio> #include <math.h> #include <cstring> #include <time.h> #include <complex> #include <algorithm> #include <queue> #include <stack> #include <unordered_map> #include <set> #include <bitset> #pragma warning(disable:4996) #define PII std::pair<long long, long long> #...
Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store — "PriceFixed". Here are some rules of that store: * The store has an infinite number of items of every product. * All products have the same price: 2 rubles per item. * ...
#include<bits/stdc++.h> using namespace std; #define int long long //delete if causing problems #define F first #define S second #define setbit(n) __builtin_popcountll(n) #define all(x) x.begin() , x.end() #define clr(x) memset(x,0,sizeof(x)) #define fast ios_base::sync_with_stdio(0); cin.tie(0); #define endl "\n" //d...
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two give...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.StringTokenizer; public class Main { public static void main(String args[]) throws Exception{ Sca...
PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features. AlgoRace is a special league of car r...
import java.io.* ; import java.util.*; import static java.lang.Math.* ; import static java.util.Arrays.* ; public class B { public static void main(String[] args) throws IOException { new B().solveProblem(); out.close(); } static Scanner in = new Scanner(new InputStreamReader(System.in)); //static Bu...
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem: You've got some training set of documents. For each document you know its su...
#include <bits/stdc++.h> int main() { int n; scanf("%d", &n); n -= 43500; puts(n > 0 ? (n > 2000 ? "3" : "2") : "1"); return 0; }
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been pa...
#include <bits/stdc++.h> using namespace std; int a[105][105]; int main() { int k; cin >> k; memset(a, 0, sizeof(a)); for (int i = 1; i <= 3; i++) for (int j = 1; j <= 3; j++) if (i != j) a[i][j] = 1; k--; int ans = 3; if (k) { for (ans = ans + 1; ans <= 100; ans++) { for (int i = 1; i...
Little Elephant loves magic squares very much. A magic square is a 3 × 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15...
l=lambda:map(int,raw_input().split()) m=[l() for _ in range(3)] a,b,c=0,0,0 # a+c=m[0][2]+m[2][0] # a-c=m[2][0]+m[2][1]-(m[0][1]+m[0][2]) a=m[2][0]+(m[2][1]-m[0][1])/2 c= m[0][2]+(m[0][1]-m[2][1])/2 b=a+m[0][1]+m[0][2]-(m[1][0]+m[1][2]) print a,m[0][1],m[0][2] print m[1][0],b,m[1][2] print m[2][0],m[2][1],c
The Bitlandians are quite weird people. They have very peculiar customs. As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work. The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. h...
#include <bits/stdc++.h> using namespace std; pair<long long, long long> dp[3][1000005]; int A[1000005], B[1000005]; int ma[3][1000005]; int main() { int n, x; pair<int, int> e1; pair<int, int> e2; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d%d", &A[i], &B[i]); dp[0][0] = make_pair(A[0], 0); dp[...
Unfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4. Vasya has a set of k distinct non-negative integers d1, d2, ..., dk. Vasya wants to choose some integers ...
#include <bits/stdc++.h> using namespace std; int n, arr[100], i, j; bool a[100][100]; bool Ok(int x, int y) { while (x && y) { int a = x % 10; int b = y % 10; x /= 10; y /= 10; if (a && b) return false; } return true; } int main() { cin >> n; vector<vector<int> > v; for (int i = 0; i < ...
— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? — Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcomin...
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; import java.text.*; public class Rough{ static PrintWriter w=new PrintWriter(System.out); public static void main(String [] args){ DecimalFormat dm=new DecimalFormat("0.000000"); Scanner sc=new Scanner(System.in);...
Jeff loves regular bracket sequences. Today Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of nm brackets. Let's number all brackets of this sequence from 0 to nm - 1 from left to right. Jeff knows that he is going to spend ai mod n liters of ink on the i-th bracket of th...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; int n, m, a[N], b[N]; int dp[22][44]; struct uzi { long long A[44][44]; uzi() { memset(A, 0x3f3f3f, sizeof A); }; } G; uzi operator*(const uzi& a, const uzi& b) { uzi c; for (int i = 0; i <= 40; i++) { for (int j = 0; j <= 40; j++) { ...
Pavel loves grid mazes. A grid maze is an n × m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any oth...
#include <bits/stdc++.h> using namespace std; const int M = 505; struct Node { int x, y; }; int cnt = 0, sum = 0; int k, n, m; bool book[M][M]; char mapp[M][M]; int mv[4][2] = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}}; void bfs(int x, int y) { queue<Node> q; int xt, yt; Node tmp, next; tmp.x = x; tmp.y = y; book...
User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. 1. At first, the score is 0. 2. For each block of contiguous "o"s with length x the score increases by x2. 3. F...
#include <bits/stdc++.h> using namespace std; long long n, m, x, y, s, t, res, ans = -1LL << 60; long long get(long long t) { x = m / t; y = m % t; return (t - y) * x * x + y * (x + 1) * (x + 1); } int main() { cin >> n >> m; if (!n) { cout << -m * m << endl; for (int i = 0; i < m; i++) cout << "x"; ...
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!' The head of the company d...
#include <bits/stdc++.h> using namespace std; const long long N = 2e5; void solve() { long long n, p; cin >> n >> p; vector<vector<long long> > g(n); vector<pair<long long, long long> > e(n); map<pair<long long, long long>, long long> cnt; for (long long i = 0; i < n; ++i) { long long a, b; cin >> a...
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team. At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix...
s = input() t = input() ind = 0 for x in t: ind = s.find(x, ind) + 1 if ind <= 0: break if ind > 0 or len(t) == 0: print('automaton') else: ss = list(s) tt = list(t) bb1 = True if len(ss) >= len(tt): for x in tt: bb = False for y in ss: ...
Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together...
#include <bits/stdc++.h> using namespace std; int main() { int n; string t, s; cin >> n >> s; t = s; sort(s.begin(), s.end()); int ret = (1 << 21); for (int i = 0; i < s.length() + 1; i++) { int dif = 0; for (int i = 0; i < s.length(); i++) { if (t[i] != s[i]) dif++; } ret = min(ret,...
Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to...
import java.io.*; import java.util.*; public class D { static long mod = (long)1e9+7; public static void main(String[] args) { FastScanner sc=new FastScanner(); int n = sc.nextInt(); int x = sc.nextInt(); int y = sc.nextInt(); List<String> ans = new ArrayList<>(); int ar[] = sc.readArray(n); int countx...
Drazil is a monkey. He lives in a circular park. There are n trees around the park. The distance between the i-th tree and (i + 1)-st trees is di, the distance between the n-th tree and the first tree is dn. The height of the i-th tree is hi. Drazil starts each day with the morning run. The morning run consists of the...
#include <bits/stdc++.h> using namespace std; const int INF = numeric_limits<int>::max(); const int MINF = numeric_limits<int>::min(); const int INFF = (INF / 2 - 1); const double EPS = 1e-9; const int dy8[] = {-1, -1, 0, 1, 1, 1, 0, -1}; const int dx8[] = {0, 1, 1, 1, 0, -1, -1, -1}; const int dy4[] = {-1, 0, 1, 0}; c...
You have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i....
#include <bits/stdc++.h> using namespace std; const int N = 22, mod = 1e9 + 7; const long long inf = 1e15; int n, m, a[N][N], faa[N][N], famask[N][N]; string s[N]; long long dp[1 << 20]; inline void smin(long long &a, long long b) { if (a > b) a = b; } int main() { cin >> n >> m; for (int i = 0; i < n; ++i) cin >...
Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has ...
#include <bits/stdc++.h> using namespace std; int tree[4 * 200005], cs[200005], ar[200005]; struct dt { int b, e, h, id, res; } st[100005]; bool cmp1(dt x, dt y) { return x.b < y.b; } bool cmp2(dt x, dt y) { return x.id < y.id; } void update(int nd, int b, int e, int x, int v) { if (b > x || e < x) return; if (b ...
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practi...
#include <bits/stdc++.h> using namespace std; int arr[505000], ans; void updata(int l, int r) { int i = l + 1, j = r - 1; while (i <= j) { arr[i] = arr[l]; arr[j] = arr[r]; i++, j--; } ans = max(ans, (r - l) / 2); } int main() { int n; scanf("%d", &n); ans = 0; int st = 0, ed = 0; for (int...
Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it...
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.*; /*2A*/ public class Main { public static void main(String[] args) throws Exception { Main mainClass = new Main(); } BufferedReader...
Dante is engaged in a fight with "The Savior". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots. For every bullet that hits the shield, Ebony deals a units of damage while Ivory deals b units of dama...
import java.util.*; import java.io.*; import java.math.*; public final class Solution { public static void main(String[] args) { Reader input = new Reader(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int a = input.nextInt(), b = input.nextInt(), total = in...
Snow Queen told Kay to form a word "eternity" using pieces of ice. Kay is eager to deal with the task, because he will then become free, and Snow Queen will give him all the world and a pair of skates. Behind the palace of the Snow Queen there is an infinite field consisting of cells. There are n pieces of ice spread ...
#include <bits/stdc++.h> using namespace std; typedef struct POINT { int x, y, v; POINT(int x = 0, int y = 0, int v = 0) : x(x), y(y), v(v) {} bool operator<(POINT& other) { if (this->x != other.x) return this->x < other.x; if (this->y != other.y) return this->y < other.y; if (this->v != other.v) retu...
Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed <image>. You are given a tree of size n and can perform no more than one edge ...
#include <bits/stdc++.h> inline long long read() { long long x = 0; char ch = getchar(), w = 1; while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return x * w; } void write(long long x) { if (...
This is an interactive problem. In the interaction section below you will find the information about flushing the output. The New Year tree of height h is a perfect binary tree with vertices numbered 1 through 2h - 1 in some order. In this problem we assume that h is at least 2. The drawing below shows one example New...
#include <bits/stdc++.h> using namespace std; mt19937 gen(1); map<int, vector<int>> memo; vector<int> ask(int x) { if (memo.count(x)) { return memo[x]; } cout << "? " << x << endl; int cnt; cin >> cnt; vector<int> edges(cnt); for (auto& el : edges) { cin >> el; } return memo[x] = edges; } int ...
Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an. While Vasya was walking, his little brother Stepan played with Vasya's cubes and chan...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ; long long n, l, r; cin >> n >> l >> r; std::vector<long long> v(n); std::vector<long long> v1(n); long long f = 1; for (long long i = 0; i < n; +...
In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Ar...
#include <bits/stdc++.h> using namespace std; template <typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; } template <typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; } template <typename T> inline bool smin(T &a, const T &b) { return a > b ? a = b : a;...
After studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly T seconds. The problem is that the star is yet to be discovered by scientists. There are n astronomers numerated fr...
#include <bits/stdc++.h> using namespace std; const int size = 200 * 1000 + 100; int ans[size]; int a[size]; int mycur[size]; int t, n; int d; int shift[size]; int ord[size]; int nod(int a, int b) { if (b == 0) return a; else return nod(b, a % b); } int pwr(int a, int b, int mdl) { if (b == 0) return 1 % ...
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky. The ticket is considered lucky if the sum of first three digits equals to the sum of las...
import java.util.*; public class b { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); int[] arr = new int[6]; for (int i = 0; i < 6; i++) { arr[i] = str.charAt(i) - '0'; } int min = 6; for (int ...
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws IOException { FastScanner in= new Fast...
Sloth is bad, mkay? So we decided to prepare a problem to punish lazy guys. You are given a tree, you should count the number of ways to remove an edge from it and then add an edge to it such that the final graph is a tree and has a perfect matching. Two ways of this operation are considered different if their removed...
#include <bits/stdc++.h> int s[500001], su[500001], ru[500001], ss1[500001], ss2[500001], m, fir[500001], nex[1000001], sto[1000001], fa[500001], a1, b1, tot; long long n, sum, dp[500001][2][2], f[500001][2][2], s1, s2, s3, s4, siz[500001], f1[2][2], ans; bool p[500001][2]; void addbian(int aa, int bb) { tot+...
You are given n positive integers a1, a2, ..., an. For every ai you need to find a positive integer ki such that the decimal notation of 2ki contains the decimal notation of ai as a substring among its last min(100, length(2ki)) digits. Here length(m) is the length of the decimal notation of m. Note that you don't ha...
#include <bits/stdc++.h> using namespace std; int T, n, m; long long x, y, a, b; inline long long ps(long long x, long long y, long long P) { long long z = 0; while (y) { if (y & 1) z = z + x; x <<= 1, y >>= 1; if (x >= P) x -= P; if (z >= P) z -= P; } return z; } inline long long pm(long long x...
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on. During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The s...
import java.io.*; import java.util.*; public class CF936_D1_A{ public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); long k=sc.nextLong(); long d=sc.nextLong(); long t=sc.nextLong(); long total=2*t; if(k>=t) pw.print...
You are given a string s consisting of n lowercase Latin letters. Let's denote k-substring of s as a string subsk = sksk + 1..sn + 1 - k. Obviously, subs1 = s, and there are exactly <image> such substrings. Let's call some string t an odd proper suprefix of a string T iff the following conditions are met: * |T| > ...
#include <bits/stdc++.h> const int P = 233; const int P2 = 131; const int maxn = 1000000 + 3; const int MOD = 1000000007; inline int getint() { bool flag = 0; register int n = 0; register char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') flag = 1; ch = getchar(); } while (ch >= '0' ...
The cool breeze blows gently, the flowing water ripples steadily. "Flowing and passing like this, the water isn't gone ultimately; Waxing and waning like that, the moon doesn't shrink or grow eventually." "Everything is transient in a way and perennial in another." Kanno doesn't seem to make much sense out of Mino's...
#include <bits/stdc++.h> using namespace std; void readi(int &x) { int v = 0, f = 1; char c = getchar(); while (!isdigit(c) && c != '-') c = getchar(); if (c == '-') f = -1; else v = v * 10 + c - '0'; while (isdigit(c = getchar())) v = v * 10 + c - '0'; x = v * f; } void readll(long long &x) { l...
Two strings are said to be anagrams of each other if the letters of one string may be rearranged to make the other string. For example, the words 'elvis' and 'lives' are anagrams. In this problem you’ll be given two strings. Your job is to find if the two strings are anagrams of each other or not. If they are not anag...
from string import ascii_lowercase,ascii_uppercase alp=ascii_lowercase+ascii_uppercase def lpalin(S): l=list(S) one,two=0,0 d=set(l);ch='' for i in d: if l.count(i)%2==0:two+=1 else:one+=1;ch=i if one>1: return '0' else: f='';g=ch sx=list(set(l));sx.sort()...
Phineas is Building a castle in his backyard to impress Isabella ( strange, isn't it? ). He has got everything delivered and ready. Even the ground floor has been finished. Now is time to make the upper part. This is where the things become interesting. As Ferb is sleeping in the house after a long day painting the fen...
T = int(raw_input()) for i in range(0,T): M = int(raw_input()) lst = map(int, raw_input().split()) N= lst.pop(0) """ s = raw_input() lst = s.split() N = int(lst[0]) lst.pop(0) """ lst.sort() j = N - 1 i = 0 res = 0 while ( i <= j): if(int(lst[j]) > M): j -= 1 elif(int(lst[i]) + int(lst[j]) > M...
Roman loved diamonds. Monica decided to give him a beautiful gift on Valentine's Day. Her idea of diamonds was different though. She lit up all the windows of her rectangular building with N floors and M windows on each floor, with 2 shapes - / or \ . According to her, a diamond was made when such a shape was created: ...
p=input() s=range(1000) import string for i in range(p): d=0 n,m= map(int, raw_input().split()) for i in range(n): s[i]=string.split(raw_input()) for i in range(n-1): for j in range(m-1): if s[i][j]=="/" and s[i][j+1]=="\\" : if s[i+1][j]=="\\" and s[i+1][j+1]=="/": d=d+1 print d
One day Alice was experimenting with the numbers to make new algorithms. He introduce a new term Rsum. Rsum of any number is defined as number obtained by iterative summing of digits of the given number until single digit number is obtained. For example: 365 --> (3+6+5) = 14 14 --> 1+4 = 5 Rsum(365)=5 Naughty...
facts = [0, 1, 2, 6, 6, 3] for _ in range(input()): ans = 0 a, b = map(int, raw_input().split()) if a >=6: ans = 9 * (b - a + 1) elif a < 6 and b >=6: ans = 9 * (b - 6 + 1) for i in range(a, 6): ans += facts[i] elif b < 6: for i in range(a, b+1): ...
All the students in NIT are very lazy. They want to have maximum time for rest. But due to college rules, they must maintain 75% attendance at the end of every week. Given the schedule of a week, tell them what is the maximum amount of time they might have for resting. NOTE: Each day has 24 hrs. i.e. 24x60x60 second...
from math import ceil for i in range(int(raw_input())): clas=[] total=0 for k in range(7): arr=map(int,raw_input().strip().split()) total+=arr[0] for j in range(1,arr[0]+1): clas.append(arr[2*j]-arr[2*j-1]) atte=int(ceil(total*3.0/4)) nota=total-atte for k in range(nota): max=0 for j in range(1,t...
Monk visits the land of Islands. There are a total of N islands numbered from 1 to N. Some pairs of islands are connected to each other by Bidirectional bridges running over water. Monk hates to cross these bridges as they require a lot of efforts. He is standing at Island #1 and wants to reach the Island #N. Find th...
'__author__'=='deepak Singh Mehta(learning to code :) ) ' ''' Hard work beats Talent when Talent doesn't work hard. :) ''' int_max = 10000000 if __name__=='__main__': tests = int(raw_input()) for _ in range(tests): n,m = map(int,raw_input().split()) graph =[[] for i in range(n+1)] ...
Given an integer N. Find out the PermutationSum where PermutationSum for integer N is defined as the maximum sum of difference of adjacent elements in all arrangement of numbers from 1 to N. NOTE: Difference between two elements A and B will be considered as abs(A-B) or |A-B| which always be a positive number. Inpu...
''' from itertools import permutations def abs_sum(l): res = 0 for i in range(len(l)-1): res += abs(l[i] - l[i+1]) return res def all_perms(l): a = permutations(l) return map(list, a) for i in range(2, 12): l = range(1, i) ap = all_perms(l) print l, max(map(abs_sum, ap...
Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload. Minimum dimension of the picture can be L x L, where L is the length of the side of square. Now Roy has N photos of various dimensions. Dimension of a photo is denoted as W x H wh...
import sys l= raw_input().strip() l=int(l) n=raw_input().strip() n=int(n) for i in xrange(n): w, h=raw_input().strip().split() w, h=[int(w), int(h)] if w<l or h<l: print 'UPLOAD ANOTHER' elif w==h: print 'ACCEPTED' else: print 'CROP IT'
Yes, you read it right - Little Jhool is back, but no, he's not over his break up, still. And he's sad, broken and depressed; thus, he decided to visit a psychologist. She tells him to think about his pleasant memories of childhood, and stay busy so as to not miss his ex-girlfriend. She asks him about his favorite mem...
for i in range(input()): n = input() ans = 1000000 for i in xrange(113): for j in xrange(113): if (i*10 + j*12 == n): ans = min (ans, i+j) if (ans==1000000): print -1 else: print ans
As it is the Valentines month, Puchi's girlfriend asks him to take her shopping. He, being the average bloke, does not have a lot of money to spend. Hence, decides to buy each item from the shop that offers the best price on it. His girlfriend wants to buy N items. Each item is available on M shops . Being the Valenti...
import sys t = int(raw_input()) for i in range(0,t): products,shops = map(int,raw_input().split()) for prod in range(0,products): bestShop=1; bestPrice=101; for m in range(1,shops+1): basePrice=100.00; for discount in raw_input().split(): if(int(discount)==100): basePrice=0; break; bas...
To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives. He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the n...
n,*a=map(int,open(0).read().split()) m=1000 for i in range(1,n): if a[i]>a[i-1]: m=m//a[i-1]*a[i]+m%a[i-1] print(m)
Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S. For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows: * f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{...
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int S = sc.nextInt(); int A[] = new int[N]; for(int i = 0 ; i < A.length ; ++i){ A[i] = sc.nextInt(); } long MOD = 998244353; ...
We have N points numbered 1 to N arranged in a line in this order. Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows: * The operation uses integers L_i ...
#include <bits/stdc++.h> #define MAX 131072 using namespace std; pair<pair<int, int>, int> edge[MAX]; map<int, long long> val; int main(void) { int N, M; cin >> N >> M; val[1] = 0LL; val[N] = 1LL * 998244353 * 998244353; for (int i = 0; i < M; i++) cin >> edge[i].first.first >> edge[i].first.second >> edge[i].se...
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive). In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content? Here the subsequence of A is a sequence obtained by removing zero or ...
#include <iostream> #include <vector> #include <algorithm> using namespace std; const int MOD = 1000 * 1000 * 1000 + 7; int main() { int N, M; cin >> N >> M; vector<int> S(N), T(M); for (auto &x : S) cin >> x; for (auto &x : T) cin >> x; vector<vector<long long>> dp(N + 1, vector<long long>(M + 1, 0)); for...
There is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Also, each of these vertices and edges has a specified weight. Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i. We would like to remove zero o...
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <vector> using namespace std; const int N=100010; bool w[N]; int fa[N],pa[N]; vector <int> q[N]; long long a[N],b[N]; inline int gi() { int x=0,o=1; char ch=getchar(); while(ch<'0'||ch>'9') ch=='-'?o=-1:...
There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies. You will take out the candies from some consecutive boxes and distribute them evenly to M children. Such being the case, find the number of the pairs (l, r) that satisfy the following: * l and r are both integers...
#include <iostream> #include <map> using namespace std; int main() { uint64_t n, m; cin >> n >> m; map<uint64_t, uint64_t> mp; mp[0] = 1; uint64_t accumulate = 0; uint64_t ans = 0; for (auto i = 0; i < n; i++) { uint64_t v; cin >> v; accumulate += v; ans += mp[accumulate % m]++; } co...
There is a bridge that connects the left and right banks of a river. There are 2 N doors placed at different positions on this bridge, painted in some colors. The colors of the doors are represented by integers from 1 through N. For each k (1 \leq k \leq N), there are exactly two doors painted in Color k. Snuke decide...
#include <bits/stdc++.h> using namespace std; using ll=int64_t; #define int ll #define FOR(i,a,b) for(int i=int(a);i<int(b);i++) #define REP(i,b) FOR(i,0,b) #define MP make_pair #define PB push_back #define ALL(x) x.begin(),x.end() #define REACH cerr<<"reached line "<<__LINE__<<endl #define DMP(x) cerr<<"line "<<__LI...
We have a tree with N vertices. Vertex 1 is the root of the tree, and the parent of Vertex i (2 \leq i \leq N) is Vertex P_i. To each vertex in the tree, Snuke will allocate a color, either black or white, and a non-negative integer weight. Snuke has a favorite integer sequence, X_1, X_2, ..., X_N, so he wants to all...
#include<iostream> #include<cstdio> #include<cstring> const int N=1002; inline void apn(int &a,int b){ if(a>b)a=b; } inline char get_c(){ static char buf[20000],*h,*t; if(h==t){ t=(h=buf)+fread(buf,1,20000,stdin); } return h==t?EOF:*h++; } inline int nxi(){ int x=0; char c; while((c=get_c())>'9'||c<'0'); ...
On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis. Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i. Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i. For ever...
import java.util.Scanner; public class Main { public static void main(String[] args) { Main main = new Main(); main.run(); } long MOD = 1000000007; public void run() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int x[] = new int[n]; for(int i=0; i<n; i++) {...
Input The input is given from standard input in the following format. > $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$ Output * Print the maximum number of souvenirs...
#include <bits/stdc++.h> typedef long long int ll; #define FOR(i, a, b) for (ll i = (signed)(a); i < (b); ++i) #define REP(i, n) FOR(i, 0, n) #define EREP(i, n) for (int i = (n)-1; i >= 0; --i) #define MOD 1000000007 #define pb push_back #define INF 93193111451418101 #define MIN -93193111451418101 #define EPS 1e-11 #de...
Let's play Hit and Blow game. A imagines four numbers and B guesses the numbers. After B picks out four numbers, A answers: * The number of numbers which have the same place with numbers A imagined (Hit) * The number of numbers included (but different place) in the numbers A imagined (Blow) For example, if A imagin...
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a[]=new int[4]; int b[]=new int[4]; while(sc.hasNext()){ int hit=0,blow=0; for(int i=0;i<4;i++)a[i]=sc.nextInt(); for(int i=0;i<4;i++)b[i]=sc.nextInt(); for(int i=0;i<4;i++){ i...
Now, a ninja is planning to sneak into the castle tower from outside the castle. This ninja can easily run on the ground and swim in the moat, but he is not very good at climbing up from the moat, so he wants to enter the moat as few times as possible. Create a program that takes a sketch of the castle as input and ou...
#include <iostream> #include <vector> #include <string> #include <stack> #include <queue> #include <deque> #include <set> #include <map> #include <algorithm> // require sort next_permutation count __gcd reverse etc. #include <cstdlib> // require abs exit atof atoi #include <cstdio> // require scanf printf #include <f...
The secret organization AiZu AnalyticS has launched a top-secret investigation. There are N people targeted, with identification numbers from 1 to N. As an AZAS Information Strategy Investigator, you have decided to determine the number of people in your target who meet at least one of the following conditions: * Thos...
#include <bits/stdc++.h> using namespace std; int N, X, Y, Z; bool Data[3][100]; void solve() { int sum; sum = 0; for (int i = 0; i < N; ++i) { if ((!Data[0][i] && Data[2][i]) || (Data[1][i] && Data[2][i])) { ++sum; } } cout << sum << endl; } int main() { int num; memset(Data, false, sizeof(Data)); ...
After a long journey, the super-space-time immigrant ship carrying you finally discovered a planet that seems to be habitable. The planet, named JOI, is a harsh planet with three types of terrain, "Jungle," "Ocean," and "Ice," as the name implies. A simple survey created a map of the area around the planned residence. ...
from itertools import accumulate from operator import add line, row = [int(x) for x in input().split()] k = int(input()) L=[] J=[[0]*(row+1) for _ in range(line+1)] O=[[0]*(row+1) for _ in range(line+1)] I=[[0]*(row+1) for _ in range(line+1)] for _ in range(line): L.append(input()) for i in range(line): for j...
One day, the teacher came up with the following game. The game uses n cards with one number from 1 to 10 and proceeds as follows. 1. The teacher pastes n cards on the blackboard in a horizontal row so that the numbers can be seen, and declares an integer k (k ≥ 1) to the students. For n cards arranged in a horizontal...
#include <stdio.h> #include <cmath> #include <algorithm> #include <stack> #include <queue> #include <vector> #include <iostream> #include <set> typedef long long int ll; typedef unsigned long long int ull; #define BIG_NUM 2000000000 #define MOD 1000000007 #define PRIME1 99999883 #define PRIME2 99999893 #define EPS 0.00...
Mr. Simpson got up with a slight feeling of tiredness. It was the start of another day of hard work. A bunch of papers were waiting for his inspection on his desk in his office. The papers contained his students' answers to questions in his Math class, but the answers looked as if they were just stains of ink. His hea...
#include <bits/stdc++.h> using namespace std; using ll = long long; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second #define dbg(x) cout<<#x" = "<<((x))<<endl template<class T,class U> ostream& operator<<(ostream& o, const pa...
Example Input 6 6 3 1 9 4 3 6 1 2 1 4 2 6 5 4 6 5 3 2 Output 17
#include <bits/stdc++.h> #define ll long long using namespace std; struct state { ll s; int v,len; }; struct comp{ bool operator()(state a,state b) { return a.len>b.len; }}; priority_queue<state,vector<state>,comp> que; int n,m,c[50],ans; vector<int> G[50]; map<ll,int> d[50]; ll mask[50]; inline void add_edge(int f,...