input stringlengths 29 13k | output stringlengths 9 73.4k |
|---|---|
We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki.
The i-th edge connects Vertex U_i and Vertex V_i. The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki).
Takahashi departs Vertex S and Aoki ... | // In The Name Of Allah
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
#define error(x) cout << #x << " = " << x << endl;
const int N = 1e5 + 5, mod = 1e9 + 7;
const ll inf = 1e15;
inline int sum(int a, int b) {
a += b;
if(a >= mod)
a -= mod;
if(a < 0)
a +... |
You are given an integer sequence of length N, a_1,a_2,...,a_N.
For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.
After these operations, you select an integer X and count the number of i such that a_i=X.
Maximize this count by making optimal choices.
Constraints
* 1≤N≤10^5
*... | #include <bits/stdc++.h>
using namespace std;
int n;
int a[100001];
int main() {
cin >> n;
for(int i = 0; i < n; i++) {
int x;
cin >> x;
if(x > 0) a[x-1]++;
a[x]++;
a[x+1]++;
}
int ans = 0;
for(int i = 0; i < 100001; i++) {
ans = max(ans,a[i]);
}
cout << ans << endl;
}
|
Snuke received an integer sequence a of length 2N-1.
He arbitrarily permuted the elements in a, then used it to construct a new integer sequence b of length N, as follows:
* b_1 = the median of (a_1)
* b_2 = the median of (a_1, a_2, a_3)
* b_3 = the median of (a_1, a_2, a_3, a_4, a_5)
* :
* b_N = the median of (a_1, ... | #include<bits/stdc++.h>
using namespace std;
long long read()
{
char ch=getchar();long long x=0,ff=1;
while(ch<'0'||ch>'9') {if(ch=='-') ff=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*ff;
}
void write(long long aa)
{
if(aa<0) putchar('-'),aa=-aa;
if(aa>9) write(aa/10);
putchar(... |
In the country there are N cities numbered 1 through N, which are connected by N-1 bidirectional roads. In terms of graph theory, there is a unique simple path connecting every pair of cities. That is, the N cities form a tree. Besides, if we view city 1 as the root of this tree, the tree will be a full binary tree (a ... | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
struct Pr{
ll x,y;
}l_r[210000],r_l[210000];
struct Te{
int ls,rs,lv,rv;
}t[210000];
int n;
ll mid;
vector<Pr>V[210000];
void insert(int x,Pr y){
//x sorted... |
<image>
There is a container that is bifurcated as shown in the figure. Drop 10 balls numbered from 1 to 10 through the opening A of the container and place the balls in the left cylinder B or the right cylinder C. Since plate D can rotate left and right around the fulcrum E, you can move plate D to decide whether to... | n=int(input())
i=1
while i<=n:
ball=list(map(int,input().split()))
left=[0]
right=[0]
m=0
while True:
#終了条件
if m==10:
print("YES")
#print("left",left,"right",right)
break
#noの条件
if ball[m]<left[len(left)-1] and ball[m]<right[len(rig... |
The king of a country loves prime numbers and gambling. The unit of currency in this country is called prime. As of November 1, 2007, Prime's cross-yen rate was just prime at 9973, so the King is overjoyed. Subsidiary coins with 1/101 prime as one subprime are used in this country.
The government of this country has d... | #include <iostream>
#include <stdio.h>
using namespace std;
int pr[1000003];
int main() {
int i,j,n,p,m,f,e,g;
for (i=2;i<1000000;i++) if (pr[i]==0) { pr[i]=2; for (j=i*2;j<1000000;j+=i) pr[j]=1;}
for (i=2,j=0;i<1000000;i++) { j+=pr[i]>1; pr[i]=j; }
while(cin >> n) {
if (n==0) break;
g=0;
for (;n>0;n--) {
... |
On the Internet shopping site, on the same page as the product that the user is currently viewing, some other products that other users have bought in the past along with the product that they are currently viewing are displayed. It is believed that sales can be increased by presenting products that are considered to b... | #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
struct Info{
char name[31];
};
struct Ans{
char left[31],right[31];
};
bool strCmp(char* base, char* comp){
int length1 = 0,length2 = 0;
for(int i=0;base[i] != '\0'; i++)length1++;
... |
problem
You love pasta, and you make and eat pasta for dinner every day. You can make three types of pasta: tomato sauce, cream sauce, and basil sauce.
I decided to plan a dinner for N days. Choose one of the three types of pasta each day. However, if the same pasta continues, you will get bored, so do not choose the... | #include <iostream>
#include <map>
using namespace std;
int n,k;
int memo[4][4][4][102];
map <int,int> ma;
int rec(int b,int y,int t,int idx){
if(b == y && y == t) return 0;
if(ma[idx] != '\0' && ma[idx] != t) return 0;
if(idx == n) return 1;
if(memo[b][y][t][idx] != 0) return memo[b][y][t][idx];
... |
Problem
KND is a student programmer at the University of Aizu. His neighbor is known to be very annoying. Neighbors find out that he is a sweet tooth and plan to add more sweetness than necessary to make him fat. To that end, your neighbor, you, was introduced to a sweets shop by a friend.
However, the way products a... | #include <bits/stdc++.h>
using namespace std;
#define MAX 334
typedef pair<int, int> pii;
int main()
{
int s, d, m;
while (cin >> s >> d >> m) {
vector<pii> v[s];
for (int i = 0; i < s; i++) {
int k, w, p;
cin >> k;
for (int j = 0; j < k; j++) {
... |
The fact that any positive integer has a representation as the sum of at most four positive squares (i.e. squares of positive integers) is known as Lagrange’s Four-Square Theorem. The first published proof of the theorem was given by Joseph-Louis Lagrange in 1770. Your mission however is not to explain the original pro... | #include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
int dfs(int n, int sum, int k, int sn) {
int ret = 0;
if ( k < 0 ) {
return 0;
}
else {
if (sn == sum) {
return 1;
}
}
if (sn > sum || n == 0) {
return 0;
}
if ( sn + (k * pow(n,2)) < sum ) {
return 0;
}
ret... |
Example
Input
Alice Bob
3
2
Alice Bob
Bob Clare
2
Bob Clare
Clare David
2
Clare David
David Alice
Output
No | #include<cstdio>
#include<vector>
#include<map>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;
map<string,int>myhash;
int hashclock=0;
int g[2000][310][310];
vector<int>fg[310][310];
bool visit[2000];
int n;
int getnu(){
string tss;
cin>>tss;
if(myhash.count(tss))
return myhash[tss];
h... |
Problem
There is a dial-type padlock. This Nanjing lock has five dials and an enter button.
Rotate the five dials to create a five-digit integer in hexadecimal, press the enter button to enter it, and if the entered value and password match, it will open. For each of the five dials
0,1,2,3,4,5,6,7,8,9, a, b, c, d, e... | #include<bits/stdc++.h>
using namespace std;
using Int = long long;
//BEGIN CUT HERE
template<typename T,bool directed>
struct Dinic{
struct edge {
int to;
T cap;
int rev;
edge(){}
edge(int to,T cap,int rev):to(to),cap(cap),rev(rev){}
};
vector<vector<edge> > G;
vector<int> level,iter;
D... |
There is a group that paints an emblem on the ground to invite aliens every year. You are a member of this group and you have to paint the emblem this year.
The shape of the emblem is described as follows. It is made of n regular triangles whose sides are equally one unit length long. These triangles are placed so tha... | #include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include... |
The rabbit, who successfully defeated the ambushed enemy, succeeded in advancing the hero into the enemy's castle. When the hero released the cats trapped in the castle dungeon, some of them were the hero's. It will help me.
According to the cats, to reach the Demon King in the back of the castle, you will have to go ... | #include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int m,n;
double dp[17][(1<<16) + 1];
double prob[17][17];
double calc(int f, int s) {
if (f == n) return 1.0;
if (dp[f][s] != -1.0) return dp[f][s];
double ret = 0;
for (int k=0; k<m; ++k) if (!(s & (1<<k))) { // ?????... |
F: Transparent mahjong tiles
You will play mahjong against Mr. Takanosu, a gambler who is rumored to have fallen into the darkness. Mr. Takanosu has been rumored to be a natural disaster, so he has proposed a game using a bizarre mahjong tile called Takanosu tile.
Mahjong is a game in which players hold multiple tile... | #include<cstdio>
#include<cstring>
#include<algorithm>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
int n,star;
int cnt[12]; // 数字 i が書かれた牌はあと i 個
int rem[12]; // * が i に成れるのは rem[i] 個まで
bool dfs(int i){
if(i==12) return star==0;
if(cnt[i]==0){
if(dfs(i+1)) return true;
}
// i, i, i
if(cnt[... |
F --Dangerous Delivery
Story
Person D had a serious mission. It is to deliver the next DAtaCoDer Regular Contest (DARC) D problem to Mr. Dhokudai, the president of DAtaCoDer. N cities are lined up in a straight line from city 1 where D's hideout is located to city N where the DAtaCoDer headquarters is located. During... | // * template
#include <bits/stdc++.h>
#ifdef LOCAL
#include "dump.hpp"
#else
#define dump(...)
#endif
using namespace std;
template<class T> inline void chmax(T &a, const T &b) { if(a < b) a = b; }
template<class T> inline void chmin(T &a, const T &b) { if(a > b) a = b; }
template<class T, class U> inline void fil... |
Example
Input
200 500 800 500
3
400 0
450 500
400 1000
3
600 0
550 500
600 1000
Output
100 600 | #include<bits/stdc++.h>
#define MAX 30
#define inf 1<<29
#define linf 1e16
#define eps (1e-8)
#define Eps (1e-15)
#define mod 1000000007
#define pi acos(-1)
#define phi (1.0+sqrt(5))/2.0
#define f first
#define s second
#define mp make_pair
#define pb push_back
#define all(a) (a).begin(),(a).end()
#define pd(a) printf(... |
F: 最短距離を伸ばすえびちゃん (Ebi-chan Lengthens Shortest Paths)
Problem
Ebi-chan loves directed graphs. One day, a directed graph with N vertices and M edges dropped from somewhere in front of Ebi-chan! The vertices and the edges of the graph is labeled with a number from 1 to N and from 1 to M, respectively. Moreover, the ith ... | #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
... |
Problem
There are $ N $ arithmetic progressions with the number of terms $ L $. The first term of the $ i $ arithmetic progression is $ a_i $ and the tolerance is $ d_i $. Arrange the first sequence, the second sequence, ..., the $ N $ sequence in order from the first sequence, and let the resulting sequence be $ A $.... | #include<bits/stdc++.h>
using namespace std;
#define MAX_N 100005
typedef long long ll;
ll calc(ll a,ll d,ll n){
if(n==0)return 0;
return ( a+a+d*(n-1) )*n/2;
}
ll N,X,L;
ll a[MAX_N],d[MAX_N];
ll solve2();
ll solve(){
ll res=0, val=0;
int j=0;
for(int i=0;i<N;i++){
while( j < i+L/X ){
val+=... |
You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.
Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2,... | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int N;
int main(){
cin >> N;
ll mini;
cin >> mini;
ll res = -1000000000000LL;
for(int i=1;i<N;i++){
int a; cin >> a;
res = max( res, a-mini );
mini = min( mini, (ll)a );
}
cout << res << endl;
} |
In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.
Note that use of goto statement ... | #include<stdio.h>
int main(){
int x;
scanf("%d",&x);
for(int a=1;a<=x;a++){
if(a%3==0){
printf(" %d",a);
}
else{
int b=a;
while(b>0){
if(b%10==3){
printf(" %d",a);
break;
}
b=b/10;
}
}
}
printf("\n");
return 0;
} |
How many ways are there to place a black and a white knight on an N * M chessboard such that they do not attack each other? The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically, or two squares vertically and one square horizontally. The knights attack ... | #!/usr/bin/python
# coding: utf-8
t=int(raw_input())
for i in range(t):
n,m=raw_input().split(' ')
n=int(n)
m=int(m)
if(n>1 and m>1):
ans=((n*m) * (n*m-1)) - (4*((n-1)*(m-2) + (n-2)*(m-1))) #nm*nm -9nm +12m +12n -16
else:
if(n==1):
ans=m*(m-1)
else:
ans=n*(n-1)
print ans
'''
How many ways are t... |
As you might know, cooking is the process of taking a food item and subjecting it to various processes(like heating, roasting, baking etc).
A food item gets prepared after it has been subjected to exactly N processes.
The order in which the processes are applied matters(heating and then baking is different from baking ... | from sys import stdin
MOD = 1000000007
for trial in xrange(int(stdin.readline())):
N,K = map(int,stdin.readline().split())
Kmod = K%MOD
K1mod=(K-1)%MOD
K2mod=(K-2)%MOD
if K==1: print 0
elif K==2: print 2
else:
inner = ((Kmod*K1mod*K1mod)%MOD + (Kmod*K1mod*K2mod*K2mod)%MOD)%MOD
... |
Problem Statement
Chef studies combinatorics. He tries to group objects by their rang (a positive integer associated with each object). He also gives the formula for calculating the number of different objects with rang N as following:
the number of different objects with rang N = F(N) = A0 + A1 * N + A2 * N^2 + A3 * N... | mod = 1000000007
comb_cache = {}
def combinations(n, r):
if r < (n // 2): r = n - r
if (n, r) in comb_cache: return comb_cache[(n, r)]
comb = 1
for i in xrange(r + 1, n + 1): comb *= i
for i in xrange(2, n - r + 1): comb /= i
comb_cache[(n, r)] = comb % mod
return comb
F_cache = {}
A0, A1, A2, A3 ... |
Okay. Before we begin, a hint : This one's taken from somewhere. Word to word. Google comes to mind, doesn't it? Here goes:
For the heck of it, we define a new sequence as the infinite sequence of all integers, in ascending order, that can represented as any positive integer power of 5 (i.e 5k where k is a positive i... | # imports
import sys
import StringIO
import math
class Problem(object):
def __init__(self, reader):
self.reader = reader
def run(self):
test_cases = int(self.reader.readline().strip())
for test_case in range(test_cases):
lucky_number = 0
number... |
Tuzik and his master Vanka are playing some unusual game. Initially there are two stacks of nuts. The first stack contains A nuts and the second contains B nuts. A player's move consists of two steps:
Choose one stack and eat it.
Split the other stack into two new stacks. If a player can't split it he loses (if stack... | T = int(raw_input())
while T > 0:
a = raw_input()
a = a.split(' ')
A = int(a[0])
B = int(a[1])
if A%2 !=0 and B%2 !=0:
print "Vanka"
else:
print 'Tuzik'
T = T - 1 |
Given n sticks' lengths, determine whether there is a solution to choose 2k out of them and use these 2k sticks to form two k-convex polygons (non-degenerated), namely, two convex polygons each has exactly k sticks as its sides, and every adjacent sticks are not parallel.
Input
The first line contains two space-separ... | from itertools import combinations
from collections import defaultdict
def small_j(sticks, cum, k):
for j in range(k - 1, len(sticks)):
i = j - k + 1
hyp = sticks[j]
rest = cum[j - 1] - cum[i] + sticks[i]
if rest > hyp:
return i, j
return None, None
def small_ii... |
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.
Recently scientists discovered that for every four... | #include <bits/stdc++.h>
using namespace std;
int n, m, q, nn;
int fa[400100];
int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
int ans;
void unionn(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
fa[x] = y;
nn--;
}
int main() {
int i, a, b;
for (i = 1; i <= 400000; i++) fa[i... |
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that:
gcd(sum(S_1), sum(S_2)) > 1
Here sum(S) denotes the sum of all elements present in set S and gcd means the[greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
Ev... | #include <bits/stdc++.h>
using namespace std;
vector<long long> let(26, 0);
int main() {
long long n;
cin >> n;
if (n <= 2) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
cout << n - 1 << " ";
for (int i = 0; i < n - 1; i++) {
cout << i + 1 << " ";
}
cout << endl << 1 << "... |
Consider a tree T (that is, a connected graph without cycles) with n vertices labelled 1 through n. We start the following process with T: while T has more than one vertex, do the following:
* choose a random edge of T equiprobably;
* shrink the chosen edge: if the edge was connecting vertices v and u, erase both ... | #include <bits/stdc++.h>
using namespace std;
int head[52], tot, size[52], n;
long double c[52][52], dp[52][52], tmp[52], g[52];
inline int rd() {
int x = 0;
char c = getchar();
bool f = 0;
while (!isdigit(c)) {
if (c == '-') f = 1;
c = getchar();
}
while (isdigit(c)) {
x = (x << 1) + (x << 3) +... |
Graph constructive problems are back! This time the graph you are asked to build should match the following properties.
The graph is connected if and only if there exists a path between every pair of vertices.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
template <class T, class U>
inline void che... |
There are n cities along the road, which can be represented as a straight line. The i-th city is situated at the distance of a_i kilometers from the origin. All cities are situated in the same direction from the origin. There are m trucks travelling from one city to another.
Each truck can be described by 4 integers:... | #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
using namespace std;
const int MAXN = 401;
const int INF = 1e9 + 5;
int city[MAXN], dp[MAXN][MAXN][MAXN];
int main() {
for (int i = 0; i < int(MAXN); i++)
for (int j = 0; j < int(MAXN); j++)
for (int k = 0; k < int(MAX... |
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:
You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.
Input
The first line contains an int... | import java.util.Arrays;
import java.util.Scanner;
public class PetyaAndDivisors {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] result = new int[n];
int[] divisor = new int[100000+5];
Arrays.fill(divisor, -1);
... |
On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number t is his lucky number, if it can be represented as:
t = a2 + b2, where a, b are arbitrary positive integers.
Now, the boys decided to f... | #include <bits/stdc++.h>
using namespace std;
bitset<300000001> gao;
int l, r;
int main() {
gao.set();
gao[1] = 0;
scanf("%d%d", &l, &r);
for (int i = 3; i * i <= r; i += 2)
if (gao[i]) {
int t = i << 1;
for (int j = i * i; j <= r; j += t) gao[j] = false;
}
int ans = l <= 2 && r > 1;
for... |
Nauuo is a girl who loves playing cards.
One day she was playing cards but found that the cards were mixed with some empty ones.
There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n... | #include <bits/stdc++.h>
using namespace std;
int a[200005], b[200005];
int fl[200005];
int tm[200005];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) cin >> b[i];
for (int j = 1; j <= n; j++)
if (b[j] == 1) {
int nfl = 1;
for (int k = j + ... |
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk... | a=int(input())
x=a
w=[]
while a>=0:
b=[]
b.append(a)
for i in range(a):
b.append(str(a-1-i))
b.insert(0,(a-1-i))
b.insert(0,' '*(2*(x-a)))
w.append(b)
w.insert(0,b)
a=a-1
w.pop(x)
for j in w:
xx=str(j)
xxx=xx.replace(',','')
xxxx=xxx.replace("'",'')
print(xxxx... |
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that:
* If we consider any color, all elements of this color must be divisible by the minimal element of this color.
* The number of used colors must be minimized.
For example, it's fine to paint elements [40, 1... | n=int(input())
arr = list(map(int,input().split()))
elem = {}
arr.sort()
for i in arr:
f=0
for k in elem:
if i%k == 0:
elem[k]+=1
f=1
break
if not f:
elem[i] = 1
print(len(elem)) |
You are given an integer array a_1, a_2, ..., a_n, where a_i represents the number of blocks at the i-th position. It is guaranteed that 1 ≤ a_i ≤ n.
In one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without b... | #include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 9;
int n, a[N], ans[N][N], m[N][2], g[N], e;
vector<pair<int, int> > p;
pair<int, int> k;
int solve(int x, int y) { return min(x - 1, y); }
int main() {
cin >> n;
for (int i = 1; i < n + 1; i++) cin >> a[i];
p.push_back(make_pair(1, n + 2));
for ... |
Doctor prescribed medicine to his patient. The medicine is represented by pills. Each pill consists of a shell and healing powder. The shell consists of two halves; each half has one of four colors — blue, red, white or yellow.
The doctor wants to put 28 pills in a rectangular box 7 × 8 in size. Besides, each pill occ... | //package round93;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
public class E {
InputStream is;
PrintWriter out;... |
[Æsir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos)
[Æsir - V.](https://soundcloud.com/kivawu/aesir-v)
"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.
The time right now...... 00:01:12......
It's time."
The emotion samples are now sufficient. After almost 3 ... | #include <bits/stdc++.h>
using namespace std;
int zs[5005][5005];
int num[5005];
int mp[5005];
int main() {
mp[1] = 1;
for (int i = 2; i <= 5000; i++) {
for (int j = 2; j < i; j++) {
zs[i][j] = zs[i - 1][j];
}
int k = i;
for (int j = 2; j * j <= k; j++) {
while (!(k % j)) k /= j, zs[i][j... |
You are given an array a_1, a_2, ..., a_n. You can perform the following operation any number of times:
* Choose a pair of two neighboring equal elements a_i = a_{i + 1} (if there is at least one such pair).
* Replace them by one element with value a_i + 1.
After each such operation, the length of the array w... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class E {
int[] ints;
int[][] dp;
int[][] compress;
int NO = 1000000;
public static void main(String[] args) throws NumberFo... |
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.
You have to answer t independent test cases.
Recall that the substring s[l ... | import string
def construct(n, a, b):
return ((string.ascii_lowercase[:b] + "a" * (a - b)) * (n // a + 1))[:n]
t = int(input())
for i in range(t):
n, a, b = map(int, input().split())
print(construct(n, a, b))
|
Petya and Vasya are competing with each other in a new interesting game as they always do.
At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≤ K ≤ S.
In order to win, Vasya ha... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, s;
cin >> n >> s;
if (2 * n <= s) {
cout << "YES\n";
for (int i = 0; i < n - 1; i++) {
cout << 2 << ' ';
s -= 2;
}
cout << s << '\n' << 1;
} else {
cout << "NO";
}
return 0;
}
|
You are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1 ≤ i < n) such that a_i < a_{i + 1}, and remove either a_i or a_{i + 1} from the array (after the removal, the remaining parts are concatenated).
For example, if you have the ar... | from sys import stdin
from math import ceil
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
n = int(inp())
a = [int(x) for x in inp().split()]
if a[0]< a[-1]:
print('YES')
else:
print('NO')
|
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won x rounds in a row. For example, if Bob won five rounds in a row and x = 2, then two sets ends.
You know that Alice and Bob... | #include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 1) + (x << 3) + c - '0';
c = getchar();
}
return x * f;
}
int n, las[2], p[10... |
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds.
Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb... | import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import m... |
You are given four integers n, c_0, c_1 and h and a binary string s of length n.
A binary string is a string consisting of characters 0 and 1.
You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change.
After some changes (possibly zero) ... | #include <bits/stdc++.h>
using namespace std;
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
long long t;
cin >> t;
while (t--) {
long long n, c0, c1, h;
cin >> n >> c0 >> c1 >> h;
string s;
cin >> s;
long long ans = 0;
for (long long i = 0; i < n;... |
You are given a sequence of n integers a_1, a_2, ..., a_n. Let us call an index j (2 ≤ j ≤ {{n-1}}) a hill if a_j > a_{{j+1}} and a_j > a_{{j-1}}; and let us call it a valley if a_j < a_{{j+1}} and a_j < a_{{j-1}}.
Let us define the intimidation value of a sequence as the sum of the number of hills and the number of v... | #include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<math.h>
#include<map>
typedef long long int ll;
using namespace std;
#define maxn 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
const int mm=3e5+100;
ll d[mm],num[mm];
int main()
{
ll n,m,i,j,t,a,b,c,p,k... |
Let F_k denote the k-th term of Fibonacci sequence, defined as below:
* F_0 = F_1 = 1
* for any integer n ≥ 0, F_{n+2} = F_{n+1} + F_n
You are given a tree with n vertices. Recall that a tree is a connected undirected graph without cycles.
We call a tree a Fib-tree, if its number of vertices equals F_k for som... | import java.util.*;
import java.io.*;
public class E1491 {
static ArrayList<Edge>[] adjList;
static int[] subTree;
static int[] fib;
static class Edge {
int u, v;
boolean valid;
int myNode, mySize;
public Edge(int u, int v) {
this.u = u;
this.v = v;
valid = true;
}
int other(int x) {
ret... |
Baby Badawy's first words were "AND 0 SUM BIG", so he decided to solve the following problem. Given two integers n and k, count the number of arrays of length n such that:
* all its elements are integers between 0 and 2^k-1 (inclusive);
* the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of a... | #include<bits/stdc++.h>
using namespace std;
#define ll long long int
const ll mod = 1e9 + 7;
#define inf 1e18 + 3
#define pb push_back
#define mp make_pair
void solve() {
int n, k;
cin >> n >> k;
ll ans = 1;
while (k > 0) {
ans = (ans * n) % mod;
k--;
}
cout << ans << '\n';
}
signed main() {
#ifndef ONLINE... |
You are given an array a_1, a_2, ..., a_n consisting of n distinct integers. Count the number of pairs of indices (i, j) such that i < j and a_i ⋅ a_j = i + j.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t cases follow.
The first line of each test case contains one int... | #include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define maxn 200005
#define inf 1e9
#define maxi LONG_LONG_MAX
#define mini LONG_LONG_MIN
#define sz(x) (x).size()
#define ed(x) (x).end()
#define contains(v,i) (v.find(i)!=v.end())
#define grt_sort(x) sort(x.begin(),x.... |
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.
As Petya is older, he wants to take the chores with complexity larger... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, x, y;
cin >> n >> x >> y;
long a[2000];
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
cout << a[y] - a[y - 1];
return 0;
}
|
PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.
AlgoRace is a special league of car r... | #include <bits/stdc++.h>
using namespace std;
using namespace std;
int g[70][70][70];
int dp[70][70][70];
void solve() {
int n, m, r;
scanf("%d%d%d", &n, &m, &r);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
scanf("%d", &g[i][j][k]);
}
}
... |
Vasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located... | #include <bits/stdc++.h>
const int INF = 0x3f3f3f3f;
const long long int INFLL = 0x3f3f3f3f3f3f3f3fll;
long long int getint() {
long long int ret = 0;
bool f = 0;
char c;
while ((c = getchar()) < '0' || c > '9')
if (c == '-') f ^= 1;
while (c >= '0' && c <= '9') {
ret = ret * 10 + c - '0';
c = get... |
You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X".
Using the play sequence you can calculate the... | #include <bits/stdc++.h>
using namespace std;
const double eps = 1e-5;
const int inf = (1 << 31) - 1;
const int hinf = 1000000000;
const int mod = 1000000007;
int main() {
double e = 1;
int n;
cin >> n;
double p;
double ans = 0;
for (int i = 1; i <= n; i++) {
scanf("%lf", &p);
ans += e * p;
e = ... |
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters.
Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (... | #include <bits/stdc++.h>
using namespace std;
int N, P;
int A[50];
long long dp[52][52][52][52];
double C[52][52];
double fac[52], res;
int main() {
scanf("%d", &N);
for (int(i) = 0; (i) < (N); (i)++) scanf("%d", &A[i]);
scanf("%d", &P);
C[0][0] = 1;
for (int(i) = (1); (i) < (52); (i)++)
for (int(j) = 0; ... |
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position s. Then he performs some (pos... | import java.util.*;
public class Main {
public static void main(String[] strings) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int s = scan.nextInt() - 1;
int t = scan.nextInt() - 1;
int[] p = new int[n];
for (int i = 0; i < p.length; ++i) {
p[i] = scan.nextInt() - 1... |
The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that a... | #include <bits/stdc++.h>
using namespace std;
int main() {
struct date {
int d, m, y;
date(){};
date(int D, int M, int Y) {
d = D;
m = M;
y = Y;
if (m > 12 || d > 31 ||
(d == 31 && (m == 2 || m == 4 || m == 6 || m == 9 || m == 11)) ||
(d == 30 && m == 2) || (d =... |
Let's assume that p and q are strings of positive length, called the container and the key correspondingly, string q only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message s from the given container p:
i = 0;
j = 0;
s = <>;
while i is le... | #include <bits/stdc++.h>
using namespace std;
const int MAXS = 200;
const int MAXP = 1e6;
const int MAXK = 2000;
bool canTake[MAXS + 5][MAXK + 5][MAXS + 5];
char s[MAXS + 5], p[MAXP + 5];
int S, P, K;
bool best[MAXK + 5][MAXS + 5];
bool vis[MAXK + 5][MAXS + 5];
bool decision[MAXK + 5][MAXS + 5];
int ones;
bool solve(in... |
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.
Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, th... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 300050;
const int maxv = 1000050 * 2;
int n, k, a[maxn], mp[maxv], p[maxv];
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + c... |
You are a programmer and you have a New Year Tree (not the traditional fur tree, though) — a tree of four vertices: one vertex of degree three (has number 1), connected with three leaves (their numbers are from 2 to 4).
On the New Year, programmers usually have fun. You decided to have fun as well by adding vertices t... | #include <bits/stdc++.h>
using namespace std;
int n, m;
int dis_u, dis_v, dis;
int dep[1500005], dp[1500005][25];
void init() {
n = 4;
dep[1] = 1;
dep[2] = dep[3] = dep[4] = 2;
dp[2][0] = dp[3][0] = dp[4][0] = 1;
dis = 2;
dis_u = 2;
dis_v = 3;
}
void update(int u) {
for (int i = 1; i <= 20; i++) dp[u][i... |
A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times b... | n, v = map(int, input().split())
a = []
b = []
for i in range(n):
typ, carry = map(int, input().split())
if typ == 1:
a.append([carry, i + 1])
else:
b.append([carry, i + 1])
a.sort(reverse=True)
b.sort(reverse=True)
for i in range(1, len(a)):
a[i][0] += a[i - 1][0]
for i in range(1, min... |
Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a co... | import java.io.*;
import java.util.*;
public class ProblemE {
public static void main(String[] args) throws Exception {
ParserdoubtE in = new ParserdoubtE(System.in);
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
a = new int[n][... |
Berland amusement park shooting gallery is rightly acknowledged as one of the best in the world. Every day the country's best shooters master their skills there and the many visitors compete in clay pigeon shooting to win decent prizes. And the head of the park has recently decided to make an online version of the shoo... | #include <bits/stdc++.h>
using namespace std;
struct node {
int l, r, u, d, z, id;
} a[3001000];
int tr[3001000][2], cnt, pri[3001000], minn[3001000], x[3001000], y[3001000],
root[3001000], ex[3001000], excnt, size, i, n, m, ans[3001000],
anss[3001000];
pair<int, int> v[3001000];
bool cmp(node x, node y) { re... |
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of n playing cards. Let's describe the house they want to make:
1. The house consists of some non-zero number of floors.
2. Each ... | import java.io.*;
import java.util.*;
public class P3 {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
PrintStream op = System.out;
int count = 0;
long n = sc.nextLong();
int a = 0, b = 0;
switch ((int)(n % 3)) {
case 0: {
a = 15; b = 42;
break;
}
case 1: {
... |
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from... | #include <bits/stdc++.h>
char s[100010], t[100010];
int next[100010], occ[100010], n = 0, lens, lent;
long long f[100010], g[100010];
int main() {
scanf("%s%s", s, t), lens = strlen(s), lent = strlen(t);
next[0] = next[1] = 0;
for (int i = 1, j; i < lent; i++) {
j = next[i];
while (j && t[i] != t[j]) j = ... |
In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.
A string is a bHTML table, if it satisfies the grammar:
TABLE ::= <table>ROWS</table>
ROWS ::= ROW | ROW ROWS
ROW ::= <tr>CELLS</tr>
... | #include <bits/stdc++.h>
using namespace std;
int n, ans, a[10000], cnt, _prev[10000], cur;
string s;
bool comp(int st, string t) {
for (int i = 0; i < (int)t.length(); i++)
if (s[st + i] != t[i]) return false;
return true;
}
void inc() {
int i = cur;
while (i) {
a[i]++;
i = _prev[i];
}
a[0]++;
... |
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On each turn a fi... | #include <bits/stdc++.h>
using namespace std;
int main() {
long long n, x;
cin >> n;
long long k1, k2;
vector<long long> v1, v2, v3, v4;
cin >> k1;
for (int i = 0; i < k1; i++) {
cin >> x;
v1.push_back(x);
v3.push_back(x);
}
cin >> k2;
for (int i = 0; i < k2; i++) {
cin >> x;
v2.pu... |
'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form)
In the other words, CNF is a formula of type <image>, where & represents a logical "... | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
long long powmod(long long a, long long b) {
long long res = 1;
a %= mod;
for (; b; b >>= 1) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
}
return res;
}
int n, m, l, a;
int idx[400005][2];
vector<int> model;
vector<... |
Edo has got a collection of n refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be posit... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<pll> xs, ys;
for (int i = 0; i < n; ++i) {
ll a, b, c, d;
cin >> a >> b >> c >> d;
xs.emplace_back(a + c, i);
... |
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.
The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.
As input/output can reach huge... | a = input()
b = input()
if len(a)>len(b):
gap = len(a)-len(b)
new = ''
for _ in range(gap):
new+='0'
b = new + b
elif len(b)>len(a):
gap = len(b) - len(a)
new = ''
for _ in range(gap):
new+='0'
a = new + a
for i in range(0,len(a)):
if(a[i]>b[i]):
print('>')
... |
A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one o... | #include <bits/stdc++.h>
using namespace std;
map<int, int> a;
int b[200005];
int main() {
int n, x;
scanf("%d", &n);
int j = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &x);
if (x > 0) a[x] = j++;
}
int flag = 1, temp, k = 0;
scanf("%d", &x);
temp = (a[x] + 1) % j;
for (int i = 1; i < n; i++... |
Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm.
Formally, find the biggest integer d, such that all int... | a,b=map(int,input().split())
print(a) if a==b else print(1) |
Today Pari and Arya are playing a game called Remainders.
Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winnin... | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class D {
//private static Scanner in = new Scanner(System.in);
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)... |
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.
Input
The only line contains odd integer n (1 ≤ n ≤ 49).
Output
Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main di... | n = int(input())
if n==1:
print(1)
exit()
odd = 1
evn = 2
table = [[0 for i in range(n)] for i in range(n)]
#(x,y) x row, y col
for x in range(n):
for y in range(n):
x1 = min(x, n-1-x)
if y < (n - 1)/2-x1 or y > (n - 1)/2+x1: #even con
table[x][y] = evn
... |
Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes.
Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clo... | import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
public class C {
private static class Node {
... |
PolandBall has an undirected simple graph consisting of n vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white... | #include <bits/stdc++.h>
using namespace std;
const int N = 1017;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
if (k > 3) return cout << -1 << '\n', 0;
if (k == 1) return cout << -1 << '\n', 0;
if (k == 2 && n <= 4) return cout << -1 << '\n', 0;
if (k == 3 && n <= 3) r... |
Sherlock met Moriarty for a final battle of wits. He gave him a regular n sided convex polygon. In addition to it, he gave him certain diagonals to form regions on the polygon. It was guaranteed that the diagonals did not intersect in interior points.
He took each of the region and calculated its importance value. Imp... | #include <bits/stdc++.h>
using namespace std;
char buf[1 << 20], *p1, *p2;
template <class T>
inline void read(T &n) {
char ch =
(p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 20, stdin), p1 == p2)
? 0
: *p1++);
T w = 1, x = 0;
while (!isdigit(ch)) {
if (ch == '-') w = -1;
... |
You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1... | x = input()
y = input()
z = ''
for i in range(len(x)):
if x[i] < y[i]:
print("-1")
exit(0)
else:
z = z + y[i]
print(z)
|
Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren.
Okabe's city is represented by a 2D grid of cells. Rows are numbered from 1 to n from top to bottom, and columns are numbered 1 to m from left to right. Exactly k cells in the city are l... | #include <bits/stdc++.h>
using namespace std;
int inf;
int x[100100], y[100100], n, m, k, st, en;
int abss(int x) { return x > 0 ? x : -x; }
int dist(int a, int b) {
if (a == b) return 2;
if (x[a] == x[b] || y[a] == y[b])
return max(abss(x[a] - x[b]), abss(y[a] - y[b])) == 1 ? 0 : 1;
return min(abss(x[a] - x[... |
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win!
On the show a dog needs to eat as many bowls of dog food as poss... | #include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 200;
const long long inf = 2e18, mod = 1e9 + 7;
struct node {
int key, prior, cnt, sum;
node* l;
node* r;
node(int KEY = 0, int PRIOR = 0, int CNT = 1) {
key = KEY;
sum = cnt = CNT;
prior = PRIOR;
l = r = NULL;
}
};
typedef n... |
You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be p... | #include <bits/stdc++.h>
using namespace std;
template <class T>
inline void read(T &x) {
x = 0;
char c = getchar();
int f = 1;
while (!isdigit(c)) {
if (c == '-') f = -1;
c = getchar();
}
while (isdigit(c)) x = x * 10 - '0' + c, c = getchar();
x *= f;
}
const int N = 1e5 + 10;
int buc[N], L, R, a... |
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.
When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be... | #include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-9, PI = acos(-1.);
const int INF = 0x3f3f3f3f, MOD = 1e9 + 7;
const int N = 1e3 + 5, M = 1e6 + 5;
int n, a[N];
vector<int> v;
int main() {
scanf("%d", &n);
int ok = 1;
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
ok = ok && (a[i... |
You are given a tree T consisting of n vertices. A number is written on each vertex; the number written on vertex i is ai. Let's denote the function I(x, y) as the difference between maximum and minimum value of ai on a simple path connecting vertices x and y.
Your task is to calculate <image>.
Input
The first line ... | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MOD = (int)1e9 + 7;
const int MAXN = (int)1e6 + 5;
int n;
pair<int, int> a[MAXN];
vector<int> e[MAXN];
bool mark[MAXN];
ll solmax = 0, solmin = 0;
int sz[MAXN], p[MAXN];
int root(int u) {
while (p[u] != u) u = p[p[u]];
return u;
}
int siz... |
You are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times).
There are three types of queries you ... | #include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
template <typename _T>
inline void read(_T &f) {
f = 0;
_T fu = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') fu = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
f = (f << 3) + ... |
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. ... | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, A, B, C, T;
cin >> n >> A >> B >> C >> T;
long long int sum = 0;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
if (C >= B)
sum += 0LL + (C - B) * (T - t) + A;
else
sum += A + 0LL;
}
cout << sum << endl;
return 0... |
After passing a test, Vasya got himself a box of n candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya choos... | def ok(n, k):
a, n0 = 0, n
while n > 0:
if n <= k:
n, a = 0, a+n
break
n, a = n-k, a+k
n -= n / 10
#print k, a
return 2*a >= n0
n = int(raw_input())
lo, hi = 1, n
while lo <= hi:
mid = (lo+hi)>>1
if ok(n, mid): hi = mid-1
else: lo = mid+1
hi = max(1,hi)
if ok(n,hi):
print hi
else:
print hi+1
|
Archith was a making noise in digital logic class.Sir was very frustrated by the behaviour of Archith. Sir asked archith to meet him in staff room. As archith reached staff room sir gave a smile and asked to complete this assignment in one day if not he will be suspended. Archith has low attendence so he has to complet... | testcases = raw_input()
for i in range(int(testcases)):
decimal_number = raw_input()
if str(bin(int(decimal_number))[2 :]).count('1') % 2 == 0:
print "even"
else:
print "odd" |
Chang loves solving mathematical puzzles. One day he was solving a puzzle. According to the problem statement of the puzzle: "there are N integers. you are asked to delete some numbers such that the series obtained after deletion follows the condition.
(condition/equation): a - 3b ≤ 0 where a is the maximum and b is t... | # your code goes here
N=input()
a=[]
hash=[0]*10005
a=map(int,raw_input().split())
for i in a:
hash[i]+=1
sum=0
for i in range(0,10005):
sum+=hash[i]
hash[i]=sum
a.sort()
ans=1000000
for i in range(1,a[N-1]):
if(3*i<10004):
ans=min(ans,N-(hash[3*i]-hash[i-1]))
print ans |
Rakesh is very good in divisibility. He can easily tell the number is divisible by the given number or not. To make him work harder his teacher changed the question slightly. He will give the number and the other number with which the first number is divisible or not to make it complicated he will mention the range in ... | for _ in range(int(raw_input())):
li=[]
m=raw_input()
div=int(raw_input())
x,y=map(int,raw_input().split())
x-=1
y-=1
m=m[x:y+1]
#print(m)
for i in range(y-x+1):
for j in range(i+1,y-x+2):
if int(m[i:j])%div==0:
li.append(m[i:j])
print(len(li)) |
HackerEarth has sponsored a lot of goodies for the 'Google Week' to be held at Sir MVIT. The goodies are in the form of boxes. Each box has a surprise value associated with it.
To carry the boxes from his hostel to the venue, Karan puts the box with the smaller surprise value inside the box with larger surprise value.... | '''
Easy Goodies
'''
def fun_wid_code():
tc=int(raw_input())
while(tc):
num=[0]*10001
n=int(raw_input())
while(n):
k=int(raw_input())
num[k]+=1
n-=1
num.sort()
num.reverse()
print num[0]
tc-=1
fun_wid_code() |
Little Fajlu and Laal Baadshah are extremely good, and passionate Age of Empires 2 players. They're crazy about the game, and the passion they display for the game, if displayed for their semester exams - will make them top the university, even. But well, that's them.
Laal Baadshah relies on rushing through the game, ... | def defeat_power(food,gold,s,p,c,tp):
sam = 0
temp = -1
res = -1
while sam*100 <= food:
pal = 0
while ((pal*125 + 100*sam) <= food) and (pal*50<=gold):
food_left = (food-100*sam - 125*pal)
gold_left = (gold-50*pal)
cha = min(food_left/50,gold_left/100... |
The evil mastermind, Moriarty, strikes again! He sent Sherlock an image of a wall, with N integers painted on it. Sherlock is asked to solve the puzzle and find the next clue.
Sherlock knows that Moriarty is a deceitful person. All the numbers painted on the wall are not valid. Only the numbers that are Coprime with t... | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def gcd(a,b) :
if b == 0 :
return a
else :
return gcd(b,a%b)
t = int(raw_input())
while t>0 :
t -= 1
n,m = map(int, raw_input().split())
s = []
c=0
ip1=map(int, raw_input... |
Let there be a set of size N.
Power set of a set S, denoted by P(S) is the set of all subsets of S, including the empty set and the S itself.
Set A is said to be subset of set B if all elements of A are contained in B. Empty set is always a subset of any non-empty set. Similarly any set is subset of itself.
Set A i... | t = int(raw_input())
m = 10**9 + 7
for i in range(t):
n = int( raw_input() )
print ( pow( 4 , n , m ) % m - pow( 2 , n , m ) % m ) % m |
A notice on the notice board read:
“Is there an end to it?
While the number remains greater than one, if 2 divides the number completely, divide the number by 2; while the number remains greater than 1, if the number is not divisible by 2 , multiply the successor of the number by 3 and increment this by three. "
Dav... | import math
n = input()
if n>=1:
t = math.log(n)/math.log(2)
if n==int(n):
print "Yes"
else:
print "No"
else:
print "No" |
Given a number N, find the sum of all products x*y such that N/x = y (Integer Division).
Since, the sum can be very large, please output this modulo 1000000007.
Input Format:
The first line of input file contains an integer T, the number of test cases to follow.
Each of the next T lines contain an integer N.
Output ... | from math import sqrt
t = int(raw_input())
def summ(x):
return x*(x+1)/2
for i in range(t):
n = int(raw_input())
ans = 0
sq = int(sqrt(n))
for i in range(1,sq+1):
r = n//i
l = n//(i+1)
ans += i*r
if(l >= sq):
ans += i*(summ(r)-summ(l))
ans %= 1000000007
print ans |
Hansa loves dancing and so do her friends. But she has some pretty weird friends. Like this one friend of hers, Jack, jumps forward while dancing. The dance floor is of finite length (L) and there are many people dancing on it. During each song, Jack jumps exactly X steps forward and at the end of the song, he is pushe... | n, a, b= map(int, raw_input().split())
# calculate days_nights for n-b distance travelling
# adjust it
print (n-b)/(a-b) + (1 if (n-b)%(a-b) else 0) |
AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to sched... | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
imp... |
We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.
Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:
* For every pair of vertices (i, j), if the distance betw... | #include <bits/stdc++.h>
using namespace std;
int N;
vector<vector<int>> graph(222222);
vector<int> color(222222,-1);
vector<int> ans(222222,0);
void DFS(int f,int t){
if(f==-1)color[t]=0;
for(auto x:graph[t]){
if(color[x]==-1){
color[x]=(color[t]+1)%2;
DFS(t,x);
}
}
}
int main(){
cin >> N;
for(int i=... |
There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N.
Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each roo... | #include<bits/stdc++.h>
using namespace std;
double ans=999999999;
double inf=999999999;
int n,m;
double dp[601];
vector<int>e[601];
void get_dp(int x)
{
memset(dp,0,sizeof(dp));
dp[n]=0;
for(int i=n-1;i>=1;i--)
{
int tot=0;
double mx=0;
for(int j=0;j<e[i].size();j++)
tot++,mx=max(mx,dp[e[i][j]]),dp[i]+=dp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.