input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int i;
int x;
x = (n - 2) / k;
if ((n - 2) % k) x++;
int y;
y = (n - 1) / k;
if ((n - 1) % k) y++;
cout << x + y << endl;
for (i = 1; i < n; i++) {
cout << i << " " << min(n, i + k) << endl;
}
return 0;
}
|
Connect the countless points with lines, till we reach the faraway yonder.
There are n points on a coordinate plane, the i-th of which being (i, yi).
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes th... | import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
static int point[]=new int[1010];
static int n;
static boolean judge(double x){
int flag=0;
int po=-1;
for(int i=2;i<=n;i++){
//斜率公式:(y2-y1)=k*(x2-x1)
if(point[i]-point[1]==x*(i-1)) continue;
... |
You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.
You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7.... | #include <bits/stdc++.h>
using namespace std;
long long mi[1000100];
vector<int> des[1000100];
int x[100010], y[100010];
map<int, int> mp;
bool vis[1000100];
pair<int, int> dfs(int s) {
vis[s] = true;
pair<int, int> p = make_pair(1, 0);
for (int k = 0; k < des[s].size(); k++) {
p.second++;
if (!vis[des[s]... |
This is an interactive problem. Refer to the Interaction section below for better understanding.
Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.
<image>
Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.
This game ... | #include <bits/stdc++.h>
using namespace std;
int n, m, c;
int a[1005];
int main() {
int cnt = 0;
cin >> n >> m >> c;
for (int i = 0; i < m; ++i) {
int x;
cin >> x;
if (x <= c / 2) {
for (int j = 1; j <= n; ++j) {
if (x < a[j]) {
a[j] = x;
printf("%d\n", j);
... |
As we all know, Dart is some kind of creature from Upside Down world. For simplicity, we call their kind pollywogs. Dart and x - 1 other pollywogs are playing a game. There are n stones in a row, numbered from 1 through n from left to right. At most 1 pollywog may be sitting on each stone at a time. Initially, the poll... | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
template <class T>
inline bool setmin(T &a, T b) {
if (a > b) return a = b, 1;
return 0;
}
template <class T>
inline bool setmax(T &a, T b) {
if (a < b) return a = b, 1;
re... |
Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.
You are given an array a of length n and an integer c.
The value of some array b of length k is the sum of its elements except for the <image> smallest. For example, the value of the array [3, 1, 6, 5, 2]... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n, c;
cin >> n >> c;
long long arr[n];
for (long long i = 0; i < n; i++) cin >> arr[i];
if (c == 1) {
cout << 0;
return 0;
}
long long dp[n];
for (long long... |
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo... | #include <bits/stdc++.h>
using namespace std;
vector<long long> v;
bool super(long long x) {
int a = 0, b = 0;
while (x) {
if (x % 10 == 4)
a += 1;
else
b += 1;
x /= 10;
}
return a == b;
}
int main() {
int n;
cin >> n;
queue<long long> q;
q.push(4);
q.push(7);
while (q.front(... |
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no mo... | import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int k = sc.nextInt();
Knight[] knight = ... |
You are given a array of integers. Find the diff between the maximum average value and minimum average value of sub-sequences of array.
Input:
First line contains a single integer denoting N, the number of elements of array.
Next line contains N space separated integers denoting the array.
Output:
Print the greate... | t = input()
arr = list(map(int,raw_input().split()))
data = []
for x in arr:
temp = 0
for y in arr:
temp = float(x+y)/2
if(temp - int(temp)== 0):
temp = int(temp)
data.append(temp)
print max(data)-min(data) |
Harry was contesting to be the most stylist person in his college. He had to collect maximum points from the judges to be able to win. However there was a problem. The judges were sitting in a line and each pair of adjacent judges had ego issues with each other. So if one judge gave X points to Harry then the next judg... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
max_scores=[]
def max_score(points):
max_scores.append(points[0])
for index in range(1,len(points)):
if index==1:
max_scores.append(max(points[1],max_scores[0]))
else:
max_s... |
Now after having the event list, all the participants wanted to know where to go for their respective events, for this purpose they are given a piece of paper with an n x n grid of numbers printed on it. They are told that their event would be held in a room denoted by the number which they get on finding the minimum p... | N=input();
matrix = [map(int,raw_input().strip().split()) for x in xrange(N)]
n, m = len(matrix), len(matrix[0])
cost = [matrix[i][-1] for i in xrange(n)]
for i in xrange(m-2, -1, -1):
cost[0] += matrix[0][i]
for j in xrange(1, n):
cost[j] = min(cost[j], cost[j-1]) + matrix[j][i]
for j in xrange(n-2, -1, -1):
... |
PRAVAH, an annual techfest is being organised at SKIT. Naina comes up with an idea for an event Guess The Number. In this event, the computer thinks up a random number and the player is asked to guess that number and enter it in the system. if the number is correct, the player wins.
Rakesh, a student who is good at ha... | N1 = int(raw_input())
N2 = int(raw_input())
mod = False
res = "loses"
allequal = True
while(N1>0):
a = N1 % 10
b = N2 % 10
if (a != b):
allequal = False
if not(mod):
mod = True
res = "wins"
else:
res = "loses"
break
N1 = N1/10
N2 = N2/10
if(allequal):
print("wins")
else:
print(res) |
There is a 2D matrix of N rows and M columns. Rows are number 1 to N from top to bottom and columns 1 to M from left to right. You are standing at (1,1).
From, A [ i ] [ j ] you can move to A [ i + 1 ] [ j ] if A [ i + 1 ] [ j ] > A [ i ] [ j ].
Or, from, A [ i ] [ j ] you can move to A [ i ] [ j + 1 ] if A [ i ] [... | def process(mat, n, m):
sol = [[1 for j in range(m)] for i in range(n)]
for i in reversed(range(n-1)):
if mat[i+1][m-1] > mat[i][m-1]:
sol[i][m-1] = sol[i+1][m-1] + 1
for j in reversed(range(m-1)):
if mat[n-1][j+1] > mat[n-1][j]:
sol[n-1][j] = sol[n-1][j+1] + 1
#print sol
for i in reversed(r... |
Continuing the trend, this year too we present a 'Mystery' for you to solve!
You will be given two numbers: a and b; and you have to output a single integer. See the sample test cases for hints.
Input:
The first line of the input will contain an integer t : the number of test cases. Each of the next t lines contain ... | for tc in range(int(raw_input())):
a,b=map(int,raw_input().split())
print a%b |
Karan and Akshay love challenging each other with awesome algorithmic questions. Today, Karan decided to give Akshay a relatively easy question. Karan has string s of length N consisting entirely of lowercase latin characters and he loves double palindromes (defined below). So he asks Akshay Q questions about the strin... | from string import ascii_lowercase
A = ord("a")
ad = {}
for c in ascii_lowercase:
i = ord(c) - A
ad[c] = 2 ** i
n = int(raw_input())
t = (n + 1) * [0]
s = raw_input().strip()
for i in range(n):
t[i+1] = t[i] ^ ad[s[i]]
for _ in range(int(raw_input())):
l, r = map(int, raw_input().split())
if r - l < 1:
print "N... |
Let us see how search engines work. Consider the following simple auto complete feature. When you type some characters in the text bar, the engine automatically gives best matching options among it's database. Your job is simple. Given an incomplete search text, output the best search result.
Each entry in engine's da... | def solution():
n, q = map(int, raw_input().strip().split(' '))
tr = Trie()
for i in range(n):
string, weight = raw_input().strip().split(' ')
tr.add(string, int(weight))
for j in range(q):
string = raw_input().strip()
values = tr.search(string)
if values == 0:
... |
Slugtera is a town where three types of people lives which are criminals , terminator and life saver . Criminals are represented by o and terminator are represented by x and saver are represented by * . So in this story x function is to kill all o but however if * comes between o and x then x is not able to kil... | tc=int(raw_input())
for case in range(tc):
s=raw_input()
c=0
ans=""
q=0
for i in range(len(s)):
if s[i]=="*":
if "x" in s[q:i]:
for k in s[q:i]:
if k=="x":
ans=ans+k
else:
for k in s[q:i]:
ans=ans+k
ans=ans+"*"
q=i+1
if "x" in s[q:]:
for k in s[q:]:
if k=="x":
ans=an... |
Unfortunately someone has come and eaten the problem statement. Are you good enough to solve it without the statement?
Input
The first line contains T denoting the number of test cases.
The next T lines describe test cases and contain two integers each: N and M.
Output
For each test case output one integer - answer ... | for _ in xrange(int(raw_input())):
n, m = map(int, raw_input().split())
arr = [sum([int(x)**2 for x in str(n)])]
arrset = set(arr)
for x in xrange(m - 1):
arr.append(sum([int(x)**2 for x in str(arr[-1])]))
if arr[-1] in arrset:
# arr.pop()
break
arrset.add... |
We have a grid with A horizontal rows and B vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation:
* Assume that the grid currently has a horizontal rows and b vertical columns. Choose "vertical" or "horizontal".
* If we choose "vertical", insert one row at th... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll f[3005][3005];
int A,B,C,D,mod=998244353;
int main(){
scanf("%d%d%d%d",&A,&B,&C,&D);
f[A][B]=1;
for (int i=A;i<=C;++i) {
for (int j=B+(i==A);j<=D;++j) {
f[i][j]=(f[i][j-1]*i+f[i-1][j]*j-f[i-1][j-1]*(i-1)%mod*(j-1))%mod;
}
}
printf("%lld... |
Takahashi is a member of a programming competition site, ButCoder.
Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.
The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inn... | N, R = map(int, input().split())
print(R + max(0, 100 * (10 - N))) |
Given are positive integers A and B.
Let us choose some number of positive common divisors of A and B.
Here, any two of the chosen divisors must be coprime.
At most, how many divisors can we choose?
Definition of common divisor
An integer d is said to be a common divisor of integers x and y when d divides both x a... | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
List<Long> l1 = insu(a);
List<Long> l2 = insu(b);
HashSet<Long> h = new HashSet<Long>(l1);
l1.clear();
l1.addAll(h);
h = new HashSet<L... |
Takahashi, who is A years old, is riding a Ferris wheel.
It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currenc... | a,b = map(int,input().split())
if a > 12:
print(b)
elif a < 6:
print(0)
else:
print(b//2) |
There are N flowers arranged in a row. For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively. Here, h_1, h_2, \ldots, h_N are all distinct.
Taro is pulling out some flowers so that the following condition is met:
* The heights of the remaining flowers ar... | #include<bits/stdc++.h>
using namespace std;
long long solve(){
int n;
cin>>n;
vector<int>H(n);
vector<long long>V(n);
for(int i=0;i<n;i++) cin>>H[i];
for(int i=0;i<n;i++) cin>>V[i];
map<int,long long>A; //more height means more dp[i]
long long dp[n];
dp[0]=V[0];
A[H[0]]=V[0];
long long ans=V[0];
for(int i=... |
Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.
As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times.
Find the N-th smallest intege... | D, N = map(int, input().split(" "))
print(((100**D)*(N+(N//100))))
|
Find the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).
Constraints
* 1 \leq N \leq 10^4
* 1 \leq A \leq B \leq 36
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the s... | N, A, B = map(int, input().split())
print(sum(i for i in range(1, N+1) if A <= sum(int(c) for c in str(i)) <= B))
|
This contest, AtCoder Beginner Contest, is abbreviated as ABC.
When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.
What is the abbreviation for the N-th round of ABC? Write a program to output the answer.
Constraints
* 100 ≤ N ≤ 999
I... | #include<iostream>
using namespace std;
int main()
{
long long n;
cin>>n;
cout<<"ABC"<<n;
return 0;
} |
Snuke loves constructing integer sequences.
There are N piles of stones, numbered 1 through N. The pile numbered i consists of a_i stones.
Snuke will construct an integer sequence s of length Σa_i, as follows:
1. Among the piles with the largest number of stones remaining, let x be the index of the pile with the sma... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.PrintWriter;
public class Main {
static class Scanner {
BufferedReader br;
St... |
One day, AtCoDeer the deer found a simple graph (that is, a graph without self-loops and multiple edges) with N vertices and M edges, and brought it home. The vertices are numbered 1 through N and mutually distinguishable, and the edges are represented by (a_i,b_i) (1≦i≦M).
He is painting each edge in the graph in one... | #include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
#define LL long long
const int N=200,_N=N+33;
const int MOD=1000000007;
int n,m,k;
int fir[_N],nxt[_N],to[_N],tote=1;
int C[_N][_N];
void prework()
{
for(int i=0,j;i<=N;++i)
{
for(C[i][0]=1,j=1;j<=i;++j)
if((C[i][j]=C[i-1][j-1]+C[i-... |
Read the coordinates of four different points on the plane, $ A (x_A, y_A) $, $ B (x_B, y_B) $, $ C (x_C, y_C) $, $ D (x_D, y_D) $, and straight line $ Create a program that outputs YES if AB $ and $ CD $ are orthogonal, and NO if they are not orthogonal. Here, "straight line" does not mean a line segment. Please refer... | #include<cstdio>
double point[4][2];
double p(double b)
{
if(0>b)return -b;
return b;
}
int main()
{
while(true)
{
for(int i=0;i<4;i++)
{
for(int j=0;j<2;j++)
{
if(scanf("%lf",&point[i][j])==EOF)goto end;
}
}
if(((point[0][0]-point[1][0])*(point[2][0]-point[3][0])==-(point[2][1]-point[... |
Mr. A, who will graduate next spring, decided to move when he got a job. The company that finds a job has offices in several towns, and the offices that go to work differ depending on the day. So Mr. A decided to live in a town where he had a short time to go to any office.
So you decided to find the most convenient t... | #include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXC 12
int N,dis[MAXC][MAXC];
int main()
{
int m;
while(~scanf("%d",&N)&&N)
{
for(int i=0;i<=9;i++)
for(int j=0;j<=9;j++)
if(i==j)
dis[i][j]=0;
else
dis[i][j]=0x3FFFFFFF;
m=0;
for(int i=1,a,b,c;i<=N;i++)
... |
Yuki made a sugoroku so that everyone can play at the children's association event. In this sugoroku, squares are lined up in a ring, and each square has an integer of 1 or more written on it.
The player chooses a square as a starting point and places his piece. Advance the pieces clockwise by the number written on th... | #include <iostream>
using namespace std;
int x[100005],y[100005],a[100005],ans;
int main(void){
int n;
cin>>n;
for(int i=0;i<n;i++){
int num;
cin>>num;
a[i]=(i+num)%n;
}
for(int i=0;i<n;y[i]=-1,i++)x[i]=-1;
for(int i=0;i<n;i++){
int p=i,c=0;
while(x[p]==-1... |
Ball
In the Kingdom of IOI, a ball will be held to celebrate the birthday of Princess JOI, the princess.
N aristocrats will participate in the ball. N is an odd number. Aristocrats are numbered from 1 to N. Each aristocrat has an integer of goodness of dance, and the goodness of dance of aristocrat i (1 ≤ i ≤ N) is D... | #include<bits/stdc++.h>
using namespace std;
typedef long long int64;
const int64 INF = 1LL << 55;
int toChild[1000000][3];
int Buffer[99999];
vector< int > Dwill;
int N, M;
int MakeTree(){
queue< int > que;
for(int i = 0; i < N; i++){
que.push(i);
toChild[i][0] = -1;
toChild[i][1] = -1;
toChild... |
Let us enjoy a number guess game.
A number containing L digits is in my mind (where 4 <= L <= 10). You should guess what number it is. It is composed of any of the following ten digits:
"0","1","2","3","4","5","6","7","8", and "9".
No digits appear twice in the number. For example, when L = 4, "1234" is a legit... | #include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <cassert>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using names... |
A Bingo game is played by one gamemaster and several players. At the beginning of a game, each player is given a card with M × M numbers in a matrix (See Figure 10).
<image>
As the game proceeds, the gamemaster announces a series of numbers one by one. Each player punches a hole in his card on the announced number, i... | def solve():
from itertools import product
from sys import stdin
f_i = stdin
while True:
P, M = map(int, f_i.readline().split())
if P == 0:
break
bingo = []
for i in range(P):
b = []
card = list(map(int, f_i.readline().spl... |
Four-Coloring
You are given a planar embedding of a connected graph. Each vertex of the graph corresponds to a distinct point with integer coordinates. Each edge between two vertices corresponds to a straight line segment connecting the two points corresponding to the vertices. As the given embedding is planar, the li... | #include <bits/stdc++.h>
using namespace std;
struct Node { int x, y, c = -1; };
vector<Node> nodes;
vector<vector<int>> adj;
vector<bool> visited;
// cur から dst へ色 c1, c2 を使用して到達可能かを判定
bool CanReaach(const int cur, const int dst, const int c1, const int c2) {
if (cur == dst) return true;
visited[cur] = tru... |
Go around the Labyrinth
Explorer Taro got a floor plan of a labyrinth. The floor of this labyrinth is in the form of a two-dimensional grid. Each of the cells on the floor plan corresponds to a room and is indicated whether it can be entered or not. The labyrinth has only one entrance located at the northwest corner, ... | #include<deque>
#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>
#include<set>
#include<cmath>
#include<tuple>
#include<string>
#include<chrono>
#include<functional>
#include<iterator>
#include<random>
#include<unordered_set>
#include<array>
#include<map>
#include<iomanip>
#include<assert.h>
#inc... |
Arthur C. Malory is a wandering valiant fighter (in a game world).
One day, he visited a small village and stayed overnight. Next morning, the village mayor called on him. The mayor said a monster threatened the village and requested him to defeat it. He was so kind that he decided to help saving the village.
The may... | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
#define equals(a, b) (fabs((a) - (b)) < EPS)
using namespace std;
typedef long long ll;
t... |
Problem I: Custom paint craftsman
slip likes a video of a racing game. That said, I don't like videos of cars running, but I like videos of customizing the car body with the custom paint car creation feature of this game. This is a function that allows custom painting on the car body by superimposing basic geometric f... | #include<cstdio>
#include<vector>
#include<complex>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
typedef complex<double> Point;
const double EPS=1e-9;
const double PI=acos(-1);
class Line:public vector<Point>{
public:
Line(){}
Line(const Point &a,const Point &b){ push_back(a), push_back(b); }
};
... |
Given n integers a1, a2,…, an and n integers p1, p2,…, pn, integer m. The operation of selecting the kth integer ak with a probability of pk [%] is performed for each k (1 ≤ k ≤ n), and 0 or more and n or less integers are selected. Find the expected number of integers between 1 and m that are divisible by at least one... | #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <iomanip>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
#define MP make_pair
#define PB push_back
typedef long double ld;
typedef long long ll;
ll gcd(l... |
Ikta loves fast programs. Recently, I'm trying to speed up the division program. However, it doesn't get much faster, so I thought it would be better to make it faster only for "common sense and typical" inputs. The problem Ikta is trying to solve is as follows.
For a given non-negative integer n, divide p (n) − 1-dig... | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
int main() {
int n;
cin >> n;
if(n == 0) {
cout << 1%2 << endl;
}
if(... |
C: Shopping-Shopping-
story
Isono's older sister, Sazoe, decided to cook dinner for Isono and Nakajima, who are playing "that" and "that". Unfortunately, there are only a few ingredients left in the refrigerator, so Sazoe decided to go shopping. Mr. Sazoe is trying to buy some ingredients, but he is so cheerful that ... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 100000... |
G: Palindromic Subsequences
problem
Given a string S consisting only of lowercase letters, find out how many subsequences of this string S are not necessarily continuous and are palindromes.
Here, a subsequence that is not necessarily continuous with S is an arbitrary selection of one or more characters | S | charac... | #include <algorithm>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cassert>
#include <set>
#include <cstring>
using namespace std;
typedef long long ll;
#define SIZE 100010
#define INF 1000000000
#define mod 1000000007
ll dp[2010][2010];
int posl[26][SIZE], posr[26][SIZE];
int main(){
char s[... |
Problem
You brought a flat, holeless donut with a $ W $ horizontal $ H $ vertical $ H $ rectangle for ACPC.
Place this donut on the $ 2 $ dimension plane coordinate $ (0,0) $ with the center of the donut so that the side of length H and the $ y $ axis are parallel.
On the ACPC $ 1 $ day you ate a donut that was in t... | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9;
const ll LINF = 1e18;
template<class S,class T> ostream& operator << (ostream& out,const pair<S,T>& o){ out << "(" << o.first << "," << o.second << ")"; return out; }
template<c... |
Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is... | class BinaryTree:
class Node:
def __init__(self, nid, left, right):
self.id = nid
self.left = left
self.right = right
def has_left(self):
return self.left is not None
def has_right(self):
return self.right is not None
def... |
You are given a set $T$, which is a subset of $S$. The set $S$ consists of $0, 1, ... n-1$. Print all subsets of $T$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elemen... | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n; cin >> n;
int k; cin >> k;
int mask = 0;
while (k--) { int i; cin >> i; mask |= 1 << i; }
for (int b = mask; ; b = (b - 1) & mask) {
int rb = b ^ mask;
cout << rb << ":";
for ... |
You are given two positive integers – A and B. You have to check whether A is divisible by all the prime divisors of B.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
For each test case, you are given two space separated integers – A ... | t=input()
while (t):
a,b=raw_input().split()
a=eval(a)
b=eval(b)
print 'Yes' if (a**65)%b==0 else 'No'
t-=1 |
Arrays have fallen out of Chef's good books, and he plans to destroy all arrays he possesses. He is left with the last array A, consisting of N positive integers. In order to destroy the array, he can perform the following 2 types of operations any number of times.
Choose any 2 elements, say X and Y, from the given a... | # this is implementation of moors algorithm, where we have to find out whether there is an element whose frequency is more than half of the length of array.
# Answer of this problem can not be less than half of the length of array.
T = int(raw_input());
while T > 0:
T = T-1;
N = int(raw_input());
arr = raw... |
Devu is a little boy. He does not know how to take carries while adding two numbers in decimal base. eg. He will struggle in adding numbers 83 and 19, because
3 + 9 = 12 and he needs to take a carry of 1.
You are given an integer n. Can you write it in terms of sum of two positive integers such that while adding them ... | t = int(raw_input())
for i in range(t):
n = int(raw_input())
if n == 1 or n == 10 or n == 100 or n == 1000 or n == 10000 or n == 100000:
print "NO"
else:
print "YES" |
Problem description:
Faizaan and Sejal were playing Mathematics games. Faizaan gave Sejal three numbers: N, M and K. Sejal has to find out a number X such that
X = (N^M)%K
Sejal initially thought that the problem was very easy, but she soon realised that N and M were very huge numbers. Help Sejal find out X.
Note: A^... | t = int(raw_input())
for i in range(t) :
n = int(raw_input())
m = int(raw_input())
k = int(raw_input())
print pow(n,m,k) |
Roman has no idea, why this problem is called Stone. He also has no idea on how to solve the followong problem: given array of N integers A and a number K. During a turn the maximal value over all Ai is chosen, let's call it MAX. Then Ai =
MAX - Ai is done for every 1 <= i <= N. Help Roman to find out how will the arra... | fr=raw_input().split()
n=int(fr[0])
k=int(fr[1])
raw=raw_input().split()
l=[]
for i in range(0,n):
l.append(int(raw[i]))
if k==0:
for i in l:
print i,
print ""
me=max(l)
for i in range(0,n):
l[i]=me-l[i]
if k%2==1:
for i in l:
print i,
print ""
if k%2==0 and k!=0:
me=max(l)
for i in range(0,n):
l[i]=m... |
Olya works as a warehouse keeper for a T-Shirt factory. Now the factory is facing hard times, so currently they produce only the T-shirts of three kinds: red, green and blue T-Shirts. All the T-shirts are stored in the containers, each of the containers contain the T-Shirts of a single colour.
Now there are N container... | for _ in xrange(input()):
s = raw_input()
n = len(s)
rs = [0 for i in xrange(n)]
gs = [0 for i in xrange(n)]
bs = [0 for i in xrange(n)]
r, g, b = 0, 0, 0
for i in xrange(n):
rs[i] = r
gs[i] = g
bs[i] = b
if s[i] == 'r':
r += 1
if s[i] == '... |
Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have?
Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are conside... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, k;
cin >> n >> k;
if (k <= n) {
cout << ((k - 1) / 2) << endl;
} else if (k <= 2 * n - 1) {
cout << (2 * n - k + 1) / 2 << endl;
} else {
cout << 0 << endl;
}
}
|
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 312345;
int x[maxn], y[maxn], n;
inline int dis(pair<int, int> a, pair<int, int> b) {
return abs(a.first - b.first) + abs(a.second - b.second);
}
int main() {
scanf("%d", &n);
int xmx = -1e9, xmn = 1e9, ymx = -1e9, ymn = 1e9;
int r[4];
for (int(i)... |
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as fol... | #include <bits/stdc++.h>
using namespace std;
const long long INFll = 1ll * 1000000100 * 1000000100;
const long double PI =
3.141592653589793238462643383279502884197169399375105820974944;
vector<vector<int>> g;
int n, k;
vector<int> dist, par;
void bfs(int node) {
queue<int> q;
dist.assign(n, 1000000100);
par... |
The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland.
Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed e... | n,k = map(int,input().split())
s = list(map(int,input().split()))
p = list(map(int,input().split()))
r = {}
r2 = []
for i in range(n):
if s[i] in r:
if r[s[i]]>p[i]:
r2.append(p[i])
else:
r2.append(r[s[i]])
r[s[i]] = p[i]
else:
r[s[i]] = p[i]
r1 = k-le... |
The only difference between easy and hard versions is a number of elements in the array.
You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.
You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n.
You can choose some subset of... | #include <bits/stdc++.h>
using namespace std;
int n, m, cnt, sum, anssum, ansmx;
int a[200010], e[200010], s[200010];
int mini[200010], mx[200010], ans[200010];
int l[200010], r[200010];
inline void prework() {
scanf("%d%d", &n, &m);
int mx = -1e6, mini = 1e6;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i])... |
Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0).
Split the artists into two performance... | import sys
import random
N = int(input())
C = list(map(int, input()))
A = list(map(int, input()))
# N = random.randint(20, 40) * 2
# C = [random.randint(0, 1) for i in range(N)]
# A = [random.randint(0, 1) for i in range(N)]
def build_solution(i, j, x, y):
I = (0, 0)
J = (0, 1)
X = (1, 0)
Y = (1, 1)
ans = []
f... |
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path fro... | #include <bits/stdc++.h>
using namespace std;
long long int INF = 1e18;
const int N = 3e+5 + 5;
long long int cnt[2][N], vis[2][N], visup[2][N];
long long int n, m, k, x, u, v, ans, ct;
vector<pair<long long int, long long int>> adj[N];
string s;
queue<pair<long long int, long long int>> q;
void dfs(long long int i, in... |
This is the second subtask of problem F. The only differences between this and the first subtask are the constraints on the value of m and the time limit. It is sufficient to solve this subtask in order to hack it, but you need to solve both subtasks in order to hack the first one.
There are n+1 distinct colours in th... | #include <bits/stdc++.h>
using namespace std;
long long dp[1010][1010];
long long komm[1010][1010];
int n, m;
vector<int> t[501];
vector<int> v;
long long mod = 998244353;
long long solve(int a, int b);
long long kom(int a, int b) {
if (komm[a][b] != 0) {
return komm[a][b];
}
long long ans = 0;
for (int i =... |
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where ... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using dbl = long double;
const int MAXN = 1000;
const ll INF = 1e18;
int n, m, k;
ll a[MAXN][MAXN];
vector<pair<int, pii> > edges;
vector<ll> order;
int renum[200100];
int d[200100];
int main() {
ios_base::sync_with_stdio(... |
Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has n rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar i... |
import java.io.*;
import java.util.*;
public class A1214 {
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int d=sc.nextInt();
int e=sc.nextInt();
e=e*5;int min=n;
for(i... |
This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remov... | #include <bits/stdc++.h>
using namespace std;
void out(int a, bool ln) { printf("%d%c", a, ln ? '\n' : ' '); }
void out(long long a, bool ln) { printf("%lld%c", a, ln ? '\n' : ' '); }
void out(double a, int digit, bool ln) {
printf("%.*f%c", digit, a, ln ? '\n' : ' ');
}
void out(long double a, int digit, bool ln) {
... |
Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end!
The tournament consisted of n (n ≥ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After th... | #include <bits/stdc++.h>
using namespace std;
int fr[100005], n, b;
int sol[100005], use[100005];
vector<int> g[100005];
vector<int> nr[100005];
queue<int> q;
int main() {
cin.tie(0);
ios_base::sync_with_stdio(false);
cin >> n;
for (int i = 1; i <= n - 2; i++) {
int x, y, z;
cin >> x >> y >> z;
nr[i... |
New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.
Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly — the part which take... | import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
n, s = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
if a[ans] < a[i]:
ans = i
s -= a[i]
if (s < 0): break
if s >= 0:
ans = -1
print(ans ... |
This problem is interactive.
We have hidden a permutation p_1, p_2, ..., p_n of numbers from 1 to n from you, where n is even. You can try to guess it using the following queries:
? k a_1 a_2 ... a_k.
In response, you will learn if the average of elements with indexes a_1, a_2, ..., a_k is an integer. In other words... | //Implemented By Aman Kotiyal Date:-22-Jan-2021 Time:-3:49:30 pm
import java.io.*;
import java.util.*;
public class ques3
{
public static void main(String[] args)throws Exception{ new ques3().run();}
long mod=1000000000+7;
void solve() throws Exception
{
int n=ni();
int k=ni();
HashSet<Integer> set=new H... |
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left ha... | #include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long sum = 0, f = 1;
char ch = getchar();
while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if (ch == '-') ch = getchar(), f = -1;
while (ch <= '9' && ch >= '0') sum = sum * 10 + ch - '0', ch = getchar();
return sum * f;
... |
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights... | #include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n, k, l;
long long res = 0;
cin >> n >> k;
long long ar[n];
int con[n];
for (int i = 0; i < n; i++) {
cin >> ar[i];
con[i] = 0;
}
for (int i = 1; i < n - 1; i++) {
if (ar... |
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
... | for t in range(int(input())):
s=input()
one=s.count("1")
z=s.count("0")
if one==0 or z==0:
print(0)
else:
cost=one
mi=10**9
for i in s:
if i=="0":
cost+=1
else:
cost-=1
if mi>cost:
mi=... |
Koa the Koala has a matrix A of n rows and m columns. Elements of this matrix are distinct integers from 1 to n ⋅ m (each number from 1 to n ⋅ m appears exactly once in the matrix).
For any matrix M of n rows and m columns let's define the following:
* The i-th row of M is defined as R_i(M) = [ M_{i1}, M_{i2}, …, M... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) + (c ^ 48);
c = getchar();
}
return x * f;
}
inline void print(int x) {
if (x ... |
This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10, size = 1 << 20, mod = 998244353, inf = 2e9;
int n, col[N], pos[N];
vector<int> p[N];
long long s[5];
void dfs(int x, int c) {
if (col[x] >= 0) return;
col[x] = c;
s[c] += x;
c ^= 1;
if (x <= n)
dfs(x + n, c);
else
dfs(x - n, c);
... |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | from functools import reduce
import os
import sys
from collections import *
#from fractions import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value(): return tuple(map(int, input().split())) # multiple values
def a... |
This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void ckmax(T& x, T y) {
x = (y > x ? y : x);
}
template <typename T>
inline void ckmin(T& x, T y) {
x = (y < x ? y : x);
}
const int MAXN = 2e5;
const int INF = 1e9;
const int BOUND = 448;
int n, mxa, a[MAXN + 5];
int cnt[MAXN + 5], mp[MAXN ... |
There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i — the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city wit... | import sys
from sys import stdin
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
if ret[nex] > ret... |
You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 ≤ a_1 < a_2 < ... < a_k ≤ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ...,... | for q in range(int(input())):
n=input()
s=0
s1=0
p=0
l=len(n)
for i in range(l-1,0,-1):
if(n[i]=='0' and n[i-1]=='0' ):
s=1
p=i-1
break
for i in range(p,0,-1):
if(n[i]=='1' and n[i-1]=='1'):
s1=1
break
if(s1... |
Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n × m size. Each cell (i, j) on this ... | #include <bits/stdc++.h>
using namespace std;
#define IOS ios_base::sync_with_stdio(false); cin.tie (nullptr)
#define PREC cout.precision (10); cout << fixed
#ifdef CONVICTION
#include "/home/convict/Dropbox/myfiles/sport_coding/cplib/snippets/debug.h"
#else
#define debug(x...)
#endif
typedef long long ... |
The first ship with the Earth settlers landed on Mars. The colonists managed to build n necessary structures on the surface of the planet (which can be regarded as a plane, and the construction can be regarded as points on it). But one day the scanners recorded suspicious activity on the outskirts of the colony. It was... | #include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
Point operator+(const Point &p) const { return Point(x + p.x, y + p.y); }
Point operator-(const Point &p) const { return Point(x - p.x, y - p.y); }
Point op... |
Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, x1, y1, x2, y2;
scanf("%d%d%d%d%d%d", &n, &m, &x1, &y1, &x2, &y2);
if (max(abs(x1 - x2), abs(y1 - y2)) <= 4 && abs(x1 - x2) + abs(y1 - y2) < 7)
puts("First");
else
puts("Second");
return 0;
}
|
Pavel plays a famous computer game. A player is responsible for a whole country and he can travel there freely, complete quests and earn experience.
This country has n cities connected by m bidirectional roads of different lengths so that it is possible to get from any city to any other one. There are portals in k of ... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
struct Res {
int u, v;
long long w;
void read() { scanf("%d %d %lld", &u, &v, &w); }
bool operator<(const Res &t) const { return w < t.w; }
} edge[N];
struct Node {
int u;
long long w;
bool operator<(const Node &t) const { return w > t.... |
The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ... | #include <bits/stdc++.h>
using namespace std;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cer... |
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.
Let's call a positive integer a undoubtedly lucky, if there are suc... | #include <bits/stdc++.h>
using namespace std;
int ans = 0, n;
int numDistDig(int n) {
vector<int> arr(10, 0);
while (n > 0) {
arr[n % 10]++;
n /= 10;
}
int ans = 0, i;
for (i = 0; i < 10; i++) ans += (arr[i] > 0);
return ans;
}
void dfs(int num) {
if (num > 0 && num <= n) ans++;
if (ans >= 10000... |
Emuskald is an innovative musician and always tries to push the boundaries of music production. Now he has come up with an idea for a revolutionary musical instrument — a rectangular harp.
A rectangular harp is a rectangle n × m consisting of n rows and m columns. The rows are numbered 1 to n from top to bottom. Simil... | #include <bits/stdc++.h>
using namespace std;
const int maxside = 4;
const char sides[maxside + 1] = "TRBL";
const int maxn = (int)1e5;
int h, w;
inline int getnum(char ch, int pos) {
--pos;
int chi;
for (chi = 0; chi < maxside && sides[chi] != ch; chi++)
;
assert(chi < maxside);
if (chi == 2) pos = w - 1... |
This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.
Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them a... | #include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 7;
const long long inf = 1e9 + 7;
const long long mod = 1e9 + 7;
int n;
int m;
int x;
int y;
vector<int> g[N];
int main() {
ios_base::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> x >> y;
g[x].push_back(... |
Smart Beaver became interested in drawing. He draws suns. However, at some point, Smart Beaver realized that simply drawing suns is boring. So he decided to design a program that will process his drawings. You are given a picture drawn by the beaver. It will have two colors: one for the background and one for the suns ... | #include <bits/stdc++.h>
using namespace std;
long long rdtsc() {
long long tmp;
asm("rdtsc" : "=A"(tmp));
return tmp;
}
inline int myrand() { return abs((rand() << 15) ^ rand()); }
inline int rnd(int x) { return myrand() % x; }
const int maxn = (int)1600 + 10;
int a[maxn][maxn];
int used[maxn][maxn];
int maxu;
c... |
It's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a list of subjects that he can help... | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.io.*;
import java.util.*;
public class Main {
static boolean LOCAL = false;//System.getSecurityManager() == null;
Scanner sc = new Scanner(System.in);
int toi(String s) {
return Integer.parseInt(s.substring(0, 2)) * ... |
There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.
<image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1]
Polycarpus has bought a posh piano... | #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
vector<ll> prime_factors(ll num) {
vector<ll> ans;
while (num % 2) {
ans.push_back(2);
num /= 2;
}
for (int i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
ans.push_back(i);
num /= i;
}
... |
George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t.
Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second... | #include <bits/stdc++.h>
using namespace std;
int main() {
char c;
unsigned int t11, t12;
unsigned int t21, t22;
cin >> c;
t11 = (c - 48) * 10;
cin >> c;
t11 += c - 48;
cin >> c >> c;
t12 = (c - 48) * 10;
cin >> c;
t12 += c - 48;
cin >> c;
t21 = (c - 48) * 10;
cin >> c;
t21 += c - 48;
ci... |
You are given matrix a of size n × m, its elements are integers. We will assume that the rows of the matrix are numbered from top to bottom from 1 to n, the columns are numbered from left to right from 1 to m. We will denote the element on the intersecting of the i-th row and the j-th column as aij.
We'll call submatr... | #include <bits/stdc++.h>
using namespace std;
inline int rd() {
char c = getchar();
while (!isdigit(c)) c = getchar();
int x = c - '0';
while (isdigit(c = getchar())) x = x * 10 + c - '0';
return x;
}
inline void upmax(int& a, int b) {
if (a < b) a = b;
}
const int maxn = 403;
int n, m;
int a[maxn][maxn], f... |
One day, Okazaki Tomoya has bought a tree for Furukawa Nagisa's birthday. The tree is so strange that every node of the tree has a value. The value of the i-th node is vi. Now Furukawa Nagisa and Okazaki Tomoya want to play a game on the tree.
Let (s, e) be the path from node s to node e, we can write down the sequenc... | #include <bits/stdc++.h>
using namespace std;
int power(int a, int n, int mod) {
int res;
if (n == 0) return 1;
res = power(a, n / 2, mod);
res = (int)((long long)res * (long long)res % mod);
if (n % 2) res = (int)((long long)res * (long long)a % mod);
return res;
}
int in, tot, root, size[110000], value[11... |
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.
Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting... | #include <bits/stdc++.h>
using namespace std;
long long q[100010];
long long p[100010];
int main() {
int n, m;
while (~scanf("%d%d", &n, &m)) {
long long suma = 0;
for (int i = 0; i < n; i++) {
scanf("%I64d", &q[i]);
suma += q[i];
}
long long sumb = 0;
for (int i = 0; i < m; i++) {
... |
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. Howe... | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamW... |
Misha has an array of n integers indexed by integers from 1 to n. Let's define palindrome degree of array a as the number of such index pairs (l, r)(1 ≤ l ≤ r ≤ n), that the elements from the l-th to the r-th one inclusive can be rearranged in such a way that the whole array will be a palindrome. In other words, pair (... | #include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int n, a[N], lim[N], sum[N], ans;
void count(int l, int r) {
for (int i = (int)(1); i <= (int)(n); i++) lim[i] = sum[i];
int len = r - l + 1;
for (int i = (int)(1); i <= (int)(len / 2); i++)
if ((lim[a[r - i + 1]] -= 2) < 0)
return;
... |
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice t... | #include <bits/stdc++.h>
using namespace std;
int w, h, n;
void func(set<int> &s, multiset<int> &sdist, int x) {
auto it = s.upper_bound(x), it2 = it--;
sdist.erase(sdist.find(*it2 - *it));
sdist.insert(x - *it);
sdist.insert(*it2 - x);
s.insert(x);
}
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
cin... |
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i... | #include <bits/stdc++.h>
using namespace std;
int C[1010][1010] = {};
int main() {
int k, b, sum = 0;
long long ans = 1;
cin >> k;
C[0][0] = 1;
for (int i = (int)(1); i <= (int)(1000); i++)
for (int j = (int)(0); j <= (int)(i); j++)
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % 1000000007;
;
for (... |
You are given a string S of length n with each character being one of the first m lowercase English letters.
Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.
Recall that LCS ... | #include <bits/stdc++.h>
using namespace std;
char s[100005];
int n, m;
int main(void) {
scanf("%d%d%s", &n, &m, s);
long long sol = (long long)n * m - n;
for (int i = 1; i < n; ++i)
sol += (s[i] != s[i - 1]) * ((long long)n * m - n);
int curr = 1;
for (int i = 1; i < n; ++i) {
if (curr == 1) {
... |
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree... | #include <bits/stdc++.h>
using namespace std;
const int N = 1000 * 100;
int col[N + 3], sz[N + 3];
long long ans[N + 3];
map<int, long long>* cnt[N + 2];
map<int, long long>* val[N + 3];
vector<int> g[N + 3];
void dfs(int u, int p) {
int mx = -1, bigChild = -1;
sz[u] = 1;
for (auto v : g[u]) {
if (v == p) con... |
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may b... | import javafx.util.Pair;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Parameter;
import java.util.*;
public class Main {
private static final long INF = Long.MAX_VALUE >> 2;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStr... |
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the em... | #include <bits/stdc++.h>
using namespace std;
int main() {
string a1, a2, a, b, b1, b2, s;
cin >> a1 >> a2 >> b1 >> b2;
swap(a2[0], a2[1]);
swap(b2[0], b2[1]);
a += a1 + a2;
b += b1 + b2;
a.erase(a.find('X'), 1);
b.erase(b.find('X'), 1);
s += a + a;
if (s.find(b) != string::npos) {
printf("YES\n... |
Mayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.
Yusland consists of n intersections connected by n - 1 bidirectional roads. One can travel from any intersection to any other intersection using only these roads.
There is only o... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline bool upmin(T &x, T y) {
return y < x ? x = y, 1 : 0;
}
template <typename T>
inline bool upmax(T &x, T y) {
return x < y ? x = y, 1 : 0;
}
const long double eps = 1e-9;
const long double pi = acos(-1);
const int mods = 1e9 + 7;
const int oo ... |
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the ... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long t, s, x;
cin >> t >> s >> x;
if ((x - t) < s && x != t) {
cout << "NO";
return 0;
}
if (((x - t) % s != 0) && ((x - t - 1) % s != 0)) {
cout << "NO";
return 0;
}
cout << "YES";
return 0;
}
|
Welcome to the world of Pokermon, yellow little mouse-like creatures, who absolutely love playing poker!
Yeah, right…
In the ensuing Pokermon League, there are n registered Pokermon trainers, and t existing trainer teams each of which belongs to one of two conferences. Since there is a lot of jealousy between train... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int cf[N], t[N], ch[N], a[N], b[N];
vector<int> w[N];
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> a[i] >> b[i];
a[i]--;
b[i]--;
}
mt19937 rnd(time(0)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.