input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.
More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by pay... | #include <bits/stdc++.h>
using namespace std;
const long long hell = 1000000007LL;
const long long INF = hell * hell;
const int MAXN = 1e5;
int main() {
if (!0) {
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(false);
}
int N, i, j;
cin >> N;
vector<int> a(N), b(N), pos(N + 1);
vector<pair<int, i... |
Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.
He has suggestions to wo... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-9;
int dcmp(const double &x) {
if (x < -eps) return -1;
if (x > eps) return 1;
return 0;
}
struct Point {
double x, y;
Point(double x = 0.0, double y = 0.0) : x(x), y(y) {}
};
Point operator-(Point a, Point b) { return Point(a.x - b.x, a.y - ... |
A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad).
The country Zeydabad is a rectangular table consisting of n rows and m columns. Each cell on the country is either 'z' or '.'.
The tourist knows this country is named Zeydabad because there are lots of ''Z-pattern"s in the country. A ''Z-... | #include <bits/stdc++.h>
using namespace std;
const int N = 3010;
int fenw[N];
void add(int pos, int what) {
for (int i = pos; i < N; i += i & (-i)) fenw[i] += what;
}
int pref(int r) {
int ans = 0;
for (int i = r; i > 0; i -= i & (-i)) ans += fenw[i];
return ans;
}
int segm(int l, int r) { return pref(r) - pre... |
n ants are on a circle of length m. An ant travels one unit of distance per one unit of time. Initially, the ant number i is located at the position si and is facing in the direction di (which is either L or R). Positions are numbered in counterclockwise order starting from some point. Positions of the all ants are dis... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 300005;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double EPS = 1e-9;
inline int sgn(double a) { return a < -EPS ? -1 : a > EPS; }
long long n, m, t;
struct node {
long long p;
int id;
int f;
} ant[maxn];
long long tp[maxn];
long ... |
Consider a linear function f(x) = Ax + B. Let's define g(0)(x) = x and g(n)(x) = f(g(n - 1)(x)) for n > 0. For the given integer values A, B, n and x find the value of g(n)(x) modulo 109 + 7.
Input
The only line contains four integers A, B, n and x (1 ≤ A, B, x ≤ 109, 1 ≤ n ≤ 1018) — the parameters from the problem s... | #include <bits/stdc++.h>
using namespace std;
const long long P = 1e9 + 7;
long long fpow(long long b, long long p) {
p %= (P - 1);
long long r = 1ll;
while (p) {
if (p & 1) r *= b, r %= P;
b = b * b % P;
p >>= 1;
}
return r;
}
int main() {
long long a, b, x, n;
scanf("%I64d%I64d%I64d%I64d", &... |
Alice wants to send an important message to Bob. Message a = (a1, ..., an) is a sequence of positive integers (characters).
To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function f, that maps each letter that appears in the string to so... | #include <bits/stdc++.h>
using namespace std;
int a[200010], n, m, block, Maxs, M;
inline int Read() {
char c = getchar();
int num = 0;
while ('0' > c || c > '9') c = getchar();
while ('0' <= c && c <= '9') num = num * 10 + c - '0', c = getchar();
return (num);
}
int heap[200010], top, del[510], num[200010], ... |
You are given n sequences. Each sequence consists of positive integers, not exceeding m. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the i-th sequence is ki.
Each second integers in each of the sequences are shifted by one to the left, i.e. integers a... | #include <bits/stdc++.h>
using namespace std;
const int MAX = 2e5 + 5;
int n, m, l, r, now, res, a[MAX], b[MAX], c[MAX], w[MAX], v[MAX], vis[42],
nex[MAX], head[MAX];
void add(int x, int y, int z) {
nex[++now] = head[x], w[now] = z;
head[x] = now, v[now] = y;
}
int _gcd(int x, int y) {
while (y) {
int t =... |
Hongcow really likes the color red. Hongcow doesn't like the color blue.
Hongcow is standing in an infinite field where there are n red points and m blue points.
Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the bound... | #include <bits/stdc++.h>
using namespace std;
const int N = 20010;
const long double eps = 1e-13;
struct P {
long double x, y;
} pb[N], pr[N], ipb[N], ipr[N], hb[N], o;
long double ms = 1e9, ml = 0;
int n, m, hbt, hrt;
P operator-(P a, P b) {
P c;
c.x = a.x - b.x;
c.y = a.y - b.y;
return c;
}
P operator+(P a,... |
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, r = 0, i, j, p = 0;
cin >> n;
int a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n);
for (i = 0; i < n; i++) {
if (a[0] == a[i] || a[n - 1] == a[i]) p++;
}
cout << n - p;
}
|
Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible.
Limak has a string s t... | #include <bits/stdc++.h>
using namespace std;
const int N = 80;
const int M = 1010;
const int INF = 0x3f3f3f3f;
const int mod = 1000000007;
long long qpow(long long a, long long b) {
long long ans = 1;
while (b) {
if (b & 1) ans = ans * a % mod;
a = a * a % mod;
b /= 2;
}
return ans;
}
long long qpo... |
Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.
The building consists of n floors with stairs at the left and the right sides... | #include <bits/stdc++.h>
using namespace std;
const int MOD9 = 1e9 + 7;
const int MOD91 = 1e9 + 9;
const long long MOD12 = 1e12 + 39LL;
const long long MOD15 = 1e15 + 37LL;
const int INF = 1e9;
const int base = 1e9;
const int MAX = 2e5;
const long double EPS = 1e-10;
int n, m;
int a[20][200];
int b[20];
int c[20];
int ... |
You are given a directed weighted graph with n nodes and 2n - 2 edges. The nodes are labeled from 1 to n, while the edges are labeled from 1 to 2n - 2. The graph's edges can be split into two parts.
* The first n - 1 edges will form a rooted spanning tree, with node 1 as the root. All these edges will point away fro... | #include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int D = 25;
struct Edge {
int u, v, w, nex;
} edges[N];
int head[N], etot;
void addEdge(int u, int v, int w) {
edges[++etot] = Edge{u, v, w, head[u]};
head[u] = etot;
}
int dep[N], L[N], R[N], id[N];
long long dis[N];
int rt[N][D];
int dfs... |
The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.
Unfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.
Vladimir wants to re... | #include <bits/stdc++.h>
using namespace std;
int lim;
bool used[100005];
int trans(string name, int type) {
int len = name.length();
for (int i = 0; i < len; ++i) {
if (name[i] < '0' || name[i] > '9') {
return -1;
}
}
if (name[0] == '0') {
return -1;
}
int shu = 0;
for (int i = 0; i < l... |
Mayor of city S just hates trees and lawns. They take so much space and there could be a road on the place they occupy!
The Mayor thinks that one of the main city streets could be considerably widened on account of lawn nobody needs anyway. Moreover, that might help reduce the car jams which happen from time to time o... | import java.io.*;
import java.util.*;
public class D_1296 {
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n=in.nextInt();
int[] s = new int[n], g = new int[n], min = new int[n], max = new int[... |
Priests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from k - 1 rocks, possesses power p and we want to... | #include <bits/stdc++.h>
using namespace std;
long long n, q, mod, a[100010];
map<long long, long long> mp;
long long qpow(long long x, long long n, long long mod) {
long long res = 1;
while (n) {
if (n & 1) res = res * x < mod ? res * x : res * x % mod + mod, n--;
x = x * x < mod ? x * x : x * x % mod + mo... |
Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.
A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with lengt... | #include <bits/stdc++.h>
using namespace std;
map<pair<string, int>, vector<pair<string, int> > > g;
int n;
string s, sr;
pair<string, int> pa[1000];
vector<pair<string, int> > que;
int a, ar;
map<string, int> ans;
void bfs() {
map<string, int> now;
for (int i = 0; i < que.size(); ++i) {
for (auto it = g[que[i]... |
Arkady the air traffic controller is now working with n planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The i-th plane, small enough to be represented by a point, currently has a coordinate of xi and is moving with speed vi. It's guaranteed that xi·vi < ... | #include <bits/stdc++.h>
using namespace std;
class frac {
public:
long long int a, b;
frac() {}
frac(long long int aa, long long int bb) {
a = aa;
b = bb;
}
bool operator<(const frac q) const {
long long int aa = a, bb = b, qa = q.a, qb = q.b;
if (bb < 0) {
aa = -aa;
bb = -bb;
... |
Consider a [billiard table](https://en.wikipedia.org/wiki/Billiard_table) of rectangular size n × m with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture).
<image>
There is one ball at the point (x, y) currently. Max comes to the table and strikes the ball. ... | #include <bits/stdc++.h>
using namespace std;
long long exgcd(long long a, long long b, long long &x, long long &y) {
if (b) {
long long g = exgcd(b, a % b, x, y);
long long tmp = x;
x = y, y = tmp - a / b * y;
return g;
} else {
x = 1, y = 0;
return a;
}
}
int main() {
ios::sync_with_st... |
Ashima's mid term exams are just over. Since, its raining heavily outside, she can't go shopping.
So, she and her best friend Aishwarya have now decided to chill out by eating pizza, chocolates, biscuits, etc.. and playing some indoor games.
The pizza guy has just delivered the pizza, but they forgot to order any soft-... | t = input()
for x in range(0,t):
a ,b ,c = map(int,raw_input().split())
if int(a)%2!= 0:
print "Ashima"
elif int(b)%2!=0:
print "Ashima"
elif int(c)%2!=0:
print "Ashima"
else:
print "Aishwarya" |
Ben was playing with the Omnitrix in free time. He screwed up once again. Not knowing what he was doing, he accessed the DNA analysis and modification subroutine of the watch and accidentally manipulated the DNA of an alien.
While fighting with Vilgax, he realized that one of his alien is not accessible. He some how ... | T = int(input())
for t in range(T):
A1 = raw_input()
A2 = raw_input()
l1 = len(A1)
l2 = len(A2)
maximum = 0
for offset in range(l1-l2+1):
#print "offset =", offset
counter = 0
for i in range(l2):
#print "i =", i
if A1[i+offset]==A2[i]:
#print "comparing", A1[i+offset], A2[i]
counter+=1
if ma... |
Rufus wants to go to the Lily's birthday party to surprise Lily. But Lily's party invitation has a unique code on it which is in the form X-Y(e.g. 123-456). So Rufus need a invitation but he fails to get the invitation.
So he decided to make a invitation on his own with a fake code on it. But each code has a unique ch... | f=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025]
for i in xrange(input()):
a,b=map(int,raw_input().split())
c=0
for i in f:
if a<=i<=b:c+=1
if c&1:print("INVALID")
else:print("VALID") |
On Unix computers, data is stored in directories. There is one root directory, and this might have several directories contained inside of it, each with different names. These directories might have even more directories contained inside of them, and so on.
A directory is uniquely identified by its name and its parent... | t = input()
mkdir_a = []
for i in range(t):
paths = dict()
temp = []
inp = raw_input()
inp = inp.split()
for j in range(int(inp[0])):
temp = raw_input()
folder = []
c = 0
parent = 0
par = ""
path =""
while c != len(temp):
if temp[c] == '/' or (c + 1) == len(temp):
if parent == 1:
f... |
Jack stays in a n-storey hostel. His dorm room is on the jth floor. Every morning, he is in so much hurry for classes that he cannot not decide whether to take Lift or Stairs to reach ground-floor. He asks you to help him choose either Stairs or Lift based on total time taken to reach ground-floor.
It takes him 10 sec... | import os
import sys
import random
import math
def main():
t=int(raw_input())
for i in range(t):
inp=str(raw_input()).split(" ")
n=int(inp[0])
j=int(inp[1])
l=int(inp[2])
if inp[3]=="U":
stairst=j*10
if l==n and j==n:
liftt=10+n*5+10;
elif l>j:
liftt=(n-l)*5+10+(n-j)*5+10+j*5+10;
else:
... |
Micro's midsem exams are finally over. When they were going on, instead of studying he would spend time making list of things that he wanted to do after the exams. But, now when they are over, he has lost the list. He was feeling very low, so his roommate Naik gave him a game to kill time.
He gave him N blocks. Each ... | Size=int(raw_input())
N=map(str,raw_input().split())
#print N
def comp(x,y):
return int(x+y) - int(y+x)
L=sorted(N,reverse=True,cmp=comp)
ans=''
for i in L:
ans+=i
print ans |
Ramesh and Suresh are now given One Last Task, to distribute tickets to all the students as their admissions are finalized. Sounds simple, but there's one twist, they are supposed to give 1 ticket to the first student, 2 tickets to the second student, 3 tickets to the third student and so on. Now, the professor knows t... | for _ in xrange(input()):
n=input()
if n==100000000:
print "987459712"
continue
t=(n*(n+1))
t//=2
print t |
Problem :
Bajirao asks Avni out on a date. However, Avni will go out with him only on one condition :
Bajirao has to tell her all possible N - digit numbers such that all the digits of every number he tells her are distinct , non-zero and less than or equal to N.
Also, he has to tell her all these numbers in asc... | t=int(raw_input());
import itertools;
while t!=0:
t-=1;
n=int(raw_input());
l=[i for i in range(1,n+1)];
l=list(itertools.permutations(l));
for i in l:
s='';
for j in i:
s+=str(j);
print s,
print |
Let us define an easy Sorting Algorithm called SoftSort. SoftSort Sorting algorithm involves use of IF and ELSE decision statements only. For example :
To sort two numbers a and b. SoftSort Algorithm's Code is given below.
void print(int a,int b){
printf( "%d %d\n",a,b);
}
void sort( int a, int b){
if( b < ... | dic = {0:1}
i=1
while i<10**6+1:
dic[i] = (i*dic[i-1])%(10**9 + 7)
i += 1
x = int(raw_input())
for elem in range(x):
y = int(raw_input())
n = (3*dic[y] + 3) % (10**9 + 7)
print n |
A palindrome is a string that is the same whether it is read from left to right or from right to left. Chota Bheem likes palindromes a lot. As a birthday gift he received two strings A and B. Now he is curious if there is a way to insert string B into string A so that the resulting string is a palindrome. You agreed to... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
t = long(raw_input());
while ( t ):
a= raw_input();
b= raw_input();
c = 0L;
s= a+b;
if ( s == s[::-1] ):
c+=1;
for i in range (0,len(a)) :
s = a[0:i]+b+a[i:];
if ( s ==... |
You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j). A nonnegative integer A_{i,j} is written for each square (i,j).
You choose some of the squares so that each row and column contains at most K chosen squares. Under this constraint, calculate the maximum v... | public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
FastPrintStream pw = new FastPrintStream();
solve(sc, pw);
sc.close();
pw.flush();
pw.close();
}
public static void solve(FastScanner sc, FastPrintStream pw) {
... |
Takahashi the Jumbo will practice golf.
His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).
If he can achieve the objective, print `OK`; if he cannot, print `NG`.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \... | #include <bits/stdc++.h>
using namespace std;
int main()
{
int k, a, b;
cin >> k >> a >> b;
cout << ((b / k) * k >= a ? "OK" : "NG") << endl;
} |
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all th... | import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().spli... |
We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.
You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.
Print `YES` if you can sort p in ascending order in th... | N=int(input())
p=list(map(int,input().split()))
a=0
for i in range(N):
if p[i]!=i+1:
a+=1
if a>=3:
print('NO')
else:
print('YES') |
We have a round pizza. Snuke wants to eat one third of it, or something as close as possible to that.
He decides to cut this pizza as follows.
First, he divides the pizza into N pieces by making N cuts with a knife. The knife can make a cut along the segment connecting the center of the pizza and some point on the ci... | #include <bits/stdc++.h>
#define rep(i, a, b) for(int i = (a); i <= (b); i++)
#define per(i, a, b) for(int i = (a); i >= (b); i--)
using namespace std;
const int mod = 1e9 + 7;
const int N = 1000010, inv3 = (mod + 1) / 3;
int n, ans, ba = 1;
int inv[N];
int main() {
scanf("%d", &n), inv[0] = inv[1] = 1;
rep(i, 2, n)... |
In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc.
The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0).
Aoki, an explorer, conducted a survey to identify the center ... | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] x = new int[n];
int[] y = new int[n];
int[] h = new int[n];
for(int i=0; i<n; i++) {
x[i] = in.nextInt(... |
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase... |
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
string s;
cin >> s;
int cnt[26] = {};
for(auto i:s)cnt[i-'a']++;
bool is = false;
for(int i = 0;i<26;i++)
{
if(cnt[i]==0&&is==false)
{
is = true;
s.push_back('a'+i);
}
}
if(is)cout<<s<<endl;
else
{
string t = ... |
Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.
Constraints
* 1 \leq N \leq 10^9
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the largest square number not exceeding N... | import math;print(round((math.sqrt(int(input()))//1))**2) |
Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below. Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.
b4ab979900ed647703389d4349eb84ee.png
Constraints
* x and y are integers.
* 1 ≤ x < y ≤ 12
Input
Input i... | L=[1,0,1,2,1,2,1,1,2,1,2,1]
a,b=map(int,input().split())
if L[a-1]==L[b-1]:
print("Yes")
else:
print("No") |
Takahashi and Aoki are going to together construct a sequence of integers.
First, Takahashi will provide a sequence of integers a, satisfying all of the following conditions:
* The length of a is N.
* Each element in a is an integer between 1 and K, inclusive.
* a is a palindrome, that is, reversing the order of elem... | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
const int INF = 1 << 30;
ll mod_pow(ll a, ll n) {
if (n == 0) return 1;
if (n % 2 == 0) {
ll tmp = mod_pow(a, n / 2);
return (tmp * tmp) % MOD;
}
return (a * mod_pow(a, n - 1)) % MOD;
}
ll cnt[10001];
int main() {
int ... |
Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.
He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See ... | #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> a(n);
int sum=0,ave1,ave2,s=0,t=0;
for(int i=0;i<n;i++){
cin >> a[i];
sum+=a[i];
}
ave1=sum/n;
ave2=(sum+n-1)/n;
for(int i=0;i<n;i++){
s+=(a[i]-ave1)*(a[i]-ave1);
t+=(a[i]-ave2)*(a[i]-ave2);
}
co... |
Stellar history 2005.11.5. You are about to engage an enemy spacecraft as the captain of the UAZ Advance spacecraft. Fortunately, the enemy spaceship is still unnoticed. In addition, the space coordinates of the enemy are already known, and the "feather cannon" that emits a powerful straight beam is ready to launch. Af... | // AOJ 0115
#include <iostream>
#include <cmath>
using namespace std;
typedef double Real;
const Real EPS = 1e-5;
struct plane{
Real a, b, c, d;
plane() {}
plane(Real a, Real b, Real c, Real d) : a(a), b(b), c(c), d(d) {}
};
struct vect {
Real x, y, z;
vect(Real x = 0, Real y = 0, Real z = 0) : x(x), y(y), z(z... |
A witch named Marie lived deep in a remote forest. Since she is a witch, she magically covers everything she needs to live, such as food, water, and fuel.
Her magic is activated by drawing a magic circle using some magical stones and strings. This magic circle is drawn by placing stones and tying several pairs of ston... | #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;
#define NUM 100000
int N,E;
int height[NUM],boss[NUM];
int in_num[NUM];
int get_boss(int id){
if(id == boss[id])return id;
else{
re... |
Given a string consisting of only numbers from 0 to 9, consider the operation of creating a new string from that string according to the following rules. Read the given string one character at a time from the left end. Go, if the same number a continues r, write the number r and the number a in this order without separ... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder sb = new StringBuilder();
whi... |
Klein is trying to get her dog Jack into the Frisbee Dog Tournament. But she's not sure if Jack will get a good grade. For her, she simulates the tournament to get Jack's grade. I want you to create a program to estimate.
The tournament is held by N dogs on a two-dimensional plane. At the start of the tournament, the ... | #include<complex>
#include<vector>
#include<iostream>
#include<stack>
#include<cmath>
#define sc second
#define fr first
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
using namespace std;
typedef double elem;
typedef complex<elem> point, vec;
typedef pair<point, point> line, hline, seg, pp;
const double eps =... |
Hierarchical Democracy
The presidential election in Republic of Democratia is carried out through multiple stages as follows.
1. There are exactly two presidential candidates.
2. At the first stage, eligible voters go to the polls of his/her electoral district. The winner of the district is the candidate who takes a ... | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string S;
vector<long long> vals[100]; // 深さ d のところに一時格納する値たち
long long solve() {
for (int i = 0; i < 100; ++i) vals[i].clear();
int depth = 0;
int val = 0;
for (int i = 0; i < S.size(); ++i) {
if (S[i] == '[') ... |
You got an old map, which turned out to be drawn by the infamous pirate "Captain Q". It shows the locations of a lot of treasure chests buried in an island.
The map is divided into square sections, each of which has a digit on it or has no digit. The digit represents the number of chests in its 9 neighboring sections ... | #pragma GCC optimize "O3"
#define F first
#define S second
#define ALL(x) x.begin(), x.end()
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL, int> PLI;
constexpr int N = 19, INF = INT_MAX / 2;
const int di[9] = {-1, -1, -1, 0, 0, 0, 1, 1, 1};
const int dj[9] = {-1, 0, 1, -1, ... |
Problem
A large-scale joint party is held every year at Aizu University.
This year, N men and M women will participate.
Males are assigned IDs from 0 to N-1, and females are assigned IDs from 0 to M-1.
At this joint party, you will be presented with the IDs of your "loved person" and "moderately favorite person".
Eac... | #include <bits/stdc++.h>
using namespace std;
typedef long long weight;
typedef pair<weight, int> P;
struct edge {
int to;
int cap;
weight cost;
int rev;
edge(int to_, int cap_, weight cost_, int rev_):to(to_), cap(cap_), cost(cost_), rev(rev_) {}
};
constexpr weight INF = (1ll << 55);
vector<vector<edge>... |
You have an appointment to meet a friend of yours today, but you are so sleepy because you didn’t sleep well last night.
As you will go by trains to the station for the rendezvous, you can have a sleep on a train. You can start to sleep as soon as you get on a train and keep asleep just until you get off. However, bec... | #include<bits/stdc++.h>
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
using namespace std;
const char EMPTY = 'X';
struct Node{
short value;
/*
lazy :
A : 加算の遅延 ( ADD )
S : 区間の要素を指定した値にする遅延 ( SET )
lazy_coef :
区間にいくら加算するのかor何をセットするのかを記録
*/
char lazy;
short la... |
Many cats live on the campus of a school. Natsume's daily routine is to pet those cats. However, the cats may be capricious and go for a walk off campus.
The campus site is a rectangle with each side parallel to the x-axis or y-axis and is surrounded by a fence except for the gate, but cats can freely enter and exit t... | #include <iostream>
using namespace std;
int main(){
int T;
cin>>T;
for(int t1=0;t1<T;t1++){
int x,y,w,h;
cin>>x>>y>>w>>h;
int N,ans=0;
cin>>N;
for(int i=0;i<N;i++){
int nx,ny;
cin>>nx>>ny;
if(nx>=x&&ny>=y&&nx<=x+w&&ny<=y+h)++ans;
}
cout<<ans<<endl;
}... |
Problem statement
Two players are playing the game. The rules of the game will be described below.
There is a board of $ N × N $ squares, and each square has the number $ X_ {i, j} $ ($ 1 \ leq i, j \ leq N $) written on it. The first move and the second move alternately select hands and accumulate points. The first ... | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <assert.h>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
static const dou... |
Problem Statement
Kikuchi loves big bicycles. Today he is still riding his favorite bike on the cycling road.
There are N towns in the area where he lives. Each town will be called town 1, town 2 ..., town N. The town where he lives is Town 1. Many people in this area have a hobby of cycling, and recently, cycling ro... | #include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <numeric>
#include <utility>
#include <iomanip>... |
Example
Input
3
()(()((
))()()(()
)())(())
Output
Yes | #include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
typedef pair<int,int> pii;
int main(){
int n;
string s;
cin >> n;
vector<pii> v1,v2;
rep(i,n){
cin >> s;
pii p = pii(0,0);
rep(j,s.size()){
if(s[j]=='('){
p.first++;
}else{
if(p.first)p.... |
D: Country In Distortion-
story
Alice was completely bored. This is because the White Rabbit, who is always playing with him, is out to Trump Castle. (Ah, I wish I had gone out with him in this case.) Alice thought. However, this is a country of distortion. If you go out so easily, you will get very tired. What does ... | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
struct Edge {
ll to, cost;
Edge(ll t, ll c) : to(t), cost(c) {}
};
struct Elem {
ll dist, speed, cur;
Elem(ll a, ll b, ll c) : dist(a), speed(b), cur(c) {}
};
bool operator>(const Elem& a, const Elem& b) {
return a.dist != b.di... |
F: MOD Rush
problem
Given a positive integer sequence A of length N and a positive integer sequence B of length M.
For all (i, j) (1 \ leq i \ leq N, 1 \ leq j \ leq M), find the remainder of A_i divided by B_j and output the sum of them.
Input format
N M
A_1 A_2 ... A_N
B_1 B_2 ... B_M
Constraint
* 1 \ leq N,... | #include <bits/stdc++.h>
using namespace std;
#define int long long
#define FOR(i, s, n) for (int i = (s); i < (n); i++)
#define RFOR(i, s, n) for (int i = (n) - 1; i >= (s); i--)
#define REP(i, n) FOR(i, 0, n)
#define RREP(i, n) RFOR(i, 0, n)
#define ALL(a) a.begin(), a.end()
#define IN(a, x, b) (a <= x && x < b)
cons... |
Run, Twins
E869120 You started running from home to school at a speed of $ P $ meters per minute.
square1001 noticed E869120's forgotten thing $ A $ minutes after E869120 left home and chased at $ Q $ meters per minute.
Then E869120 noticed something left behind $ B $ minutes after E869120 left home and turned back ... | a,b = map(int,input().split())
p,q,r = map(int,input().split())
print((b*p+b*r+a*q)/(r+q))
|
Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:
* $update(s, t, x)$: change $a_s, a_{s+1}, ..., a_t$ to $x$.
* $getSum(s, t)$: print the sum of $a_s, a_{s+1}, ..., a_t$.
Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0.
Constraints
* $... | #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... |
You are given a sequence of N integer numbers A. Calculate the sum of Ai AND Aj for all the pairs (i, j) where i < j.
The AND operation is the Bitwise AND operation, defined as in here.
Input
The first line of input consists of the integer N.
The second line contains N integer numbers - the sequence A.
Output
Out... | import fileinput
import math
foundN = False
for line in fileinput.input():
if not foundN:
N = int(line)
foundN = True
continue
number_list = map(int, line.split())
bit_count = [0]*31
for number in number_list:
for i in range(31):
if number & (1 << ... |
Balajiganapathi and Bipin are brothers. They have saved their money to buy Dairy Milk for their respective girlfriend on this Valentine's day. Balaji managed to buy M chocolates and Bipin managed to buy N chocolates.
They have made a bet as if who will give more Dairy Milk to their girlfriend.If Bipin manages to give... | t=int(raw_input())
for i in range(t):
n,m=map(int,raw_input().split())
if m>n:
print "Balaji",m-n
elif n>m:
print "Bipin",n-m
else:
print "No Winner" |
Once upon a time, a king and a few of his soldiers were caught by an enemy king in a war.
He puts them in a circle. The first man in the circle has to kill the second man, the third man has to kill the fourth, fifth man to kill the sixth and so on. When the circle is completed, the remaining people have to form a ci... | N,i=input(),1;
while i<=N:
i*=2;
i/=2; print 1+2*(N-i); |
Chef is known to have friends as well as enemies. Chef has a habit of communicating with friends through encrypted messages. But recently some of his enemies found the way to decrypt and get the original message. You need to write a program that simulates how the enemies decrypted the messages.
Chef’s enemies observe... | def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
def fibo(n):
a=0
b=1
fibon=[0,1]
while(b<n):
c=a+b
fibon.append(c)
a=b
b=c
return fibon
n=int(raw_input())
i=0
stri=[]
singlelist=[]
finalsingle=[]
alphabet=['a','b','c','d','e'... |
Did you know that the yummy golden triangle was introduced in India as early as 13th century ? By the way, I'm referring to the popular South Asian snack, Samosa. I guess its hard to code while thinking of Samosa, especially if you are very hungry now ; so lets not get in to any recipe or eating game.
You have N box... | import sys
from operator import itemgetter
num_tests = int(sys.stdin.readline())
def search(bands, box, lo, hi):
if lo == hi:
return None
mid = lo + (hi - lo) / 2
band = bands[mid][1]
if not mid:
return mid
if bands[mid - 1][1] < box and band >= box:
return mid
if ... |
Euler's phi function for a positive integer N is usually denoted as φ(N) and defined as the number of positive integers less than or equal to N that are coprime with N. Let's call a positive integer N a super number if N can be divided by φ(N) without a remainder.
e.g. 2 is a super number (since 2 mod φ(2) = 0), whi... | t = input()
while t:
L, R = map(int,raw_input().split())
answer = 0
value = 2
while( value <= R ):
current = value
while current <= R:
if L <= current <= R:
answer+=1
current *= 3
value *= 2
if L <= 1 <= R:
answer+=1
print answer
t-=1 |
You are given two strings a and b consisting of lowercase English letters, both of length n. The characters of both strings have indices from 1 to n, inclusive.
You are allowed to do the following changes:
* Choose any index i (1 ≤ i ≤ n) and swap characters a_i and b_i;
* Choose any index i (1 ≤ i ≤ n) and sw... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
string a, b;
cin >> a;
cin >> b;
int ans = 0;
for (int i = 0; i < n / 2; ++i) {
map<char, int> c;
c[a[i]]++;
c[a[n - i - 1]]++;
c[b[i]]++;
... |
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to l... | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class C {
class T implements Comparable<T>{
char ch;
int c;
public T(char ch, int c) {
this.ch = ch;
this.c = c;
}
public int compareTo(... |
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4.
Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q... | n = int(input())
s = list(map(int, input().split()))
d = {}
mt = False
mti = -1
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = 1
else:
d[s[i]] += 1
if d[s[i]] > 2:
mt = True
mti = i
good = []
for i in d.keys():
if d[i] == 1:
good.append(i)
if len(... |
XXI Berland Annual Fair is coming really soon! Traditionally fair consists of n booths, arranged in a circle. The booths are numbered 1 through n clockwise with n being adjacent to 1. The i-th booths sells some candies for the price of a_i burles per item. Each booth has an unlimited supply of candies.
Polycarp has de... | from sys import stdin
input = stdin.readline
n, t = map(int, input().split())
lst = list(map(int, input().split()))
s = sum(lst)
x = min(lst)
candy = n * (t // s)
t -= s * (t // s)
while t >= x:
s, c = 0, 0
for i in lst:
if i <= t - s:
c += 1
s += i
candy += c * (t // s)
... |
There are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the da... | n = int(input())
p = [(None, None)]
for _ in range(n):
p.append(list(map(int, input().split())))
if n==3:
print("1 2 3")
else:
for idx, (a, b) in enumerate(p[1:], 1):
if a in p[b]:
p[idx] = [b]
elif b in p[a]:
p[idx] = [a]
return_val = [p[1][0]]
n-=1
while n:
return_val.append(p[return_val[... |
This is an interactive problem!
An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element (x_i - x_{i - 1}, where i ≥ 2) is constant — such difference is called a common difference of the sequence.
That is, an arithmetic progression is a ... | #include <bits/stdc++.h>
using namespace std;
using i64 = long long int;
using ii = pair<int, int>;
using ii64 = pair<i64, i64>;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
bool used[1000005];
int main() {
int n;
cin >> n;
mt19937 mt(chrono::high_resolution_clock::now().time_since_ep... |
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are ex... | def the_doors(arr,n):
count_1 = 0
count_0 = 0
for i in arr:
if i == 0:count_0 += 1
else:count_1 += 1
check_1 = 0
check_0 = 0
for i in range(n):
if arr[i] == 0:
check_0 += 1
else:
check_1 += 1
if count_0 == check_0:
retur... |
This problem is same as the next one, but has smaller constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to the n... | import java.io.*;
import java.util.*;
public class E1066 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
... |
This problem is a version of problem D from the same contest with some additional constraints and tasks.
There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type pres... | //package cf570d3;
import java.io.*;
import java.util.*;
public class G{
// ------------------------
static class X implements Comparable<X>{
int nof, f;
public X(int N,int F){
nof=N;
f=F;
}
public int compareTo(X other){
if(nof!=other.nof)
return nof-other.nof;
return other.f-f;
}
public... |
You are given an array a_1, a_2, …, a_n.
In one operation you can choose two elements a_i and a_j (i ≠ j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the size of the array.... | n=int(input())
a=list(map(int, input().split()))
if(sum(a)<2*max(a) or sum(a)%2==1):
print("NO")
else:
print("YES") |
You are in charge of the BubbleReactor. It consists of N BubbleCores connected with N lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring.
Your task is to start the BubbleReactor by starting each BubbleCor... | #include <bits/stdc++.h>
using namespace std;
int const INF = (int)1e9 + 1e3;
long long const INFL = (long long)1e18 + 1e6;
mt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());
uniform_int_distribution<long long> ll_distr;
long long rnd(long long a, long long b) {
return ll_distr(tw) % (b - a ... |
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct str... | t=int(input())
for ti in range(t):
n=int(input())
lia=[]
lib=[]
a=list(input())
b=list(input())
ctr=0
for i in range(n):
if a[i]!=b[i]:
lia.append(a[i])
lib.append(b[i])
ctr+=1
if ctr>2:
print("No")
break
if ctr=... |
You are given two sets of integers: A and B. You need to output the sum of elements in the set C = \\{x | x = a ⊕ b, a ∈ A, b ∈ B\} modulo 998244353, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Each number should be counted only once.
For example, if A = \{2, 3\} a... | #include <bits/stdc++.h>
using namespace std;
const int mod = 998244353, inv2 = (mod + 1) / 2;
int n, m, rt[2], ch[60 * 100 * 8][2], cnt, ans;
bool Real[60 * 100 * 8];
void ins(int &i, long long l, long long r, long long x, long long y) {
if (!i) i = ++cnt;
if (x <= l && r <= y) return void(Real[i] = 1);
long lon... |
Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A sequence a is a subsegment of a... | #include <bits/stdc++.h>
using namespace std;
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
;
long long n, m;
cin >> n >> m;
long long ans = 0;
long long fact[n + 1];
fact[0] = 1;
for (long long i = 1; i <= n; i++) fact[i] = (fact[i - 1] * i) % m;
for (long long i = 1; i <... |
You are given a string s. You can build new string p from s using the following operation no more than two times:
1. choose any subsequence s_{i_1}, s_{i_2}, ..., s_{i_k} where 1 ≤ i_1 < i_2 < ... < i_k ≤ |s|;
2. erase the chosen subsequence from s (s can become empty);
3. concatenate chosen subsequence to th... | # by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
from math import inf,isinf
def solve(s,t):
if len(t) == 1:
if s.count(t[0]):
return 'YES'
return 'NO'
for i in range(1,len(t)):
dp = [[-inf]*(i+1) for _ in range(len(s)+... |
You are given three integers n, k, m and m conditions (l_1, r_1, x_1), (l_2, r_2, x_2), ..., (l_m, r_m, x_m).
Calculate the number of distinct arrays a, consisting of n integers such that:
* 0 ≤ a_i < 2^k for each 1 ≤ i ≤ n;
* bitwise AND of numbers a[l_i] \& a[l_i + 1] \& ... \& a[r_i] = x_i for each 1 ≤ i ≤ m... | #include <bits/stdc++.h>
using namespace std;
const int MOD = (119 << 23) + 1;
const int MX = 5e5;
int l[MX], r[MX], x[MX], one[MX + 2], dp[MX + 2], zer[MX + 2], ps[MX + 2];
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k, m;
cin >> n >> k >> m;
for (int i = 0; i < m; ++i) {
cin >> l[i] >>... |
This is an interactive problem.
John and his imaginary friend play a game. There are n lamps arranged in a circle. Lamps are numbered 1 through n in clockwise order, that is, lamps i and i + 1 are adjacent for any i = 1, …, n - 1, and also lamps n and 1 are adjacent. Initially all lamps are turned off.
John and his f... | #include <bits/stdc++.h>
using namespace std;
bitset<1000> want, have;
int main() {
int n, ans = 0, opt = 1;
scanf("%d", &n);
for (int i = 2; i <= n; ++i) {
if (n - (n + i - 1) / i - i + 1 > ans) {
ans = n - (n + i - 1) / i - i + 1;
opt = i;
}
}
for (int i = 0; i < n; ++i) {
if (i % op... |
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their ... | #include <bits/stdc++.h>
using namespace std;
int isvowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
return 1;
else
return 0;
}
int isry(string s1, string s2, int k) {
int l1, l2, ctr1 = 0, ctr2 = 0, i, j, pos1 = -1, pos2 = -1;
l1 = s1.length();
l2 = s2.length();
f... |
As Gerald, Alexander, Sergey and Gennady are already busy with the usual New Year chores, Edward hastily decorates the New Year Tree. And any decent New Year Tree must be decorated with a good garland. Edward has lamps of m colors and he wants to make a garland from them. That garland should represent a sequence whose ... | #include <bits/stdc++.h>
using namespace std;
long long n, m, p, l[1000100], a[5050][5050], x[5050], y[5050], h[5050],
f[5050];
void pre(void) {
a[1][1] = 1;
for (long long i = 2; i < 5050; ++i)
for (long long j = 2; j <= i; ++j)
a[i][j] = a[i - 1][j - 1] + (j - 1) * a[i - 1][j], a[i][j] %= p;
}
void ... |
You are given an undirected graph consisting of n vertices and n edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.
Your task is to calculate the number of simple paths of length at leas... | import java.util.*;
import java.io.*;
public class E_1454 {
static ArrayList<Integer>[] adjList;
static int s, d;
static boolean[] path, vis;
public static boolean findPath(int u) {
vis[u] = true;
if(u == d)
return path[u] = true;
boolean flag = false;
for(int v : adjList[u])
if(!vis[v])
flag... |
Long time ago there was a symmetric array a_1,a_2,…,a_{2n} consisting of 2n distinct integers. Array a_1,a_2,…,a_{2n} is called symmetric if for each integer 1 ≤ i ≤ 2n, there exists an integer 1 ≤ j ≤ 2n such that a_i = -a_j.
For each integer 1 ≤ i ≤ 2n, Nezzar wrote down an integer d_i equal to the sum of absolute d... | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode... |
<image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
public class Main{
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringT... |
To AmShZ, all arrays are equal, but some arrays are more-equal than others. Specifically, the arrays consisting of n elements from 1 to n that can be turned into permutations of numbers from 1 to n by adding a non-negative integer to each element.
Mashtali who wants to appear in every problem statement thinks that an ... | #include <bits/stdc++.h>
const int P = 998244353, G = 3;
void inc(int &a, int b) {
a + b >= P ? a += b - P : a += b;
}
void dec(int &a, int b) {
a < b ? a += P - b : a -= b;
}
int plus(int a, int b) {
return a + b >= P ? a + b - P : a + b;
}
int minus(int a, int b) {
return a < b ? a + P - b : a - b;
}
int qp... |
Last summer Peter was at his granny's in the country, when a wolf attacked sheep in the nearby forest. Now he fears to walk through the forest, to walk round the forest, even to get out of the house. He explains this not by the fear of the wolf, but by a strange, in his opinion, pattern of the forest that has n levels,... | #include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000009;
long long n, f[1000100], g[1000100], times = 1;
long long t(long long x) {
if (x % 2) return x / 2;
return 0;
}
signed main() {
scanf("%lld", &n);
f[0] = 0;
f[1] = 2;
g[1] = 4;
for (long long i = 2; i <= n; i++) g[i] = (1LL * ... |
Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using max_heap = priority_queue<T>;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5... |
Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j.
L... | #include <bits/stdc++.h>
using namespace std;
int main() {
int x, n;
cin >> x;
n = 1;
int sum = 1;
while (sum < x) {
n += 2;
sum = (n / 2 + 1) * (n / 2 + 1) + (n / 2) * (n / 2);
}
if (x == 3) n = 5;
cout << n << endl;
return 0;
}
|
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ... |
import java.util.*;
public class JavaApplication145 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] data = new int[size];
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i<size; i++)
{
data[i] = sc.nextInt();... |
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.
Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each f... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
scanf("%d %d", &n, &m);
string cur, next;
cin >> cur;
int t = 0;
int d = 1;
long long ans = 0;
for (int i = 1; i < n; i++) {
cin >> next;
if (cur[t] == '.' && next[t] == '.') {
ans++;
cur = next;
continue;
... |
Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.
The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch... | n, k = map(int,input().split())
f = t = 0
maxf = -1000000000
for i in range(n):
f, t = map(int,input().split())
if t > k: f -= (t - k)
if f > maxf: maxf = f
print(maxf) |
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves fir... |
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map;
public class R232C {
public static vo... |
Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
* either the boy in the dancing pair must dance for the first time (so... | def solver():
n,m = map(int, raw_input().split())
print n+m-1
for i in range(1,m+1):
print 1,i
for i in range(2,n+1):
print i,1
if __name__ == "__main__":
solver()
|
The boss of the Company of Robot is a cruel man. His motto is "Move forward Or Die!". And that is exactly what his company's product do. Look at the behavior of the company's robot when it is walking in the directed graph. This behavior has been called "Three Laws of Robotics":
* Law 1. The Robot will destroy itself... | #include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m, s, t;
cin >> n >> m;
vector<vector<int> > g(n + 1);
vector<bool> vis(n + 1, 0);
vector<int> indeg(n + 1, 0);
vector<int> dp(n + 1, -1);
deque<int> dq;
while (m--) {... |
Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump k squ... | //package cf36;
import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws Exception {
PrintStream out = new PrintStream("output.txt");
Scanner sc = new Scanner(new File("input.txt"));
int t = sc.nextInt();
int k = sc.nextInt();
for (int i=0; i<t; i++) {
int n =... |
This problem consists of two subproblems: for solving subproblem E1 you will receive 11 points, and for solving subproblem E2 you will receive 13 points.
A tree is an undirected connected graph containing no cycles. The distance between two nodes in an unweighted tree is the minimum number of edges that have to be tra... | #include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5;
int n1, n2, n3, x, y, ss, tot, last[N], nex[N * 2], to[N * 2];
long long sum, h, ans, ans1, g1, g2, g3, w, s1, s2, s[N], f[N], g[N], f1[N][2];
int read() {
int x = 0;
char ch = getchar();
for (; ch < '0' || ch > '9';) ch = getchar();
for (; ch... |
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog... | #include <bits/stdc++.h>
using namespace std;
int n;
int m;
int a[2000005];
long long dp[22][2];
void solve1() {
int cnt = 1;
for (int i = 0; i < n; i++) {
if (cnt == m) continue;
for (int j = 0; j < m; j += cnt * 2) {
vector<int> v1, v2;
for (int k = j; k < j + cnt; k++) {
v1.push_back(... |
Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if h... | r = lambda: list(map(int, input().split()))[1:]
n,c = map(int, input().split())
d = []
for _ in range(n):
for i in r():
if i<c:
d.append(str(_+1))
break
print (len(d))
print (' '.join(d)) |
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon... | n=int(input())
s=list(map(int,input().split()))
m,h,d=0,0,0
for i in range(n):
m+=h-s[i]
if(m<0):
d-=m
m=0
h=s[i]
print(d) |
A monster is attacking the Cyberland!
Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF).
During the battle, every second the monster's HP decrease by max(0, ATKY - DEFM), while Yang's HP decreases by max(0,... | #include <bits/stdc++.h>
using namespace std;
template <typename T>
inline string toString(T a) {
ostringstream os("");
os << a;
return os.str();
}
template <typename T>
inline long long toLong(T a) {
long long res;
istringstream os(a);
os >> res;
return res;
}
template <typename T>
inline int toInt(T a) ... |
A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple:
x2 + 2bx + c = 0 where b, c are natural numbers.
Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover ... | #include <bits/stdc++.h>
int main() {
static int kk[5000000 * 2 + 1];
long long ans;
int n, m, b, r;
scanf("%d%d", &n, &m);
ans = 0;
r = 0;
for (b = 1; b <= n; b++) {
long long b2 = (long long)b * b;
ans += b2 < m ? b2 : m;
while ((long long)r * r + m < b2) r++;
if (r < b) {
ans -= b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.