contest_id
stringlengths 1
4
| index
stringclasses 43
values | title
stringlengths 2
63
| statement
stringlengths 51
4.24k
| tutorial
stringlengths 19
20.4k
| tags
listlengths 0
11
| rating
int64 800
3.5k
⌀ | code
stringlengths 46
29.6k
⌀ |
|---|---|---|---|---|---|---|---|
468
|
A
|
24 Game
|
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of $n$ integers: $1, 2, ..., n$. In a single step, you can pick two of them, let's denote them $a$ and $b$, erase them from the sequence, and append to the sequence either $a + b$, or $a - b$, or $a × b$.
After $n - 1$ steps there is only one number left. Can you make this number equal to $24$?
|
Solution 1: If $n \le 3$, it's easy to find that it's impossible to make $24$, because the maximal number they can form is $9$. If $n > 5$, we can simply add $n - (n - 1) = 1, 24 * 1 = 24$ at the end of the solution to the number $n - 2$. So we can find the solution of $4, 5$ by hand. $1 * 2 * 3 * 4 = 24, (5 - 3) * 4 * (2 + 1) = 24$ Solution 2: We can find the pattern like that $n + (n + 3) - (n + 1) - (n + 2) = 0$, and find the solution of $4, 5, 6, 7$ by hand or brute forces. Solution 3: A knapsack-like solution.
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,500
|
// Author: Ruchiose
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#define i64 long long
#define d64 long double
#define fortodo(i, f, t) for (i = f; i <= t; i++)
using namespace std;
bool posi[100010];
int main()
{
int N;
scanf("%d", &N);
switch (N)
{
case 1:
case 2:
case 3:
puts("NO\n");
break;
case 4:
printf("YES\n1 * 2 = 2\n2 * 3 = 6\n4 * 6 = 24\n");
break;
case 5:
printf("YES\n2 * 4 = 8\n3 * 5 = 15\n1 + 8 = 9\n9 + 15 = 24\n");
break;
case 6:
printf("YES\n1 * 2 = 2\n2 * 3 = 6\n4 * 6 = 24\n6 - 5 = 1\n24 * 1 = 24\n");
break;
default:{
printf("YES\n");
i64 Tn = (N + 1ll) * N / 2;
if (Tn & 1)
{
printf("%d - %d = 1\n1 * 1 = 1\n", N, N - 1);
N -= 2;
Tn -= N * 2 + 3;
}
i64 Positive = (Tn + 24) / 2;
vector<int> VI;
VI.clear();
VI.push_back(1);
while ((VI.back() + 1LL) * (VI.back() + 2LL) / 2 <= Positive)
VI.push_back(VI.back() + 1);
int q = VI.back(), i;
i64 rest = Positive - (q * (q + 1LL) / 2);
fortodo(i, 1, rest) VI[q - i]++;
fortodo(i, 1, N) posi[i] = false;
fortodo(i, 0, q - 1) posi[VI[i]] = true;
i64 ths = VI[0];
fortodo(i, 1, q - 1)
{
printf("%I64d + %d = %I64d\n", ths, VI[i], ths + VI[i]);
ths += VI[i];
}
fortodo(i, 1, N)
if (!posi[i])
{
printf("%I64d - %d = %I64d\n", ths, i, ths - i);
ths -= i;
}
}
break;
};
}
|
468
|
B
|
Two Sets
|
Little X has $n$ distinct integers: $p_{1}, p_{2}, ..., p_{n}$. He wants to divide all of them into two sets $A$ and $B$. The following two conditions must be satisfied:
- If number $x$ belongs to set $A$, then number $a - x$ must also belong to set $A$.
- If number $x$ belongs to set $B$, then number $b - x$ must also belong to set $B$.
Help Little X divide the numbers into two sets or determine that it's impossible.
|
Solution 1: If we have number $x$ and $a - x$, they should be in the same set. If $x\in A$, it's obvious that $a-x\in A$. The contraposition of it is $a-x\not\in A\Rightarrow x\not\in A$, that means if $x\in B$, $a - x$ should in the set $B$. Same as the number $x, b - x$. So we can use Disjoint Set Union to merge the number that should be in the same set. If $a - x$ doesn't exist, $x$ can not be in the set $A$. If $b - x$ doesn't exist, $b$ can not be in the set $B$. Then check if there are any conflicts among numbers which should be in the same set. There are many other solutions to solve this problem based on the fact that $x, a - x, b - x$ should be in the same set, like greedy, BFS and 2-SAT. Solution 2: If $a = b$, it's easy to find the solution. We regards every number as a node. Every number $x$ links to number $a - x$ and number $b - x$. The degree of every node is at most $2$. So this graph consists of a lot of chains and cycles, and some node may have self loop. We only need to check if the lengths of all the chains are even or the chain ends with a self loop.
|
[
"2-sat",
"dfs and similar",
"dsu",
"graph matchings",
"greedy"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
const int N=101000;
map<int,int> hs;
int vis[N],way[N],A[N],B[N],p[N];
int n,a,b;
bool check0() {
rep(i,0,n) if (!hs.count(a-p[i])) return 0;
return 1;
}
void dfs(int u,int p,int s) {
vis[u]=1;
way[u]=s;
if (p==0) {
if (A[u]==u) throw 1;
if (A[u]==-1) throw s;
dfs(A[u],p^1,s);
} else {
if (B[u]==u) throw 1;
if (B[u]==-1) throw s^1;
dfs(B[u],p^1,s);
}
}
bool check1() {
rep(i,0,n) if (!vis[i]) {
if (A[i]==i||B[i]==i) continue;
if (((A[i]==-1)^(B[i]==-1))==0) continue;
try {
dfs(i,A[i]==-1,A[i]==-1);
} catch(int e) {
if (e==0) return 0;
}
}
rep(i,0,n) if (!vis[i]) {
if (A[i]==i) vis[i]=1,way[i]=0;
else if (B[i]==i) vis[i]=1,way[i]=1;
}
rep(i,0,n) if (!vis[i]) return 0;
return 1;
}
int main() {
scanf("%d%d%d",&n,&a,&b);
rep(i,0,n) scanf("%d",p+i),hs[p[i]]=i;
if (a==b) {
if (check0()) {
puts("YES");
rep(i,0,n) {
putchar('0');
if (i!=n-1) putchar(' ');
}puts("");
} else puts("NO");
} else {
rep(i,0,n) {
if (hs.count(a-p[i])) A[i]=hs[a-p[i]]; else A[i]=-1;
if (hs.count(b-p[i])) B[i]=hs[b-p[i]]; else B[i]=-1;
}
if (check1()) {
puts("YES");
rep(i,0,n) {
putchar(way[i]+'0');
if (i!=n-1) putchar(' ');
}
puts("");
} else puts("NO");
}
}
|
468
|
C
|
Hack it!
|
Little X has met the following problem recently.
Let's define $f(x)$ as the sum of digits in decimal representation of number $x$ (for example, $f(1234) = 1 + 2 + 3 + 4$). You are to calculate $\sum_{i=1}^{r}f(i)\,\bmod\,a.$
Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code:
\begin{verbatim}
ans = solve(l, r) % a;
if (ans <= 0)
ans += a;
\end{verbatim}
This code will fail only on the test with $\sum_{i=l}^{r}f(i)\equiv0{\mathrm{~(mod~}}a)$. You are given number $a$, help Little X to find a proper test for hack.
|
Define $g(x)=\sum_{i=0}^{x-1}f(i)$. $\sum_{i=l}^{r}f(i)=g(r+1)-g(l)$, so we should find a pair of number $a, b$ that $g(a)\equiv g(b)(\mathrm{mod}\ a)$ Solution 1: First we choose $x$ randomly. Then we can use binary search to find the minimal $d$ that $g(x+d)-g(x)\geq a-g(x)\;\mathrm{mod}\;a$ . So $g(x+d){\mathrm{~mod~}}a$ is very small, between $0$ and $9*\lceil\log_{10}(x+d)\rceil$. If $x+d\in[0,10^{l e n})$, after choosing $x$ atmost $9 * len + 2$ times, we can definitely find a pair that $g(a)\equiv g(b)(\mathrm{mod}\ a)$ Solution 2: We can use binary search to find the minimal $d$ that $g(d) \ge a, g(d) \ge 2a, ...$ This solution is similar to the first one. Solution 3: We can use binary search to find the minimal $d$ that $g(d) \ge a$. And we use two pointers to maintain an interval $[l, r]$ that $\textstyle\sum_{i=l}^{r}f(i)\geq a$ until we find $\textstyle\sum_{i=l}^{r}f(i)=a$. I can't prove the correctness of this algorithm, but it performs well in practice. Solution 4: Thanks ZhouYuChen for his talented idea. If $x < 10^{18}$, we can get $f(10^{18} + x) = f(x) + 1$. That means if we shift the interval $[x + 1, x + 10^{18}]$ by $1$, the result will be increase by $1$ too. And it also not hard to find that $g(10^{x}) = 45 * x * 10^{x - 1}$. So if $g(10^{18})\equiv x({\mathrm{mod}}\ a)$, $[a - x, a - x + 10^{18} - 1]$ is the answer. It's easy to see that upper bound of the answer is $a$, because of pigeonhole principle (among $g(0), g(1), ..., g(a)$ at least two are equal). So big integer is not required in this problem. If solution 3 is correct, the upper bound of the answer can be $2 * 10^{16}$.
|
[
"binary search",
"constructive algorithms",
"math"
] | 2,500
|
m = int(input())
x,t=10**100-1,m-100*45*10**99%m
print(t,t+x)
|
468
|
D
|
Tree
|
Little X has a tree consisting of $n$ nodes (they are numbered from $1$ to $n$). Each edge of the tree has a positive length. Let's define the distance between two nodes $v$ and $u$ (we'll denote it $d(v, u)$) as the sum of the lengths of edges in the shortest path between $v$ and $u$.
A permutation $p$ is a sequence of $n$ distinct integers $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$. Little X wants to find a permutation $p$ such that sum $\sum_{i=1}^{n}d(i,p_{i})$ is maximal possible. If there are multiple optimal permutations, he wants to find the lexicographically smallest one. Help him with the task!
|
$d(u, v) = dep_{u} + dep_{v} - 2 * dep_{LCA(u, v)}$, so the answer is: $\textstyle{\sum_{i=1}^{n}d e p_{i}+d e p_{p_{i}}-2*d e p_{L C A(i,p_{i})}=2*\sum_{i=1}^{n}d e p_{i}-2*\sum_{i=1}^{n}d e p_{L C A(i,p_{i})}}$ $dep_{i}$ there means the distance between node $i$ and root. We choose centroid of tree as root (let's denote it $u$), so we can make every pair $(i, p_{i})$ are in different subtrees, that means $dep_{LCA(i, pi)} = 0$. So the answer is $\sum_{i=1}^{n}2*d(i,u)$. The next part of this problem is find the lexicographically smallest solution. We regards it as finding the lexicographically smallest matching in a bipartite graph. For a subtree, if the amount of nodes in this subtree in the left part > the amount of nodes not in this subtree in the right part, the perfect matching doesn't exist. So the amount of nodes in this subtree in the left part + the amount of nodes in this subtree in the right part should be no more than the amount of nodes unmatched, while the root is an exception. We can use a segment tree to maintain it easily. We determined the minimum possible $p_{i}$ from $1$ to $n$. If there is a subtree that the amount of nodes in this subtree in the left and right part is equal to the amount of nodes unmatched, we must select a node from it, so $p_{i}$ equal to the node in this subtree with the minimum id. Otherwise, we can choose a node with the minimum id that is not in the same subtree with $i$.
|
[
"graph matchings"
] | 3,100
|
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const ll mod=1000000007;
ll powmod(ll a,ll b) {ll res=1;a%=mod;for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
// head
const int N=101000;
int q[N],f[N],vis[N],sz[N],ms[N],brh[N];
int u,v,w,n,tot;
VI e[N],d[N];
long long ans;
set<int> ts[N];
int nd[N*4],l[N],r[N],spe[N],p[N];
VI must;
int find(int u) {
int t=1;q[0]=u;f[u]=-1;
rep(i,0,t) {
u=q[i];
rep(j,0,SZ(e[u])) {
int v=e[u][j];
if (!vis[v]&&v!=f[u]) f[q[t++]=v]=u;
}
ms[q[i]]=0;
sz[q[i]]=1;
}
for (int i=t-1;i>=0;i--) {
ms[q[i]]=max(ms[q[i]],t-sz[q[i]]);
if (ms[q[i]]*2<=t) return q[i];
sz[f[q[i]]]+=sz[q[i]];
ms[f[q[i]]]=max(ms[f[q[i]]],sz[q[i]]);
}
return 0;
}
void df(int u,int f,long long dep) {
ans+=dep;
rep(j,0,SZ(e[u])) {
int v=e[u][j];
if (v==f) continue;
df(v,u,dep+d[u][j]);
}
}
void dfs(int u,int f,int br) {
l[u]=++tot; brh[u]=br; sz[u]=1;
rep(i,0,SZ(e[u])) {
int v=e[u][i];
if (v==f) continue;
dfs(v,u,br);
sz[u]+=sz[v];
}
r[u]=tot;
}
void modify(int p,int l,int r,int x,int v) {
if (l==r) nd[p]=v;
else {
int md=(l+r)>>1;
if (x<=md) modify(p+p,l,md,x,v);
else modify(p+p+1,md+1,r,x,v);
nd[p]=min(nd[p+p],nd[p+p+1]);
}
}
int query(int p,int l,int r,int tl,int tr) {
if (l==tl&&r==tr) return nd[p];
else {
int md=(l+r)>>1;
if (tr<=md) return query(p+p,l,md,tl,tr);
else if (tl>md) return query(p+p+1,md+1,r,tl,tr);
else return min(query(p+p,l,md,tl,md),query(p+p+1,md+1,r,md+1,tr));
}
}
int query(int u,int k) {
if (k==0) {
if (r[u]==n) return query(1,1,n,1,l[u]-1);
else return min(query(1,1,n,1,l[u]-1),query(1,1,n,r[u]+1,n));
} else return query(1,1,n,l[u],r[u]);
}
int main() {
scanf("%d",&n);
rep(i,1,n) {
scanf("%d%d%d",&u,&v,&w);
e[u].pb(v); e[v].pb(u);
d[u].pb(w); d[v].pb(w);
}
u=find(1);
df(u,0,0);
printf("%I64d\n",ans*2);
l[u]=++tot;
rep(i,0,SZ(e[u])) {
v=e[u][i];
dfs(v,u,v);
sz[v]*=2;
ts[sz[v]].insert(v);
}
r[u]=1; brh[u]=u; spe[u]=1;
rep(i,1,n+1) modify(1,1,n,l[i],i);
rep(i,1,n+1) {
must.clear();
for (set<int>::iterator it=ts[n+1-i].begin();it!=ts[n+1-i].end();it++)
must.pb(*it);
if (SZ(must)==2) p[i]=query(must[brh[i]==must[0]],1);
else if (SZ(must)==1) {
if (brh[i]==must[0]) p[i]=query(brh[i],0);
else p[i]=query(must[0],1);
} else {
if (spe[i]) p[i]=nd[1];
else p[i]=query(brh[i],0);
}
modify(1,1,n,l[p[i]],1<<30);
u=brh[i],v=brh[p[i]];
if (!spe[u]) ts[sz[u]].erase(u),ts[--sz[u]].insert(u);
if (!spe[v]) ts[sz[v]].erase(v),ts[--sz[v]].insert(v);
}
rep(i,1,n+1) printf("%d%c",p[i],(i==n)?'\n':' ');
}
|
468
|
E
|
Permanent
|
Little X has solved the #P-complete problem in polynomial time recently. So he gives this task to you.
There is a special $n × n$ matrix $A$, you should calculate its permanent modulo $1000000007 (10^{9} + 7)$. The special property of matrix $A$ is almost all its elements equal to $1$. Only $k$ elements have specified value.
You can find the definition of permanent at the link: https://en.wikipedia.org/wiki/Permanent
|
The permanent can be obtained as follows: for each $(e_{1}, e_{2}, ..., e_{t})$ such that $x_{1}, x_{e2}..., x_{et}$ are distinct and $y_{e1}, y_{e2}, ..., y_{et}$ are distinct, add $(n-t)!\prod_{i=1}^{t}(w_{e_{i}}-1)$ to the answer. It can be proved by the formula : ${\mathrm{perm}}(A+B)=\sum_{s,t}{\mathrm{perm}}(a_{i j})_{i\in s,j\in t}{\mathrm{perm}}(b_{i j})_{i\in\bar{s},j\in t}$, where $s$ and $t$ are subsets of the same size of ${1, 2, ..., n}$ and $\scriptstyle{\vec{s}}$, $\overline{{t}}$ are their respective complements in that set. Construct a undirected graph $G$ with $2n$ vertices $v_{1}, v_{2}, ..., v_{2n}$, where the edge weight between vertex $v_{i}, v_{n + j}$ is $A_{i, j} - 1$. We only need to know the sum of weight of all matchings that we choose $t$ edges. The weight of matching is the product of all edge weights in the matching. We only need to know the sum of the weights that we choose $x$ edges in the each connected components. The number of nodes in a connected component is $s$ and the number of edges in this connected component is $t$. Algorithm 1: Because it's a bipartite graph, so the number of vertices in one part is at most $s / 2$. So we can use state compressed dp to calculate the ways to choose $x$ edges in this connected component. The complexity is $O(2^{s / 2} * s^{2})$. Algorithm 2: We can choose a spanning tree. The number of edges in spanning tree of these vertices is $s - 1$, and the number of non-tree edges is $t - s + 1$. So we can enumerate all the non-tree edge, use tree dp to calculate the ways. The complexity is $O(2^{t - s} * s^{2})$. Combined with these two algorithm, the complexity is $O(min(2^{s / 2}, 2^{k - s}) * s^{2})) = O(2^{k / 3} * k^{2})$.
|
[
"dp",
"graph matchings",
"math",
"meet-in-the-middle"
] | 3,100
| null |
469
|
A
|
I Wanna Be the Guy
|
There is a game called "I Wanna Be the Guy", consisting of $n$ levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only $p$ levels of the game. And Little Y can pass only $q$ levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
|
The problem itself is easy. Just check if all the levels could be passed by Little X or Little Y.
|
[
"greedy",
"implementation"
] | 800
|
R=lambda:map(int,raw_input().split())[1:]
print ["Oh, my keyboard!","I become the guy."][input()==len(set(R()).union(set(R())))]
|
469
|
B
|
Chat Online
|
Little X and Little Z are good friends. They always chat online. But both of them have schedules.
Little Z has fixed schedule. He always online at any moment of time between $a_{1}$ and $b_{1}$, between $a_{2}$ and $b_{2}$, ..., between $a_{p}$ and $b_{p}$ (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time $0$, he will be online at any moment of time between $c_{1}$ and $d_{1}$, between $c_{2}$ and $d_{2}$, ..., between $c_{q}$ and $d_{q}$ (all borders inclusive). But if he gets up at time $t$, these segments will be shifted by $t$. They become $[c_{i} + t, d_{i} + t]$ (for all $i$).
If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between $l$ and $r$ (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment $[l, r]$ suit for that?
|
This problem is not hard. Just iterator over all possible $t$, and check if the schedule of Little X and Little Z will overlap.
|
[
"implementation"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
const int N=110;
int p,q,l,r,ans,tl,tr;
int pool[10000],pa[10000],pb[10000],*vis=pool+5000,*a=pa+5000,*b=pb+5000;
int main() {
scanf("%d%d%d%d",&p,&q,&l,&r);
rep(i,0,p) {
scanf("%d%d",&tl,&tr);
rep(j,tl,tr) a[j]=1;
}
rep(i,0,q) {
scanf("%d%d",&tl,&tr);
rep(j,tl,tr) b[j]=1;
}
rep(i,0,1001) rep(j,0,1001) if (a[i]&&b[j]) vis[i-j]=vis[i-j-1]=1;
rep(k,l,r+1) ans+=vis[k]|vis[k-1];
printf("%d\n",ans);
}
|
471
|
A
|
MUH and Sticks
|
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
- Four sticks represent the animal's legs, these sticks should have the same length.
- Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.
Your task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.
|
Given six sticks and their lengths we need to decide whether we can make an elephant or a bear using those sticks. The only common requirement for both animals is that four leg-sticks should have same length. This means that the answer "Alien" should be given only if we can't find four sticks for the legs. Otherwise we will be able to make some animal. The type of the animal will depend on the relation of the remaining sticks' lengths. If they are equal then it will an elephant, if they are different we will have a bear. So this algorithm should solve the problem: Find the number which appears at least four times in the input. If no such number exist then the answer is "Alien". Otherwise remove four entries of that number from the input. After removing that number you will have two numbers left, compare them and decide whether it's an elephant or a bear. One shortcut for this problem might be to sort the input array, then if it's a bear or an elephant then 3rd and 4th elements in the sorted should be animal's legs. So you can assume that one of these numbers is the length of the leg and count how many times you see this number in the input. Since the numbers in the input are very small you can implement 'brute force' solution as well. By brute force solution in this case I mean that you can actually check all possible values for leg-length, head-length and body-length. If in total they give the same set as the input then you found a matching, all you need is to check whether it's a bear or an elephant. And it's an alien if you checked all possible combinations and found nothing matching to the input. Though in this case the brute force solution is not easier than another one. It seems that there were two common mistakes people were making in this problem: Not taking into account that legs can be of the same length as body or head. So you can't just count the number of distinct numbers in the input to decide which type of animal is that. We assumed that people might make such a mistake, there was a relevant warning in the statement. Trying to sort the input and then check whether some elements in this array are equal to other elements and based on this comparison decide which type of animal is that. People were simply making mistakes when deciding which elements to compare. The correct way to implement this is: This solution seems to be shorter but there are many failed solutions like this because people were not paying enough attention to the details. So I would prefer implementing more straightforward approach. Hope you liked the pictures!
|
[
"implementation"
] | 1,100
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> l(6);
for (int i = 0 ; i < 6 ; i++) cin >> l[i];
sort(l.begin(), l.end());
if (l[0] == l[3]) cout << (l[4] == l[5] ? "Elephant" : "Bear");
else if (l[1] == l[4]) cout << "Bear";
else if (l[2] == l[5]) cout << (l[0] == l[1] ? "Elephant" : "Bear");
else cout << "Alien";
}
|
471
|
B
|
MUH and Important Things
|
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are $n$ tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the $n$ tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
|
You need to check whether exist three pairwise different permutations of the indices of the input which result in array being sorted. Generally you can count the number of total permutation which give non-decreasing array. This number might be very large and it might easily overflow even long integer type. And what is more important is that you don't actually need to count the exact number of such permutations. Let's tackle this problem from another angle. Assume you already sorted the input array and you have the corresponding permutation of indices. This already gives you one array for the result, you only need to find two more. Let's look for any pair of equal numbers in the input array, if we swap them then we will get another valid permutation. And if we find one more pair of equal numbers then swapping them you can get third permutation and that will be the answer. You need to keep in mind here that one of the indices when swapping the second time might be the same as one of the numbers in the first swap, that's ok as soon as second index is different. So all you need to do is to find two pairs of indices which point to the equal elements. The entire algorithm is as follows: Transform the input array into array of pairs (tuples), first element of the pair will be the number given in the input array, the second element will be the index of that number. Sort that array of pairs by the first element of the pairs. Then the second elements will give you one correct permutation. Scan this array in order to find possible swaps. You just iterate over this array and check if the first element in the current pair equals to the first element of the previous pair. If it equals you remember the indices of these two pairs. You stop scanning the array as soon as you have two swaps. Then you check how many swaps you have, if you have less than two swaps then there are no three distinct permutations. Otherwise you have two swaps which means that you have an answer. So you print the current permutation, then you execute the first swap (you just swap those two elements you remembered in the first swap), then you print the permutation array received after executing that swap. And you execute the second swap and print the permutation array third time.
|
[
"implementation",
"sortings"
] | 1,300
|
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
void print(vector<pair<int, int> > &v) {
for (int i = 0 ; i < v.size() ; i++) cout << v[i].second << ' ';
cout << endl;
}
int main() {
int n;
cin >> n;
vector<pair<int, int> > input;
for (int i = 0 ; i < n ; i++) {
int x;
cin >> x;
input.push_back(make_pair(x, i + 1));
}
sort(input.begin(), input.end());
vector<pair<int, int> > swaps;
for (int i = 1 ; i < n && swaps.size() < 2 ; i++) {
if (input[i - 1].first == input[i].first) {
swaps.push_back(make_pair(i - 1, i));
}
}
if (swaps.size() < 2) {
cout << "NO";
return 0;
}
cout << "YES" << endl;
print(input);
swap(input[swaps[0].first], input[swaps[0].second]);
print(input);
swap(input[swaps[1].first], input[swaps[1].second]);
print(input);
}
|
471
|
C
|
MUH and House of Cards
|
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:
- The house consists of some non-zero number of floors.
- Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card.
- Each floor besides for the lowest one should contain less rooms than the floor below.
Please note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more.
While bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of $n$ cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using \textbf{exactly} $n$ cards.
|
Card house. This problem required some maths, but just a little bit. So in order to start here let's first observe that the number of cards you need to use for a complete floor with $R$ rooms equals to: $C = C_{rooms} + C_{ceiling} = 2 \cdot R + (R - 1) = 3 \cdot R - 1$ Then if you have $F$ floors with $R_{i}$ rooms on the $i$-th floor then the total number of cards would be: $N=\sum_{i=1}^{F}C_{i}=\sum_{i=1}^{F}(3\cdot R_{i}-1)=3\cdot\sum_{i=1}^{F}R_{i}-F=3\cdot R-F$ where $R$ is the total number of the rooms in the card house. This already gives you an important property - if you divide $N + F$ on 3 then the remainder of this division should be 0. This means that if you have found some minimum value of floors somehow and you found maximum possible number of floors in the house, then within that interval only every third number will be a part of the solution, the rest of the numbers will give a non-zero remainder in the equation above. Now let's think what is the highest house we can build using $N$ cards. In order to build the highest possible house obviously you need to put as few cards on each floor as you can. But we have a restriction that every floor should have less rooms than the floor below. This gives us the following strategy to maximize the height of the house: we put 1 room on the top floor, then 2 rooms on the floor below, then 3 rooms on the next floor, etc. In total then the number of cards we will need equals to: $N_{m i n}=\{{\boldsymbol{3}}\cdot{\boldsymbol{R}}-{\boldsymbol{F}}={\boldsymbol{\sqrt{\cdot}}}\sum_{x=1}^{F}{\boldsymbol{x}}-{\boldsymbol{F}}={\boldsymbol{9}}\cdot{\boldsymbol{F}}\cdot\left({\boldsymbol{F+1}}\right)/2-{\boldsymbol{F}}$ This is minimum number of cards we need in order to build a house with $F$ floors. This gives us a way to calculate the maximum height of the house we can build using $N$ cards, we just need to find maximum $F$ which gives $N_{min} < = N$. Mathematicians would probably solve the quadratic inequation, programmers have two options: Check all possible $F$ until you hit that upper bound. Since $N_{min}$ grows quadratically with $F$ then you will need to check only up to $\sqrt{N}$ numbers. This gives $O({\sqrt{N}})$ time complexity and fits nicely in the given time limit. The second approach would be a binary search. Using binary search to find maximum number of the floors would give you $O(logN)$ time complexity. This was the intended originally solution but it was decided to lower the constraints in order to allow sqrt solutions as well. Now that you know the maximum number of the floors in the house you might need to correct it a bit because of that remainder thing we discussed above, this might make your maximum height one or two floors lower. Looking again at the remainder discussion on top we can see that starting from here only every third number will be valid for an answer. Now you can either count them brutally (back to $O({\sqrt{N}})$ solution) or you can simply calculate them using this formulae: $ans = (F_{max} + 3 - 1) / 3$ (integer division) That seems to be it, just don't forget to use longs all the time in this problem.
|
[
"binary search",
"brute force",
"greedy",
"math"
] | 1,700
|
#include "assert.h"
#include <iostream>
typedef long long int LL;
using namespace std;
LL getNumberOfCardsInFullHouse(LL floors) {
return 3 * floors * (floors + 1) / 2 - floors;
}
LL solve(LL n) {
LL res = 0;
for (LL floors = 1 ; getNumberOfCardsInFullHouse(floors) <= n ; floors++)
if ((n + floors) % 3 == 0)
res++;
return res;
}
int main() {
LL n; cin >> n;
cout << solve(n);
}
|
471
|
D
|
MUH and Cube Walls
|
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of $w$ towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of $n$ towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of $w$ contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
|
In this problem we are given two arrays of integers and we need to find how many times we can see second array as a subarray in the first array if we can add some arbitrary constant value to every element of the second array. Let's call these arrays $a$ and $b$. As many people noticed or knew in advance this problem can be solved easily if we introduce difference arrays like that: $aDiff_{i} = a_{i} - a_{i + 1}$ (for every $i = = 0..n - 1$) If we do that with both input arrays we will receive two arrays both of which have one element less than original arrays. Then with these arrays the problem simply becomes the word search problem (though with possibly huge alphabet). This can be solved using your favourite string data structure or algorithm. Originally it was intended to look for linear solution but then we made time limit higher in case if somebody will decide to send $O(NlogN)$ solution. I haven't seen such solutions (that is understandable) but some people tried to squeeze in a quadratic solution. Linear solution can be made using Z-function or KMP algorithm. In order to add a logarithmic factor you can exercise with suffix array for example. I had suffix array solution as well, but it's a lot messier than linear solution. There is one corner case you need to consider - when Horace's wall contains only one tower, then it matches bears' wall in every tower so the answer is $n$. Though for some algorithms it might not even be a corner case if you assume that empty string matches everywhere. Another error which several people did was to use actual string data structures to solve this problem, so they converted the differences to chars. This doesn't work since char can't hold the entire range an integer type can hold. I didn't think that switching to difference arrays will be that obvious or well-known, so I didn't expect that this problem will be solved by that many people.
|
[
"string suffix structures",
"strings"
] | 1,800
|
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int IntMinVal = (int) -1e20;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
/// compacts the array of arbitrary numbers into an array of [0 .. K - 1] numbers where K is the number of distinct numbers in the original array.
/// the items in the resulting array are guaranteed to give the same comparison result as the items in the original array on the same positions
/// Complexity - O(N logN)
vector<int> compactArray(vector<int>& v) {
vector<int> inputNumbers = v;
sort(inputNumbers.begin(), inputNumbers.end());
inputNumbers.resize(unique(inputNumbers.begin(), inputNumbers.end()) - inputNumbers.begin());
map<int, int> mapping;
for (int i = 0 ; i < inputNumbers.size() ; i++)
mapping[inputNumbers[i]] = i;
vector<int> result(v.size());
for (int i = 0 ; i < v.size() ; i++)
result[i] = mapping[v[i]];
return result;
}
// algorithm is mostly taken from e-maxx "as is", only arrays were changed to vectors
vector<int> calcSuffixArray(vector<int> s) {
s = compactArray(s); // reduce the numbers in the input array since the complexity of the algorithm below depends on alphabet size
int n = s.size();
int alphabet = n;
vector<int> p(n);
vector<int> cnt(n);
vector<int> c(n);
for (int i=0; i < n; ++i)
++cnt[s[i]];
for (int i=1; i<alphabet; ++i)
cnt[i] += cnt[i-1];
for (int i=0; i<n; ++i)
p[--cnt[s[i]]] = i;
c[p[0]] = 0;
int classes = 1;
for (int i=1; i<n; ++i) {
if (s[p[i]] != s[p[i-1]]) ++classes;
c[p[i]] = classes-1;
}
vector<int> pn(n);
vector<int> cn(n);
for (int h=0; (1<<h)<n; ++h) {
for (int i=0; i<n; ++i) {
pn[i] = p[i] - (1<<h);
if (pn[i] < 0) pn[i] += n;
}
cnt.assign(classes, 0);
for (int i=0; i<n; ++i)
++cnt[c[pn[i]]];
for (int i=1; i<classes; ++i)
cnt[i] += cnt[i-1];
for (int i=n-1; i>=0; --i)
p[--cnt[c[pn[i]]]] = pn[i];
cn[p[0]] = 0;
classes = 1;
for (int i=1; i<n; ++i) {
int mid1 = (p[i] + (1<<h)) % n, mid2 = (p[i-1] + (1<<h)) % n;
if (c[p[i]] != c[p[i-1]] || c[mid1] != c[mid2])
++classes;
cn[p[i]] = classes-1;
}
c = cn;
}
return p;
}
vector<int> v1;
/// compares the subarray of array v1 starting at index i1 with array v2
bool comp(int i1, vector<int> v2) {
int len1 = v1.size() - i1;
int len2 = v2.size();
int len = min(len1, len2);
for (int i = 0 ; i < len ; i++)
if (v1[i1 + i] != v2[i]) {
return v1[i1 + i] < v2[i];
}
if (len1 != len2) return len1 < len2;
return false;
}
int findNumberOfOccurences(vector<int> v, vector<int> &pattern) {
if (pattern.size() == 0) return v.size() + 1;
v.push_back(IntMinVal);
vector<int> suffixArray = calcSuffixArray(v);
v1 = v;
vector<int>::iterator it1 = lower_bound(suffixArray.begin(), suffixArray.end(), pattern, comp);
pattern.back()++;
vector<int>::iterator it2 = lower_bound(suffixArray.begin(), suffixArray.end(), pattern, comp);
return it2 - it1;
}
vector<int> toDiffArray(vector<int> &v) {
vector<int> result;
for (int i = 1 ; i < v.size() ; i++)
result.push_back(v[i] - v[i - 1]);
return result;
}
int main() {
ios_base::sync_with_stdio(false);
int n; cin >> n;
int m; cin >> m;
vector<int> a = readVector<int>(n);
vector<int> b = readVector<int>(m);
vector<int> aDiff = toDiffArray(a);
vector<int> bDiff = toDiffArray(b);
int result = findNumberOfOccurences(aDiff, bDiff);
cout << result;
}
|
471
|
E
|
MUH and Lots and Lots of Segments
|
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of $n$ segments. Each segment was either horizontal or vertical. Now the friends want to simplify the draft by deleting some segments or parts of segments so that the final masterpiece meets three conditions:
- Horace wants to be able to paint the whole picture in one stroke: by putting the brush on the paper and never taking it off until the picture is ready. The brush can paint the same place multiple times. That's why all the remaining segments must form a single connected shape.
- Menshykov wants the resulting shape to be simple. He defines a simple shape as a shape that doesn't contain any cycles.
- Initially all the segment on the draft have integer startpoint and endpoint coordinates. Uslada doesn't like real coordinates and she wants this condition to be fulfilled after all the changes.
As in other parts the draft is already beautiful, the friends decided to delete such parts of the draft that the sum of lengths of the remaining segments is as large as possible. Your task is to count this maximum sum of the lengths that remain after all the extra segments are removed.
|
Given a set of horizontal/vertical lines you need to erase some parts of the lines or some lines completely in order to receive single connected drawing with no cycles. First of all let's go through naive $N^{2}$ solution which won't even remove cycles. In order to solve this problem you will need a DSU data structure, you put all your lines there and then for every pair of horizontal and vertical line you check if they intersect and if they do you join them in DSU. Also your DSU should hold the sum of the lengths of the joined lines. Initially it should be equal to the line lengths. Since there might be up to $N^{2} / 4$ intersections between lines we receive a quadratic solution. Now let's get rid of cycles. Having the previous solution we can do it pretty easily, all we need is to change the way we were connecting the sets in DSU if some lines intersect. Previously we were simply asking DSU to join them even if they already belong to the same set. Now what we will do is when finding some pair of lines which intersects and is already joined in DSU instead of asking DSU to join them again we will ask DSU to decrement their length sum. In terms of the problem it is equivalent to erasing a unit piece of segment in the place where these two lines intersect and this will break the cycle. With this change we already have a correct solution which is too slow to pass the time limits. Now we need to make our solution work faster. We still might have up to $N^{2} / 4$ intersections so obviously if we want to have a faster solution we can't afford to process intersections one by one, we need to process them in batches. All our lines are horizontal and vertical only, so let's do a sweep line, this should make our life easier. Let's assume that we're sweeping the lines from the left to the right. Obviously then the code where the intersections will be handled is the code where we process the vertical line. Let's look at this case closer. We can assume that we're going to add some vertical line on with coordinates $(x, y1, x, y2)$, we can also assume that there are some horizontal lines which go through the given $x$ coordinate, we track this set of lines while sweeping left to right. So we're going to add a vertical line and let's say that it has $n$ intersections with horizontal line. Previously we were handling each intersection separately, but you can see that if some horizontal lines already belong to the same set in DSU and they go next to each other then we don't need to handle them one by one anymore. They already belong to the set in DSU so there is no need to join them, we might only need to count the number of them between $y1$ and $y2$ coordinates, but that can be calculated in logarithmic time. So the trick to get rid of quadratic time complexity is to avoid storing horizontal lines one by one and store instead an interval (across y coordinate) of horizontal lines which belong to the same set in DSU. I will call these intervals chunks. You will need to manipulate these chunks in logarithmic time and you will need to locate them by y coordinate so you need to store them in a treap or a STL map for example with $y$ coordinate serving as a key. To be clear let's see what data each of these chunks will hold: struct chunk{ int top, bottom; // two coordinates which describe the interval covered by the chunk int id; // id of this chunk in DSU. Several chunks might have the same id here if they belong to the same set in DSU }; And we agreed that data structure which holds these chunks can manipulate them in logarithmic time. Let's now get into details to see how exactly it works. While sweeping we will have one of three possible events (listed in the order we need to handle them): new horizontal line starting, vertical line added, horizontal line finishing. First and third operation only update our chunks data structure while the second operation uses it and actually joins the sets. Let's look into each of these operations: horizontal line start. We need to add one more chunk which will consist of a single point. The only additional operation we might need to do happens when this new line goes through some chunk whose interval already covers this point. In this case we need to split this covering chunk into two parts - top and bottom one. It's a constant number of updates/insertions/removals in our chunk data structure and we agreed that each of these operations can be done in logarithmic time so the time complexity of a single operation of this time is $O(logN)$. It should be also mentioned here that during processing a single operation of this type we might add at most two new blocks. Since in total we have no more than $N$ operations of this type them it means that in total we will have no more than $2 \cdot N$ blocks created. This is important for the further analysis. vertical line. In this operation we need to find all chunks affected by this vertical line and join them. Each join of two chunks takes logarithmic time and we might have up to $n$ chunks present there, so we might need up $O(NlogN)$ time to draw a single vertical line. This doesn't give us a good estimate. But we can see that we have only two ways to get new chunks - they are either added in the step 1 because it's a new line or one chunk is being split into two when we add a line in between. But we have an upper bound on total number of the chunks in our structure as shown above. Ans since we have such an upper bound then we can say that it doesn't matter how many chunks will join a single vertical line because in total all vertical lines will not join more than $2 \cdot N$ chunks. So we have an amortized time complexity analysis here, in total all vertical line operations will take $O(NlogN)$ time. There are some other details we need to handle here. For example we need to avoid cycles correctly. This margin is too narrow to contain the proof but the formulae to correct the length sum is like this: $d = y2 - y1 - (N_{intersections} - 1) + N_{distinctsets} - 1$ where $d$ - the number you need to add to the sum of the lengths in DSU $N_{intersections}$ - number of horizontal lines intersecting with the given vertical line, I used a separate segment tree to get this value in $O(logN)$ $N_{distinctsets}$ - number of distinct sets in DSU joined by this vertical line, you need to count them while joining So this gives you a way to correct the lengths sums. There is one more thing that needs to be mentioned here - it might happen that your vertical line will be contained by some chunk but will not intersect any horizontal lines in it. In this case you simply ignore this vertical line as if it doesn't overlap any chunk at all. horizontal line end. Finally we came here and it seems to be simple. When some horizontal line ends we might need to update our chunks. There are three cases here: a. This line is the only line in the chunks - we simply delete the chunk then. b. This line lays on some end of the interval covered by the chunk - we update that end. In order to update it we need to know the next present horizontal line or the previous present horizontal line. I used the same segment tree mentioned above to handle these queries. c. This line lays inside some chunk - we don't need to update that chunk at all. And that's it! In total it gives $O(NlogN)$ solution.
|
[
"data structures",
"dsu"
] | 2,700
|
#include <algorithm>
#include "assert.h"
#include <deque>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <vector>
typedef long long LL;
#define all(v) v.begin(),v.end()
int IntMaxVal = (int) 1e20;
int IntMinVal = (int) -1e20;
#define FOR(i, a, b) for(int i = a; i < b ; ++i)
#define FORD(i, a, b) for(int i = a; i >= b; --i)
template<typename T> inline void maximize(T &a, T b) { a = std::max(a, b); }
using namespace std;
class {
vector<int> parent;
vector<int> size;
vector<LL> perimeter;
public:
void init(int n) {
parent.resize(n);
for (int i = 0 ; i < n ; i++) parent[i] = i;
size.assign(n, 1);
perimeter.resize(n);
}
int get(int v) {
if (v == parent[v]) return v;
return parent[v] = get(parent[v]);
}
int join(int a, int b) {
a = get(a);
b = get(b);
if (a == b) return a;
if (size[a] < size[b]) swap(a, b);
size[a] += size[b];
perimeter[a] += perimeter[b];
parent[b] = a;
return a;
}
void add_perimeter(int v, LL addition) {
v = get(v);
perimeter[v] += addition;
}
LL get_perimeter(int v) {
v = get(v);
return perimeter[v];
}
} dsu;
struct list_element {
int top;
int bottom;
int id;
list_element(int y, int id) {
top = bottom = y;
this->id = id;
}
};
struct {
int gp2(int n) {
int x = 2;
while (x < n) x *= 2;
return x;
}
int n;
vector<int> points_count;
vector<int> leftmost;
vector<int> rightmost;
vector<int> leftmost_set_element;
vector<int> rightmost_set_element;
void init(vector<int> points) {
sort(all(points));
points.resize(unique(all(points)) - points.begin());
n = gp2(points.size());
points_count.resize(2 * n);
leftmost.assign(2 * n, IntMaxVal);
rightmost.assign(2 * n, IntMaxVal);
FOR (i, 0, points.size()) leftmost[n + i] = rightmost[n + i] = points[i];
FORD (i, n - 1, 1) leftmost[i] = leftmost[2 * i];
FORD (i, n - 1, 1) rightmost[i] = rightmost[2 * i + 1];
leftmost_set_element.assign(2 * n, IntMaxVal);
rightmost_set_element.assign(2 * n, IntMinVal);
}
void update(int key, int val) {
int ptr = 1;
while (ptr < n) {
ptr *= 2;
if (leftmost[ptr + 1] <= key) ptr++;
}
points_count[ptr] = val;
leftmost_set_element[ptr] = val ? leftmost[ptr] : IntMaxVal;
rightmost_set_element[ptr] = val ? leftmost[ptr] : IntMinVal;
ptr /= 2;
while (ptr) {
points_count[ptr] = points_count[2 * ptr] + points_count[2 * ptr + 1];
leftmost_set_element[ptr] = min(leftmost_set_element[2 * ptr] , leftmost_set_element[2 * ptr + 1]);
rightmost_set_element[ptr] = max(rightmost_set_element[2 * ptr] , rightmost_set_element[2 * ptr + 1]);
ptr /= 2;
}
}
void add(int y) {
update(y, 1);
}
void remove(int y) {
update(y, 0);
}
/// returns number of lines between y1 and y2 (both including);
int count(int y1, int y2, int i = 1) {
if (leftmost[i] >= y1 && rightmost[i] <= y2) return points_count[i];
if (leftmost[i] > y2 || rightmost[i] < y1) return 0;
return count(y1, y2, 2 * i) + count(y1, y2, 2 * i + 1);
}
int get_first_after(int y, int ptr = 1) {
if (leftmost[ptr] > y) return leftmost_set_element[ptr];
if (rightmost[ptr] <= y) return IntMaxVal;
return min(get_first_after(y, 2 * ptr),
get_first_after(y, 2 * ptr + 1));
}
int get_last_before(int y, int ptr = 1) {
if (rightmost[ptr] < y) return rightmost_set_element[ptr];
if (leftmost[ptr] >= y) return IntMinVal;
return max(get_last_before(y, 2 * ptr),
get_last_before(y, 2 * ptr + 1));
}
} current_horizontal_lines;
struct {
map<int, list_element*> elements;
list_element* find_first(int y) {
map<int, list_element*>::iterator it = elements.lower_bound(y);
if (it == elements.end()) return NULL;
return it->second;
}
void insert(list_element* newElement) {
elements[newElement->top] = newElement;
}
// splits an element into two parts (below the given Y and above it)
void split(list_element* element, int y) {
assert(element->bottom < y);
assert(element->top > y);
int bottom = element->bottom;
element->bottom = current_horizontal_lines.get_first_after(y);
list_element* bottom_part = new list_element(bottom, element->id);
bottom_part->top = current_horizontal_lines.get_last_before(y);
insert(bottom_part);
}
void remove(list_element* element) {
elements.erase(element->top);
}
void debug_print() {
cout << "List contents : " << endl;
map<int, list_element*>::iterator ptr = elements.begin();
while (ptr != elements.end()) {
cout << "( " << ptr->second->bottom << " , " << ptr->second->top << " ) " << endl;
ptr++;
}
}
} linked_list;
struct vertical_line {
int x, y1, y2, id;
};
struct horizontal_line_point {
int x, y, id;
};
void start_horizontal_line(horizontal_line_point &point) {
list_element* first_after = linked_list.find_first(point.y);
list_element* newElement = new list_element(point.y, point.id);
current_horizontal_lines.add(point.y);
if (first_after != NULL && first_after->bottom < point.y) {
linked_list.split(first_after, point.y);
}
linked_list.insert(newElement);
}
void sweep_vertical(vertical_line &line) {
list_element* firstAfter = linked_list.find_first(line.y1);
if (firstAfter == NULL || firstAfter->bottom > line.y2 || current_horizontal_lines.count(line.y1, line.y2) == 0) return;
int different_line_sets = 0;
while (true) {
list_element* next_element = linked_list.find_first(firstAfter->top + 1);
if (next_element == NULL || next_element->bottom > line.y2) break;
if (dsu.get(firstAfter->id) != dsu.get(next_element->id)) {
next_element->id = dsu.join(firstAfter->id, next_element->id);
different_line_sets++;
}
next_element->bottom = firstAfter->bottom;
linked_list.remove(firstAfter);
firstAfter = next_element;
}
dsu.join(firstAfter->id , line.id);
int perimeter_add = 0;
perimeter_add -= current_horizontal_lines.count(line.y1 , line.y2) - 1;
perimeter_add += different_line_sets;
dsu.add_perimeter(firstAfter->id, perimeter_add);
}
void end_horizontal_line(horizontal_line_point &point) {
current_horizontal_lines.remove(point.y);
list_element* element = linked_list.find_first(point.y);
assert(element != NULL);
assert(element->bottom <= point.y);
if (element->bottom == element->top) {
linked_list.remove(element);
} else if (element->bottom == point.y) {
element->bottom = current_horizontal_lines.get_first_after(point.y);
} else if (element->top == point.y) {
linked_list.remove(element);
element->top = current_horizontal_lines.get_last_before(point.y);
linked_list.insert(element);
}
}
template <typename T> bool leftToRight(const T &x, const T &y) {
return x.x < y.x;
}
int main() {
ios_base::sync_with_stdio(false);
deque<vertical_line> vertical_lines;
deque<horizontal_line_point> horizontal_line_starts;
deque<horizontal_line_point> horizontal_line_ends;
int n; cin >> n;
dsu.init(n);
vector<int> horizontal_line_ys;
FOR (i, 0, n) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
if (x1 == x2) {
vertical_line line = { x1, min(y1, y2), max(y1, y2) , i };
vertical_lines.push_back( line );
} else {
horizontal_line_point start = { min(x1, x2) , y1 , i };
horizontal_line_point end = { max(x1, x2) , y1 , i };
horizontal_line_starts.push_back(start);
horizontal_line_ends.push_back(end);
horizontal_line_ys.push_back(y1);
}
dsu.add_perimeter(i, x2 - x1 + y2 - y1);
}
sort(all(vertical_lines), leftToRight<vertical_line>);
sort(all(horizontal_line_starts), leftToRight<horizontal_line_point>);
sort(all(horizontal_line_ends), leftToRight<horizontal_line_point>);
vertical_line vLine_stub = { IntMaxVal , 0 , 0 };
horizontal_line_point hPoint_stub = { IntMaxVal , 0 , 0 };
vertical_lines.push_back(vLine_stub);
horizontal_line_starts.push_back(hPoint_stub);
horizontal_line_ends.push_back(hPoint_stub);
current_horizontal_lines.init(horizontal_line_ys);
while (vertical_lines.size() > 1 || horizontal_line_starts.size() > 1 || horizontal_line_ends.size() > 1) {
int minX = min(vertical_lines.front().x,
min(horizontal_line_starts.front().x,
horizontal_line_ends.front().x));
if (horizontal_line_starts.front().x == minX) {
start_horizontal_line(horizontal_line_starts.front());
horizontal_line_starts.pop_front();
} else if (vertical_lines.front().x == minX) {
sweep_vertical(vertical_lines.front());
vertical_lines.pop_front();
} else {
end_horizontal_line(horizontal_line_ends.front());
horizontal_line_ends.pop_front();
}
}
LL result = 0;
FOR (i, 0, n) maximize(result, dsu.get_perimeter(i));
cout << result;
}
|
472
|
A
|
Design Tutorial: Learn from Math
|
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.
You are given an integer $n$ no less than 12, express it as a sum of two composite numbers.
|
One way to solve this is by bruteforce: there are O(n) different ways to decomose n as sum of two number. If we can check if a number is a prime in O(1) then the whole algorithm can run in O(n). You can use Sieve of Eratosthenes to do the pre-calculation. And another way is try to prove this theorem. The prove is simple: if n is odd number, then 9 and (n-9) is an answer (n-9 is an even number at least 4, so a composite number), and if n is even number, then 8 and (n-8) is an answer (n-8 is an even number at least 4, also must be a composite number).
|
[
"math",
"number theory"
] | 800
| null |
472
|
B
|
Design Tutorial: Learn from Life
|
One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.
Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have $n$ people standing on the first floor, the $i$-th person wants to go to the $f_{i}$-th floor. Unfortunately, there is only one elevator and its capacity equal to $k$ (that is at most $k$ people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs $|a - b|$ seconds to move from the $a$-th floor to the $b$-th floor (we don't count the time the people need to get on and off the elevator).
What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?
|
This task can be solve by greedy: the k people with highest floor goes together, and next k people with highest floor goes together and so on. So the answer is 2 * ((f[n]-1) + (f[n-k]-1) + (f[n-2k]-1) + ...) . It is a bit tricky to prove the correctness of greedy, since people can get off the elevator and take it again. We can give a lower bound of the answer by flow analysis: between floor i and floor i+1, there must be no more than (# of f[i] >= i+1) / k times the elevator goes up between these 2 floors, and then there be same number of times goes down. We can find this lower bound matches the answer by above greedy algorithm, so it means the greedy algorithm gives an optimal answer.
|
[] | 1,300
| null |
472
|
C
|
Design Tutorial: Make It Nondeterministic
|
A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.
Let's try to make a new task. Firstly we will use the following task. There are $n$ people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are $n$ people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation $p$?
More formally, if we denote the handle of the $i$-th person as $h_{i}$, then the following condition must hold: $\forall\ i,j\ (i<\j)\cdot\ h_{p_{i}}<h_{p_{i}}$.
|
This one laso can be solved by greedy, let's think in this way: let pick one with smallest handle, then we let him/her use min(firstName, secondName) as handle. And go for the next one (2nd mallest handle), now he/she must choose a handle greater than handle of previous person, and if both meet this requirement, he/she can pick a small one. This time the correctness of this greedy solution can be proved by exchange argument. Note that if we change the goal of this problem: ask number of different permutations they can get, then it will be very hard. (I tried it for hours but can't solve.)
|
[
"greedy"
] | 1,400
| null |
472
|
D
|
Design Tutorial: Inverse the Problem
|
There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.
Now let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an $n × n$ distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).
|
Let's think it in the following way: for the minimal length edge, it must belong the the tree, ..., for the k-th minimal length edge(a, b), if there is already an path between a-b, then it can not be an edge of tree anymore, otherwise it must be edge of tree, why? Because otherwise there must be a path from a to b in the tree, that means a and b can be connected by edges with less length, but a and b is not connected. So this Kruskal style analysis gives us this theorem: if there is an answer, then the answer must be the MST of that graph. (You can also guess this theorem and try to prove it.) You can solve MST in O(n^2 log n), and then there are many way to check distance between notes on tree: you can just simply do dfs or bfs from each node, it can run in O(n^2). Or if you have pre-coded LCA algorithm, it can run in O(n^2 log n).
|
[
"dfs and similar",
"dsu",
"shortest paths",
"trees"
] | 1,900
| null |
472
|
E
|
Design Tutorial: Learn from a Game
|
One way to create task is to learn from game. You should pick a game and focus on part of the mechanic of that game, then it might be a good task.
Let's have a try. Puzzle and Dragon was a popular game in Japan, we focus on the puzzle part of that game, it is a tile-matching puzzle.
\begin{center}
(Picture from Wikipedia page: http://en.wikipedia.org/wiki/Puzzle_&_Dragons)
\end{center}
There is an $n × m$ board which consists of orbs. During the game you can do the following move. In the beginning of move you touch a cell of the board, then you can move your finger to one of the adjacent cells (a cell not on the boundary has 8 adjacent cells), then you can move your finger from the current cell to one of the adjacent cells one more time, and so on. Each time you move your finger from a cell to another cell, the orbs in these cells swap with each other. In other words whatever move you make, the orb in the cell you are touching never changes.
The goal is to achieve such kind of pattern that the orbs will be cancelled and your monster will attack the enemy, but we don't care about these details. Instead, we will give you the initial board as an input and the target board as an output. Your goal is to determine whether there is a way to reach the target in a single move.
|
First let's solve some special cases: If the initial board and the target board contains different orbs, then there can't be a solution. If n = 1 (or m = 1), then we can try all O(m^2) (or O(n^2)) possible moves. And for the other cases, there always have solution. We first hold the orb with number target[1][1] in initial board. Then we want to move other orbs to their position. So let's come up with a process to move orb from (a, b) to (c, d): it must be some continue path from (a, b) to (c, d), so we want to build a single move: it will move an orb from (a, b) to an adjacent cell (c, d). How to do that? We can move our touching orb to (c, d) first, and then move to (a, b). But there are some concerns: in this move, the touching orb shouldn't pass any already-done cells, and it shouldn't pass (a, b) when we get to (c, d). That means we need a good order to move orbs. We can do it in this way: first, as long as there are more than 2 rows, we move the orbs to last row (from left to right or right to left). And then it must be 2xm boards: we do it column by column from right to left. We can find that in this order, there always exist paths for our touching orb to get (c, d).
|
[
"constructive algorithms",
"implementation"
] | 2,800
| null |
472
|
F
|
Design Tutorial: Change the Goal
|
There are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal.
Let's have a try. I have created the following task for Topcoder SRM 557 Div1-Hard: you are given $n$ integers $x_{1}, x_{2}, ..., x_{n}$. You are allowed to perform the assignments (as many as you want) of the following form $x_{i}$ ^= $x_{j}$ (in the original task $i$ and $j$ must be different, but in this task we allow $i$ to equal $j$). The goal is to maximize the sum of all $x_{i}$.
Now we just change the goal. You are also given $n$ integers $y_{1}, y_{2}, ..., y_{n}$. You should make $x_{1}, x_{2}, ..., x_{n}$ exactly equal to $y_{1}, y_{2}, ..., y_{n}$. In other words, for each $i$ number $x_{i}$ should be equal to $y_{i}$.
|
You need to know some knowledge about linear algebra and notice the operation of xor on 32 bit integers equals to + operation in a 32 dimension linear space. If you don't know, you should learn it from the editorial of similar tasks, for example, Topcoder SRM 557 Div1-Hard. We need to know some basic properties of our operation: we can swap two number a and b by: a^=b, b^=a, a^=b. This operation is inversible, the inverse is itself. By property 1 we can do the Gaussian elimination of each set of vectors. By property 2 we can use this way to build an answer: use some operation to make A[] into a base (linear independent vectors that the span will be A[]), then transfer it into a base of B[], then use the inverse of Gaussian elimination to recover B[]. So now we have two bases: {a1, a2, ..., ax} and {b1, b2, ..., by}. If there exists some bi such that it can't be expressed as a linear combination of {a1, a2, ..., ax}, the solution can't exists. Otherwise there always exists a solution: first we build b1 and put it in the first position. Suppose b1 = a2 ^ a3 ^ a8, then we swap any of them, say, a2 into position one, and then xor it with a3 and a8, then we get b1. Note that after this operation {a1, a2, ..., ax} will remain a base. And we need to ensure we don't erase already-done numbers in a.
|
[
"constructive algorithms",
"math",
"matrices"
] | 2,700
| null |
472
|
G
|
Design Tutorial: Increase the Constraints
|
There is a simple way to create hard tasks: take one simple problem as the query, and try to find an algorithm that can solve it faster than bruteforce. This kind of tasks usually appears in OI contest, and usually involves data structures.
Let's try to create a task, for example, we take the "Hamming distance problem": for two binary strings $s$ and $t$ with the same length, the Hamming distance between them is the number of positions at which the corresponding symbols are different. For example, the Hamming distance between "\textbf{0}01\textbf{1}1" and "\textbf{1}01\textbf{0}1" is 2 (the different symbols are marked with bold).
We use the Hamming distance problem as a query in the following way: you are given two strings $a$ and $b$ and several queries. Each query will be: what is the Hamming distance between two strings $a_{p1}a_{p1 + 1}...a_{p1 + len - 1}$ and $b_{p2}b_{p2 + 1}...b_{p2 + len - 1}$?
Note, that in this problem the strings are \textbf{zero-based}, that is $s = s_{0}s_{1}... s_{|s| - 1}$.
|
Let's start with a simpler task: we have string A and B (|A|, |B| <= n), we have q queries and each query we ask the Hamming distance between A and a substring of B with length equals to |A|. How to solve this? We need to notice compute A with different offset of B is similar to the computation of convolution, so it can be done by FFT. We use +1 to replace '1' and we use -1 to replace '0', and then we do the convolution of A and reverse B. We can extract the answer of all possible query of "the Hamming distance between A and a substring of B with length equals to |A|."! Then let's come back to our problem, how to use this way to make a faster solution? We can use a way like sqrt decompose: we divide A into L blocks, for each block, we compute the convolution of this part with B, it will takes O(n*L*logn). And for each query, we can use the pre-calculated results to speedup (if a whole block contains in the query, we can compute it in O(1)). So each query needs no more than O(L) operation. If n = q then this solution can run in O((n*logn) ^ 1.5). But in practice it has some issues: for example, we can use bit operation to speedup like __builtin_popcount(). I tried to set constraints to fail solution with only bit optimization, but seems I failed: I apologies to allow this kind of solutions passed. (I used __builtin_popcount() to test such solution, but in fact cnt[x<<16] + cnt[x>>16] is much faster than the builtin fucnion)
|
[
"bitmasks",
"data structures",
"fft"
] | 2,800
| null |
474
|
A
|
Keyboard
|
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
\begin{verbatim}
qwertyuiop
asdfghjkl;
zxcvbnm,./
\end{verbatim}
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).
We have a sequence of characters he has typed and we want to find the original message.
|
This is an implementation problem, therefore most of the solution fit in the time limit. We can even save the keyboard in $3$ strings and make a brute force search for each character to find its position and then print the left/right neighbour.
|
[
"implementation"
] | 900
| null |
474
|
B
|
Worms
|
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole $n$ ordered piles of worms such that $i$-th pile contains $a_{i}$ worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers $1$ to $a_{1}$, worms in second pile are labeled with numbers $a_{1} + 1$ to $a_{1} + a_{2}$ and so on. See the example for a better understanding.
Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.
Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
|
There are two solutions: We can make partial sums ($sum_{i} = a_{1} + a_{2} + ... + a_{i}$) and then make a binary search for each query $q_{i}$ to find the result $j$ with the properties $sum_{j - 1} < q_{i}$ and $sum_{j} \ge q_{i}$. This solution has the complexity $O(n + m \cdot log(n))$ We can precalculate the index of the pile for each worm and then answer for each query in $O(1)$. This solution has the complexity $O(n + m)$
|
[
"binary search",
"implementation"
] | 1,200
| null |
474
|
C
|
Captain Marmot
|
Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has $n$ regiments, each consisting of $4$ moles.
Initially, each mole $i$ ($1 ≤ i ≤ 4n$) is placed at some position $(x_{i}, y_{i})$ in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments \textbf{compact}, if it's possible.
Each mole $i$ has a home placed at the position $(a_{i}, b_{i})$. Moving this mole one time means rotating his position point $(x_{i}, y_{i})$ $90$ degrees counter-clockwise around it's home point $(a_{i}, b_{i})$.
A regiment is \textbf{compact} only if the position points of the $4$ moles form a square with non-zero area.
Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.
|
For each $4$ points we want to see if we can rotate them with $90$ degrees such that we obtain a square. We can make a backtracking where we rotate each point $0, 1, 2$ or $3$ times and verify the figure obtained. If it's a square we update the minimal solution. Since we can rotate each point $0, 1, 2$ or $3$ times, for each regiment we have $4^{4}$ configurations to check. So the final complexity is about $O(n)$.
|
[
"brute force",
"geometry"
] | 2,000
| null |
474
|
D
|
Flowers
|
We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.
But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size $k$.
Now Marmot wonders in how many ways he can eat between $a$ and $b$ flowers. As the number of ways could be very large, print it modulo $1000000007$ ($10^{9} + 7$).
|
We can notate each string as a binary string, instead of red and white flowers. A string of this type is good only if every maximal contigous subsequence of "$0$" has the length divisible by $k$. We can make dynamic programming this way : $nr_{i}$ = the number of good strings of length $i$. If the $i$-th character is "$1$" then we can have any character before and if the $i$-th character is "$0$" we must have another $k - 1$ "$0$" characters before, so $nr_{i} = nr_{i - 1} + nr_{i - k}$ for $i \ge k$ and $nr_{i} = 1$ for $i < k$. Then we compute the partial sums ($sum_{i} = nr_{1} + nr_{2} + ... + nr_{i}$) and for each query the result will be $sum_{b} - sum_{a - 1}$. This solution has the complexity $O(maxVal + t)$, where $maxVal$ is the maximum value of $b_{i}$.
|
[
"dp"
] | 1,700
| null |
474
|
E
|
Pillars
|
Marmot found a row with $n$ pillars. The $i$-th pillar has the height of $h_{i}$ meters. Starting from one pillar $i_{1}$, Marmot wants to jump on the pillars $i_{2}$, ..., $i_{k}$. ($1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n$). From a pillar $i$ Marmot can jump on a pillar $j$ only if $i < j$ and $|h_{i} - h_{j}| ≥ d$, where $|x|$ is the absolute value of the number $x$.
Now Marmot is asking you find out a jump sequence with maximal length and print it.
|
We have to find a substring $i_{1}, i_{2}, ..., i_{k}$ such that $abs(h_{ij} - h_{ij + 1}) \ge D$ for $1 \le j < k$. Let's suppose that the values in $h$ are smaller. We can make dynamic programming this way : $best_{i}$ = the maximal length of such a substring ending in the $i$-th position, $best_{i} = max(best_{j}) + 1$ with $j < i$ and $h_{j} \ge D + h_{i}$ or $h_{j} \le h_{i} - D$. So we can easily search this maximum in a data structure, such as an segment tree or Fenwick tree. But those data structure must have the size of $O(maxH)$ which can be $10^{9}$. For our constraints we mantain the idea described above, but instead of going at some specific position in the data structure based on a value, we would normalize the values in $h$ and binary search the new index where we should go for an update or a query in the data structure. Therefore, the data structure will have the size $O(n)$. The complexity of this solution is $O(n \cdot log(n))$.
|
[
"binary search",
"data structures",
"dp",
"sortings",
"trees"
] | 2,000
| null |
474
|
F
|
Ant colony
|
Mole is hungry again. He found one ant colony, consisting of $n$ ants, ordered in a row. Each ant $i$ ($1 ≤ i ≤ n$) has a strength $s_{i}$.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$) and each pair of ants with indices between $l$ and $r$ (inclusively) will fight. When two ants $i$ and $j$ fight, ant $i$ gets one battle point only if $s_{i}$ divides $s_{j}$ (also, ant $j$ gets one battle point only if $s_{j}$ divides $s_{i}$).
After all fights have been finished, Mole makes the ranking. An ant $i$, with $v_{i}$ battle points obtained, is going to be freed only if $v_{i} = r - l$, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you $t$ segments $[l_{i}, r_{i}]$ and asks for each of them how many ants is he going to eat if those ants fight.
|
For each subsequence $[L, R]$ we must find how many queens we have. A value is "queen" only if is the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$). Also, we must notice that the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$) can be only the minimum value from ($s_{L}, s_{L + 1}, ..., s_{R}$). So for each query we search in a data structure (a segment tree or a RMQ) the minimum value and the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$) and if these two values are equal then we output the answer $R - L + 1 - nrValues$, where $nrValues$ is the number of values in the subsequence equal to the GCD and the minimum value. The complexity of this solution is $O(n \cdot log(n) \cdot log(valMax) + t \cdot log(n) \cdot log(valMax))$, where $valMax$ is the maximum value of $s_{i}$.
|
[
"data structures",
"math",
"number theory"
] | 2,100
| null |
475
|
A
|
Bayan Bus
|
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
The event coordinator has a list of $k$ participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one.
In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by $k$ participants. Your task is to draw the figure representing occupied seats.
|
As usual for A we have an implementation problem and the main question is how to implement it quickly in the easiest (thus less error-prone) way. During the contest I spent almost no time thinking about it and decided to implement quite straightforward approach - start with empty string and concatenate different symbols to the end of it. The result is quite messy and worst of all I forgot one of the main principles in the [commercial] programming - separate logic from its presentation. The "presentation" here is all these bus characters which are all the same across different inputs. So I paid my price, my original solution failed on system tests. Much better approach afterwards I looked up in Swistakk's solution - you copy&paste the "template" of the bus from the example test into your source code, then you just change the characters for each of 34 possible seats. Result becomes much cleaner - 8140120.
|
[
"implementation"
] | 1,100
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> result = {
"+------------------------+",
"|O.O.O.O.O.O.O.#.#.#.#.|D|)",
"|O.O.O.O.O.O.#.#.#.#.#.|.|",
"|O.......................|",
"|O.O.O.O.O.O.#.#.#.#.#.|.|)",
"+------------------------+"
};
int n; cin >> n;
for (int i = 1 ; i <= 34 ; i++) {
char c = i > n ? '#' : 'O';
int row = i <= 4 ? 0 : (i - 2) / 3;
int seat = i <= 4 ? i - 1 : (i - 5) % 3;
if (seat == 2 && row != 0) seat++;
result[1 + seat][1 + row * 2] = c;
}
for (auto s : result) cout << s << endl;
}
|
475
|
B
|
Strongly Connected City
|
Imagine a city with $n$ horizontal streets crossing $m$ vertical streets, forming an $(n - 1) × (m - 1)$ grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.
The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.
|
For B we already might need some kind of algorithm to solve it, though for the constraints given you might use almost any approach. If you just have a directed graph then in order to check whether you can reach all nodes from all other nodes you can do different things - you can dfs/bfs from all nodes, two dfs/bfs from the single node to check that every other node has both paths to and from that node, or you can employ different "min distance between all pairs of nodes" algorithm. All of these seem to work fine for this problem. But we shouldn't ignore here that the input graph has a special configuration - it's a grid of vertical and horizontal directed lines. For this graph all you need is to check whether four outer streets form a cycle or not. If they form a cycle then the answer is "YES", otherwise "NO". The good explanation why this works was already given by shato. And then the entire solution takes just 10 lines of code - 8140438.
|
[
"brute force",
"dfs and similar",
"graphs",
"implementation"
] | 1,400
|
#include <iostream>
#include <string>
using namespace std;
int main() {
int x; cin >> x >> x;
string s1; cin >> s1;
string s2; cin >> s2;
string s3 = { s1.front() , s1.back() , s2.front() , s2.back() };
cout << (s3 == "<>v^" || s3 == "><^v" ? "YES" : "NO");
}
|
475
|
C
|
Kamal-ol-molk's Painting
|
Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.
Consider the painting as a $n × m$ rectangular grid. At the beginning an $x × y$ rectangular brush is placed somewhere in the frame, with edges parallel to the frame, ($1 ≤ x ≤ n, 1 ≤ y ≤ m$). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment.
You have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush.
|
There are probably several completely different ways to solve this problem, I will describe only the one I implemented during the round. The start point for the solution is that there are three cases we need to cover: either first time we move the brush right or we move it down or we do not move it at all. Let's start with the last one. Since we're not moving the brush at all then it's obvious that altered cells on the painting form a rectangle. It can also be proven that the only case we need to consider here is the rectangle 1x1, that's the only rectangle which cannot be achieved by moving some smaller rectangle. So we need to count the number of altered cells, if it is equal to 1 then the answer is 1. Now we're left with two cases to consider, you start by moving right in the case and you move down in the second case. You can write some code to cover each of those cases, but you can also notice that they are symmetric in some sense. To be more clear, they are symmetric against the diagonal line which goes from (0, 0) point through (1, 1) point. If you have some code to solve "move down first" case, then you don't need to write almost completely the same code to solve "move right" case, you can simply mirror the image against that diagonal and invoke "move down" method again. Small trick which saves a lot of time and prevents copy-pasting of the code. Now let's try to solve this last case. Basically the approach I used can be shortly described like that: we start in the leftmost topmost altered cell, then we move down and that move already leaves us only one option what do in the next moves until the end, so we get the entire sequence of moves. As well as getting these moves we also get the only possible width and height of the brush, so we know everything, I was not very strict while moving the brush so at the end I also compared whether these moves and these sizes in fact give exactly the same image as we get in the input. That was the brief explanation of the "move down" method, now let's get into details. First of all since we move down immediately from the start point then there is only one value which can be valid for the brush width - it is the number of altered cells which go to the right from the start point. So we know one dimension. Now let's try moving the brush. Ok, first time as we said we move it down, what is next? Then you might have a choice whether you want to move right or to move down again. The answer is to move right first because your width is already fixed while height might be unknown still, so if you miss point to be altered in the left column of the brush and you move right, you might still have a chance to paint it if you take the correct height of the brush. But if you miss the point to the right of the current topmost brush row then you won't be able to cover it later, because your width was fixed on the first step. Here is a picture: Grayed out is the current position of the brush. So what I'm saying is that you should move to the right if the cell in the red area is painted, otherwise you will definitely miss it. So this simple thing gives you the entire idea on how to build the only possible sequence of moves. You also need to calculate some possible value for the brush height. It can be calculated just before moving right, in order not to miss any painted cells you need to extend you height of the brush to cover all the painted cells in the leftmost column of you current brush position (this was highlighted as green on the image above). Now you know all the information about the probable painting - you have both dimensions of the brush and you know how it was moving, as I said before all you need to do is to double check that these moves and these dimensions in fact give you the same painting you get. If it gives the same painting then the answer for this case is $width \cdot height$, otherwise there is no answer for this particular case. If you implement all of these steps carefully and you won't paint cells more than one time, then you will be able to achieve an $O(N \cdot M)$ complexity.
|
[
"brute force",
"constructive algorithms",
"greedy"
] | 2,100
| null |
475
|
D
|
CGCDSSQ
|
Given a sequence of integers $a_{1}, ..., a_{n}$ and $q$ queries $x_{1}, ..., x_{q}$ on it. For each query $x_{i}$ you have to count the number of pairs $(l, r)$ such that $1 ≤ l ≤ r ≤ n$ and $gcd(a_{l}, a_{l + 1}, ..., a_{r}) = x_{i}$.
$\operatorname{ecd}(v_{1},v_{2},\ldots,v_{n})$ is a greatest common divisor of $v_{1}, v_{2}, ..., v_{n}$, that is equal to a largest positive integer that divides all $v_{i}$.
|
It seems that all the solutions for this problem based on the same observation. Let's introduce two number sequences: $a_{0}, a_{1}, ..., a_{n}$ and $x_{0} = a_{0}, x_{i} = gcd(x_{i - 1}, a_{i})$. Then the observation is that the number of distinct values in $x$ sequence is no more than $1 + log_{2}a_{0}$. It can be proven by taking into account that $x$ is non-increasing sequence and value for greatest common divisor in case if it decreases becomes at most half of the previous value. So we have this observation and we want to calculate the count of GCD values across all the intervals, I see couple of ways how we can exploit the observation: We can fix the left side of the interval and look for the places where $gcd(a_{l}, ..., a_{r})$ function will decrease. Between the points where it decreases it will stay flat so we can add the size of this flat interval to the result of this particular $gcd$. There are different ways how to find the place where the function changes its value, some people were using sparse tables, I have never used those so won't give this solution here. Otherwise you can use segment tree to calculate gcd on the interval and then do a binary search to find where this value changes. This adds squared logarithmic factor to the complexity, not sure if that passes the TL easily. Otherwise you can do basically the same by doing only one descent in the segment tree. Then you get rid of one logarithmic factor in the complexity but that will make segment tree a bit more complicated. Another solution seems to be much simpler, you just go left to right and you calculate what is the number of segments started to the left of current element and what is the greatest common divisors values on those intervals. These values you need to store grouped by the $gcd$ value. This information can be easily updated when you move to the next element to the right - you can check that part in my submission. Our observation guarantees that the number of different $gcd$ values that we have to track is quite small all the time, it's no more than $1 + logA_{max}$. Submission: 8141810, maps are used here to count gcd values, using the vectors instead makes it running two times faster but the code is not that clear then.
|
[
"brute force",
"data structures",
"math"
] | 2,000
|
#include <iostream>
#include <map>
#include <vector>
using namespace std;
template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }
int gcd(int a, int b) {
if (a % b == 0) return b;
return gcd(b, a % b);
}
int main() {
ios_base::sync_with_stdio(false);
int n; cin >> n;
auto v = readVector<int>(n);
map<int, long long> results;
map<int, int> divisors;
map<int, int> nextDivisors;
for (int i = 0 ; i < n ; i++) {
nextDivisors.clear();
for (auto &p : divisors) {
nextDivisors[gcd(p.first, v[i])] += p.second;
}
nextDivisors[v[i]]++;
swap(nextDivisors, divisors);
for (auto &p : divisors)
results[p.first] += p.second;
}
int q; cin >> q;
while (q --> 0) {
int x; cin >> x;
cout << results[x] << endl;
}
}
|
475
|
E
|
Strongly Connected City 2
|
Imagine a city with $n$ junctions and $m$ streets. Junctions are numbered from $1$ to $n$.
In order to increase the traffic flow, mayor of the city has decided to make each street one-way. This means in the street between junctions $u$ and $v$, the traffic moves only from $u$ to $v$ or only from $v$ to $u$.
The problem is to direct the traffic flow of streets in a way that maximizes the number of pairs $(u, v)$ where $1 ≤ u, v ≤ n$ and it is possible to reach junction $v$ from $u$ by passing the streets in their specified direction. Your task is to find out maximal possible number of such pairs.
|
Here we can start with the simple observation - if we have a cycle then we can choose such an orientation for the edges such that it will become a directed cycle. In this case all nodes in the cycle will be accessible from all other nodes of the same cycle. I was using the bridges finding algorithm to find the cycles. So you find all the cycles, for each cycle of size $s_{i}$ you add $s_{i}^{2}$ to the answer. Then you can collapse all the cycles into the single node (storing the cycle size as well). After merging all cycles into single nodes original graph becomes a tree. Now it comes to some kind of a magic, as far as I've seen from the discussions here people were make an assumption about the optimal solution, but nobody proved this assumption. Assumption goes like this: "there exists an optimal solution which has some node (let's call it $root$) such that for every other node $v$ you can either reach $root$ from $v$ or you can reach $v$ from $root$ using directed edges of this optimal solution". Intuitively this assumption makes sense because probably in order to increase the number of pairs of reachable nodes you will try to create as least as possible components in the graph which will be mutually unreachable. So we have this assumption, now in order to solve the problem we can iterate over all nodes in the tree and check what will be the answer if we will make this node to be a $root$ from the assumption. Let's draw some example of the graph which might be a solution according to our assumption: Here the $root$ is drawn on top and every other node has either a path to the $root$ or a path from the $root$. So let's say we decided that some node will be a $root$ but we didn't decide yet for each of its children whether their edges will directed to the $root$ or from the $root$. In order to fulfil our assumption the orientation of the edges within some child's subtree should be the same as the orientation of the edge between the $root$ and its child. There will be two more numbers which we need to add to the result - pairs of reachable nodes within some child's ($root$ children only!) subtree and pairs of reachable nodes for nodes from different subtrees. Let's introduce some variables: $s_{i}$ - size of the $i$-th cycle from the step when we were merging the cycles. In our tree all cycles are already merged into a single node, so $s_{i}$ is a weight of the $i$-th node. It can be equal to 1 if node $i$ did not belong to any cycle. $W_{i}$ - weight of the entire subtree rooted at node $i$. It can be seen that if we orient all edges in the subtree in the same manner according to our assumption then the number of reachable pairs of nodes will not depend on the chosen orientation. Each particular node $i$ adds the following term to the final result: $s_{i} \cdot (W_{i} - s_{i})$. Now we need to decide what should be the orientation of all the edges adjacent to the $root$. Let's declare two more variables: $in$ - sum of $W_{i}$ for all $root$'s children whose edge is directed towards the root. $out$ - same for the children whose edge is directed from the root. So if we have those definitions then the last term for the result will be equal to: $(in + s_{root}) \cdot out + in \cdot s_{root}$. We can see that this term depends only on the $in$ and $out$ values, it doesn't depend on which particular children contribute to each of these values. We check which values for $in$ and $out$ we can achieve, we can do it using the DP similar to the one used in knapsack. So we check every possible value for $in$, based on this we can calculate $out$ value because their sum is fixed and equals to $W_{root} - s_{root}$, then we put them into the formula above and check whether it gives us a better total answer. There is one more thing to be noted about this solution - you can see that I said that we need to iterate over all nodes and make them to be the $root$, then you will need to get all the sizes of the children for particular $root$ and for those sizes you will need to find all the possible values for their sums. The sum can be up to $N$, for some $root$ we might have up to $O(N)$ children, so if you've fixed the $root$ then the rest might have $O(N^{2})$ complexity. This might lead you to a conclusion that the entire algorithm then has $O(N^{3})$ complexity, which is too slow for the given constraints. But that is not the case because outermost and innermost loops depend on each other, basically there you iterate over all the parent-children relations in the tree, and we know that this number in the tree equals to $2(N - 1)$, less than $N^{2}$, so in total it gives $O(N^{2})$ complexity for this solution.
|
[
"dfs and similar"
] | 2,700
|
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
typedef long long LL;
template<typename T> inline void maximize(T &a, T b) { a = std::max(a, b); }
#define all(v) v.begin(),v.end()
using namespace std;
template<typename T> struct argument_type;
template<typename T, typename U> struct argument_type<T(U)> { typedef U type; };
#define next(t, i) argument_type<void(t)>::type i; cin >> i;
#define nextVector(t, v, size) vector< argument_type<void(t)>::type > v(size); { for (int i = 0 ; i < size ; i++) cin >> v[i]; }
#define range(name, start, count) vector<int> name(count); { for (int i = 0 ; i < count ; i++) name[i] = i + start; }
// this dsu will help us to track cycles in the graph
class dsuClass {
public:
int n;
vector<int> parent;
vector<int> size;
void init(int n) {
this->n = n;
parent.resize(n);
size.resize(n);
reset();
}
void reset() {
for (int i = 0 ; i < n ; i++) {
parent[i] = i;
size[i] = 1;
}
}
int update(int a) {
if (parent[a] == a) return a;
return parent[a] = update(parent[a]);
}
void join(int a, int b) {
a = update(a);
b = update(b);
if (size[b] > size[a]) swap(a, b);
if (a == b) return;
size[a] += size[b];
parent[b] = a;
}
};
dsuClass dsu;
// these are used to find bridges, code itself is taken from e-maxx
vector<bool> used;
const int MAXN = 2000;
int timer, tin[MAXN], fup[MAXN];
void dfs (int v, int p, vector<vector<int>> &vEdges) {
used[v] = true;
tin[v] = fup[v] = timer++;
for (auto to : vEdges[v]) {
if (to == p) continue;
if (used[to]) {
fup[v] = min (fup[v], tin[to]);
dsu.join(v,to);
} else {
dfs (to, v, vEdges);
fup[v] = min (fup[v], fup[to]);
if (fup[to] <= tin[v])
dsu.join(v,to);
}
}
}
void find_bridges(vector<vector<int>> &vEdges) {
timer = 0;
for (int i=0; i<used.size(); ++i)
if (!used[i])
dfs (i, -1, vEdges);
}
int calc_tree_size(int v, int parent, vector<vector<int>> &edges, vector<int> &sizes, int &result_acc) {
int result = 0;
for (auto child : edges[v]) if (child != parent) {
result += calc_tree_size(child, v, edges, sizes, result_acc);
}
result_acc += sizes[v] * result;
result += sizes[v];
return result;
}
int calc_tree_best_result(vector<int> sizes, vector<pair<int, int>> &edges_list) {
int best = 0;
int n = sizes.size();
vector<vector<int>> edges(n);
for (auto e : edges_list) {
edges[e.first].push_back(e.second);
edges[e.second].push_back(e.first);
}
const int MAXSUM = 2000;
for (int v = 0 ; v < n ; v++) {
int cur = 0;
vector<int> childrenSizes(edges[v].size());
for (int i = 0 ; i < childrenSizes.size() ; i++)
childrenSizes[i] = calc_tree_size(edges[v][i], v, edges, sizes, cur);
vector<int> achievable_sum(MAXSUM + 1);
achievable_sum[0] = true;
for (auto cs : childrenSizes) {
for (int x = MAXSUM ; x >= cs ; x--) if (achievable_sum[x - cs]) achievable_sum[x] = true;
}
int full_sum = accumulate(all(childrenSizes), 0);
for (int in = 0 ; in <= MAXSUM ; in++) if (achievable_sum[in]) {
int out = full_sum - in;
maximize(best, (in + sizes[v]) * out + in * sizes[v] + cur);
}
}
return best;
}
int main() {
int n; cin >> n;
int m; cin >> m;
vector<vector<int>> vEdges(n);
vector<pair<int, int>> edges(n);
for (int i = 0 ; i < m ; i++) {
int a; cin >> a;
int b; cin >> b;
a--;
b--;
vEdges[a].push_back(b);
vEdges[b].push_back(a);
edges.push_back( { a , b } );
}
used.resize(n);
dsu.init(n);
find_bridges(vEdges);
vector<int> newParents; // these will represent the nodes of the tree after we merge cycles
for (int i = 0 ; i < n ; i++) if (dsu.update(i) == i) newParents.push_back(i);
map<int, int> parentsMapping;
for (int i = 0 ; i < newParents.size() ; i++) parentsMapping[newParents[i]] = i;
vector<pair<int, int>> newEdges;
int result = 0;
for (auto parent : newParents) {
result += dsu.size[parent] * dsu.size[parent];
}
for (auto e : edges) {
if (dsu.update(e.first) != dsu.update(e.second))
newEdges.push_back( make_pair(parentsMapping[dsu.update(e.first)] , parentsMapping[dsu.update(e.second)]) );
}
vector<int> sizes(newParents.size());
for (int i = 0 ; i < sizes.size() ; i++) sizes[i] = dsu.size[newParents[i]];
result += calc_tree_best_result(sizes, newEdges);
cout << result;
}
|
475
|
F
|
Meta-universe
|
Consider infinite grid of unit cells. Some of those cells are planets.
Meta-universe $M = {p_{1}, p_{2}, ..., p_{k}}$ is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet $p_{i}$ of meta-universe $M$ on it; 2) there are planets of $M$ located on both sides from this row or column. In this case we can turn the meta-universe $M$ into two non-empty meta-universes $M_{1}$ and $M_{2}$ containing planets that are located on respective sides of this row or column.
A meta-universe which can't be split using operation above is called a universe. We perform such operations until all meta-universes turn to universes.
Given positions of the planets in the original meta-universe, find the number of universes that are result of described process. It can be proved that each universe is uniquely identified not depending from order of splitting.
|
Let's try to solve this problem naively first, the approach should be obvious then - you have a set of points, you iterate them left to right and you mind the gap between them. If there is such a gap between two neighbours you split this meta-universe with vertical line and do the same thing for each of two subsets. If you found no such gap by going left to right, you do the same going top to bottom. If you are unlucky again then you are done, this is a universe, it cannot be split. Let's think about the complexity of this approach now, even if get the points sorted and split for free then the complexity will highly depend on how soon you found a place where you could split the meta-universe. For example if you are lucky and you will always split close to the start of the sequence then your total complexity would be $O(n)$, which is very good indeed. If you will encounter the option to split somewhere in the middle of the sequence, which means that you split the meta-universe in two halves, you will get a $O(NlogN)$ solution, not linear but still good enough for this problem. The worst case occurs when you split always after iterating through the entire sequence, that means that in order to extract one point from the set you will have to iterate through all of them, now the complexity becomes $O(N^{2})$, that's not enough already. Let's think about it again, we got several cases, two of them are good (when we split in the beginning or in the middle) and the third one is too slow, it happens when we split always in the end. We need to make our solution better in this particular case and that should be almost enough to solve the entire problem. The obvious approach how to get rid of "split at the end" case is to start iterating from the end initially. And it should be obvious as well that it doesn't change much because your old start becomes the end now. But what we can do instead is to start iterating from both sides, then in any case you are winner! Intuitively, if you encountered a way to split at some end of the sequence then you're good to go because you spent almost no time on this particular step and you already found a way to split it further. In the opposite case, if you had to iterate through the entire sequence and found a split point in the middle you should be still happy about it because it means that on the next steps each of your new sets will be approximately two times smaller, that leads you back to $O(NlogN)$ complexity. Also you should not forget that you need to do the same for Y coordinate as well, that means that you need to have four iterators and you need to check them simultaneously. This is the basic idea for my solution, there is just one more detail to be added. Initially I told that our complexity estimate is given if we "sort and split for free". That's not that easy to achieve, but we can achieve something else almost as good as this one. In order to split cheaply all you need to do is to avoid the actual split :-) Instead of splitting the sequence into two subsequences you can just leave the original sequence and extract part of it which will become a new subsequence. Obviously if you want to make this operation cheaper you need to extract the smaller part. For example if you have a sequence of points sorted by X and you found a split point by iterating from the end of the sequence then you can be sure that the right subsequence will not be longer than the left sequence, because you iterate from the left-hand side and from the right-hand side simultaneously. Now we need to take care about sorting part as well. This one is easy, all you need to do is instead of storing one sequence of points you store all the points in two sorted sets - one by X and one by Y coordinate. In total this should add just one more logarithmic factor to the complexity. That is the entire solution, I'd like to get back one more time to the complexity analysis. We have a recurring algorithm, on every step of the recurrence we're looking for the split point, then we split and invoke this recurring algorithm two more times. It looks that for the worst case (which is split in the middle) we will split a sequence into two subsequences of the same size, so we have a full right to apply a Master theorem here. On each step our complexity seems to be $O(NlogN)$ (log factor because of using sets) so the "Case 2. Generic form" section from the Wiki gives us a solution that our entire algorithm has an $O(Nlog^{2}N)$ time complexity. Am I correct?
|
[
"data structures"
] | 2,900
|
#include <cstdlib>
#include <iostream>
#include <set>
using namespace std;
pair<int, int> mirror(pair<int, int> &p) {
return { p.second , p.first };
}
void move_from_first_two_sets_to_other_two(set<pair<int, int>> &set1_1, set<pair<int, int>> &set1_2, set<pair<int, int>> &set2_1, set<pair<int, int>> &set2_2,
pair<int, int> item) {
set1_1.erase(item);
set1_2.erase(mirror(item));
set2_1.insert(item);
set2_2.insert(mirror(item));
}
int split(set<pair<int, int>> &byX, set<pair<int, int>> &byY) {
if (byX.size() == 1) return 1;
auto x_forward = byX.begin();
auto x_backward = byX.rbegin();
auto y_forward = byY.begin();
auto y_backward = byY.rbegin();
set<pair<int, int>> byX2, byY2;
do {
int x_prev = x_forward->first;
x_forward++;
if (abs(x_forward->first - x_prev) > 1) {
while (byX.begin()->first <= x_prev) {
move_from_first_two_sets_to_other_two(byX, byY, byX2, byY2, *byX.begin());
}
return split(byX, byY) + split(byX2, byY2);
}
x_prev = x_backward->first;
x_backward++;
if (abs(x_backward->first - x_prev) > 1) {
while (byX.rbegin()->first >= x_prev) {
move_from_first_two_sets_to_other_two(byX, byY, byX2, byY2, *byX.rbegin());
}
return split(byX, byY) + split(byX2, byY2);
}
int y_prev = y_forward->first;
y_forward++;
if (abs(y_forward->first - y_prev) > 1) {
while (byY.begin()->first <= y_prev) {
move_from_first_two_sets_to_other_two(byY, byX, byY2, byX2, *byY.begin());
}
return split(byX, byY) + split(byX2, byY2);
}
y_prev = y_backward->first;
y_backward++;
if (abs(y_backward->first - y_prev) > 1) {
while (byY.rbegin()->first >= y_prev) {
move_from_first_two_sets_to_other_two(byY, byX, byY2, byX2, *byY.rbegin());
}
return split(byX, byY) + split(byX2, byY2);
}
} while (*x_forward < *x_backward);
return 1;
}
int main() {
int n; cin >> n;
set<pair<int, int>> byX, byY;
while (n --> 0) {
int x; cin >> x;
int y; cin >> y;
byX.insert( { x , y } );
byY.insert( { y , x } );
}
cout << split(byX, byY);
}
|
476
|
A
|
Dreamoon and Stairs
|
Dreamoon wants to climb up a stair of $n$ steps. He can climb $1$ or $2$ steps at each move. Dreamoon wants the number of moves to be a multiple of an integer $m$.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
|
We can show that the maximum number of moves possible is n and minimal moves needed is $\textstyle{\left[\!\!{\frac{n}{2}}\right]\!\!}\$, so the problem equals to determine the minimal integer that is a multiple of m in the range $\textstyle\left[{\frac{n}{2}}\right],n\right]$. One way to find the minimal number which is a multiple of m and greater than or equal to a number x is $\textstyle\bigcap{\frac{x}{m}}\mid*\ y n$, we can compare this number to the upper bound n to determine if there is a valid solution. Although best practice is $O(1)$, $O(n)$ enumeration of each possible number of moves would also work. time complexity: $O(1)$ explanation of sample code: The $\left[{\frac{a}{b}}\right]$ can be calculated in the following c++ code if $a$ is non-negative and $b$ is positive: (a+b-1)/b Because / in c++ is integral division so (a+b-1)/b would result in $d i v(a+b-1,b)={\bigl\lfloor}{\frac{a+b-1}{b}}{\bigr\rfloor}$ Let $a = div(a, b)b + mod(a, b) = db + m$, $d i v(a+b-1,b)=d i v(d b+m+b-1,b)={\bigl\lfloor}{\frac{d b+m+b-1}{h}}{\bigr\rfloor}=d+{\bigl\lfloor}{\frac{m+b-1}{h}}{\bigr\rfloor}$. Which means if $m=0\Rightarrow d i v(a+b-1,b)=d$, otherwise $div(a + b - 1, b) = d + 1$. Can be translated to if $m o d(a,b)=0\Rightarrow d i v(a+b-1,b)=d i v(a,b)$, otherwise $div(a + b - 1, b) = div(a, b) + 1$. Which matches the value of $\left[{\frac{a}{b}}\right]$.
|
[
"implementation",
"math"
] | 1,000
|
#include <cstdio>
int main(void)
{
int n, m ;
scanf("%d%d", &n, &m) ;
int lower_bound = (n+1)/2 ;
int ans = (lower_bound+m-1)/m*m ;
if(ans>n)
ans = -1 ;
printf("%d\n", ans) ;
return 0 ;
}
|
476
|
B
|
Dreamoon and WiFi
|
Dreamoon is standing at the position $0$ on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types:
- Go 1 unit towards the positive direction, denoted as '+'
- Go 1 unit towards the negative direction, denoted as '-'
But the Wi-Fi condition is so poor that Dreamoon's smartphone reports some of the commands can't be recognized and Dreamoon knows that some of them might even be wrong though successfully recognized. Dreamoon decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the $1$ unit to the negative or positive direction with the same probability $0.5$).
You are given an original list of commands sent by Drazil and list received by Dreamoon. What is the probability that Dreamoon ends in the position originally supposed to be final by Drazil's commands?
|
The order of moves won't change the final position, so we can move all '?'s to the end of the string. We have the following information: 1. the correct final position 2. the position that Dreamoon will be before all '?'s 3. the number of '?'s We can infer that the distance and direction dreamoon still needs to move in the '?' part from 1. and 2., and furthur translate that to how many +1s and -1s dreamoon will need to move. What's left is a combinatorial problem, the probability would be $\frac{C({\it(r u u p u b e r~o f~\stackrel{f}{~}}^{f}s_{\it3},n u p m b e r~o f~\underbrace{~}{~+\mathrm{l}{\it s}})}{2^{(n u m b e r~o f~\stackrel{f}{~}}s)}$. So we can compute that formula within $O(n)$ time assuming n is the length of commands, but since N is small so we can brute force every possible choice of '?' with some recursive or dfs like search in $O(2^{n})$ time complexity. Note that the problem asks for a precision of $10^{ - 9}$, so one should output to $11$ decimal places or more. time complexity: $O(n)$, assuming $n$ is the length of commands.
|
[
"bitmasks",
"brute force",
"combinatorics",
"dp",
"math",
"probabilities"
] | 1,300
|
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
int main(void)
{
char s1[15], s2[15] ;
scanf("%s%s", s1, s2) ;
int n = strlen(s1) ;
int answerPosition = 0 ;
for(int i=0;i<n;i++)
answerPosition += (s1[i]=='+'?1:-1) ;
int finalPosition = 0 ;
int moves = 0 ; //number of '?'
for(int i=0;i<n;i++)
{
if(s2[i]=='?')
moves++ ;
else
finalPosition += (s2[i]=='+'?1:-1) ;
}
int distance = answerPosition-finalPosition ;
double answer ;
if((distance+moves)%2!=0 || moves<abs(distance)) //can't reach the destination no matter how
answer = 0 ;
else
{
int m = (moves+abs(distance))/2 ; //moves needed toward the distance m is abs(distance)+(moves-abs(distance))/2
//answer is C(moves,m)/(1<<moves)
int c = 1 ;
for(int i=0;i<m;i++)
c *= moves-i ;
for(int i=2;i<=m;i++)
c /= i ;
answer = (double)c/(1<<moves) ;
}
printf("%.12f\n", answer) ;
return 0 ;
}
|
476
|
C
|
Dreamoon and Sums
|
Dreamoon loves summing up something for no reason. One day he obtains two integers $a$ and $b$ occasionally. He wants to calculate the sum of all nice integers. Positive integer $x$ is called nice if $\operatorname*{mod}(x,b)\neq0$ and $\frac{\mathrm{div}(x,b)}{\mathrm{mod}\{x.b)}\implies\int$, where $k$ is some \textbf{integer} number in range $[1, a]$.
By $\operatorname{div}(x,y)$ we denote the quotient of integer division of $x$ and $y$. By ${\mathrm{mod}}(x,y)$ we denote the remainder of integer division of $x$ and $y$. You can read more about these operations here: http://goo.gl/AcsXhT.
The answer may be large, so please print its remainder modulo $1 000 000 007$ ($10^{9} + 7$). Can you compute it faster than Dreamoon?
|
If we fix the value of $k$, and let $d = div(x, b)$, $m = mod(x, b)$, we have : $d = mk$ $x = db + m$ So we have $x = mkb + m = (kb + 1) * m$. And we know $m$ would be in range $[1, b - 1]$ because it's a remainder and $x$ is positive, so the sum of $x$ of that fixed $k$ would be $\textstyle\sum_{m=1}^{b-1}((k b+1)m)=(k b+1){\frac{b(b-1)}{2}}$. Next we should notice that if an integer $x$ is $nice$ it can only be $nice$ for a single particular $k$ because a given $x$ uniquely defines $div(x, b)$ and $mod(x, b)$. Thus the final answer would be sum up for all individual $k$: $\textstyle\sum_{k=1}^{a}((k b+1){\frac{b(b-1)}{2}})$ which can be calculated in $O(a)$ and will pass the time limit of 1.5 seconds. Also the formula above can be expanded to ${\frac{(a{(a+1)}}{2}}b+a){\frac{b(b-1)}{2}}$. Dreamoon says he's too lazy to do this part, so if you use $O(1)$ solution you just computed the answer faster than Dreamoon!!! Note that no matter which approach one should be very careful of overflowing of the integer data type of the used language. For example one should do a module after every multiplication if using 64-bit integer type. And pay attention to precedence of operations: take c++ for example a+b%c would be executed as a+(b%c) instead of (a+b)%c, another c++ example a*(b*c)%m would be executed as (a*(b*c))%m instead of a*((b*c)%m). Thanks saurabhsuniljain for pointing out the preceding problem and examples in the comment! time complexity: $O(1)$
|
[
"math"
] | 1,600
|
#include <cstdio>
long long mod = 1000000007 ;
int main(void)
{
long long a, b ;
scanf("%I64d%I64d", &a, &b) ;
long long B = (b*(b-1)/2) % mod ;
long long A1 = (a*(a+1)/2) % mod ;
long long A = (A1*b+a) % mod ;
long long answer = (A*B) % mod ;
printf("%I64d\n", answer) ;
return 0 ;
}
|
476
|
D
|
Dreamoon and Sets
|
Dreamoon likes to play with sets, integers and $\operatorname{gcd}$. $\operatorname*{gcd}(a,b)$ is defined as the largest positive integer that divides both $a$ and $b$.
Let $S$ be a set of exactly four distinct integers greater than $0$. Define $S$ to be of rank $k$ if and only if for all pairs of distinct elements $s_{i}$, $s_{j}$ from $S$, $\operatorname*{gcd}(s_{i},s_{j})=k$.
Given $k$ and $n$, Dreamoon wants to make up $n$ sets of rank $k$ using integers from $1$ to $m$ such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum $m$ that makes it possible and print one possible solution.
|
The first observation is that if we divide each number in a set by $k$, than the set would be rank $1$. So we could find $n$ sets of rank $1$ then multiple every number by $k$. For how to find $n$ sets of rank 1, we can use ${6a + 1, 6a + 2, 6a + 3, 6a + 5}$ as a valid rank $1$ set and take $a = 0$ to $n - 1$ to form $n$ sets and thus $m = (6n - 1) * k$. The proof that $m$ is minimal can be shown by the fact that we take three consecutive odd numbers in each set. If we take less odd numbers there will be more than $1$ even number in a set which their gcd is obviously a multiple of $2$. And if we take more odd numbers $m$ would be larger. The output method is straight forward. Overall time complexity is $O(n)$. time complexity: $O(n)$ sample code:
|
[
"constructive algorithms",
"greedy",
"math"
] | 1,900
|
#include <cstdio>
int main(void)
{
int n, k ;
scanf("%d%d", &n, &k) ;
printf("%d\n", k*(6*n-1)) ;
for(int i=0;i<n;i++)
printf("%d %d %d %d\n", k*(6*i+1), k*(6*i+3), k*(6*i+4), k*(6*i+5)) ;
return 0 ;
}
|
476
|
E
|
Dreamoon and Strings
|
Dreamoon has a string $s$ and a pattern string $p$. He first removes exactly $x$ characters from $s$ obtaining string $s'$ as a result. Then he calculates $\operatorname{occ}(s^{\prime},p)$ that is defined as the maximal number of non-overlapping substrings equal to $p$ that can be found in $s'$. He wants to make this number as big as possible.
More formally, let's define $\operatorname{ans}(x)$ as maximum value of $\operatorname{occ}(s^{\prime},p)$ over all $s'$ that can be obtained by removing exactly $x$ characters from $s$. Dreamoon wants to know $\operatorname{ans}(x)$ for all $x$ from $0$ to $|s|$ where $|s|$ denotes the length of string $s$.
|
First let $A[i]$ to be the minimal length $L$ needed so that substring $s[i..i + L]$ can become pattern $p$ by removing some characters. We can calculate this greedily by keep selecting next occurrence of characters in $p$ in $O(length(s))$ time for a fixed $i$, so for all $i$ requires $O(length(s)^{2})$. Next we can do a dp $D[i][j]$ where $D[i]$ is the answer array for $s[0..i]$. $D[i]$ can contribute to $D[i + 1]$ with $0$ or $1$ removal and to $D[i + A[i]]$ with $A[i] - length(p)$ removal(s). In other words, $D[i][j]$ can transition into tree relations $D[i + 1][j] = D[i][j]$ //not delete $s[i]$, $D[i + 1][j + 1] = D[i][j]$ //delete $s[i]$, and $D[i + A[i]][j + A[i] - length(p)] = D[i][j] + 1$ //form a substring $p$ by deleting $A[i] - length(p)$ characters. Calculate forwardly from $D[0]$ to $D[length(s) - 1]$ gives the final answer array as $D[length(s)]$. Calculating $D[i]$ requires $O(length(s))$ time for a fixed $i$, so for all $i$ takes $O(length(s)^{2})$ time. time complexity: $O(n^{2})$, $n = length(s)$ Another solution: Let $k$ = $div(length(s), length(p))$. We can run an edit distance like algorithm as following (omitting the details of initialization and boundary conditions): for(i=0;i<n;i++) for(j=0;j<k*p;j++) if(s[i]==p[j%length(p)]) D[i][j] = D[i-1][j-1] D[i][j] = min(D[i][j], D[i-1][j] + (j%length(p)!=length(p)-1))That means remove cost is $1$ when it is in the middle of a $p$ and $0$ elsewhere because $p$ need to be consecutive(thus no need to be actually remove outside of a $p$). Then $D[n][t * length(p)]$ is the minimal number of removals to have $t$ non-overlapping substring of $p$. So we have $answer[D[n][t * length(p)..(t + 1) * length(p)] = t$. And after the maximal $t$ is reached, decrease answer by $1$ for every $length(p)$. time complexity: $O(n^{2})$
|
[
"dp",
"strings"
] | 2,200
|
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std ;
char s[2100], p[510] ;
int D[2100][2100] ;
int answer[2100] ;
int INF = 2100 ;
int main(void)
{
gets(s) ;
gets(p) ;
int Len_s = strlen(s) ;
int Len_p = strlen(p) ;
int k = Len_s/Len_p ;
D[0][0] = 0 ;
for(int i=1;i<=Len_p*k;i++)
D[0][i] = INF ;
for(int i=1;i<=Len_s;i++)
{
D[i][0] = 0 ;
for(int j=1;j<=Len_p*k;j++)
{
if(s[i-1]==p[(j-1)%Len_p])
D[i][j] = D[i-1][j-1] ;
else
D[i][j] = INF ;
D[i][j] = min(D[i][j], D[i-1][j]+(j%Len_p!=0)) ;
}
}
int end = 0 ;
for(int t=0;D[Len_s][t*Len_p]<INF && t<=k;t++)
{
end = D[Len_s][(t+1)*Len_p] ;
if(end==INF || t==k)
end = Len_s-t*Len_p+1 ;
for(int i=D[Len_s][t*Len_p];i<end;i++)
answer[i] = t ;
}
for(int i=end;i<=Len_s;i++)
answer[i] = (Len_s-i)/Len_p ;
printf("%d", answer[0]) ;
for(int i=1;i<=Len_s;i++)
printf(" %d", answer[i]) ;
putchar('\n') ;
return 0 ;
}
|
477
|
D
|
Dreamoon and Binary
|
Dreamoon saw a large integer $x$ written on the ground and wants to print its binary form out. Dreamoon has accomplished the part of turning $x$ into its binary format. Now he is going to print it in the following manner.
He has an integer $n = 0$ and can only perform the following two operations in any order for unlimited times each:
- Print n in binary form without leading zeros, each print will append to the right of previous prints.
- Increase n by 1.
Let's define an ideal sequence as a sequence of operations that can successfully print binary representation of $x$ without leading zeros and ends with a print operation (i.e. operation 1). Dreamoon wants to know how many different ideal sequences are there and the length (in operations) of the shortest ideal sequence.
The answers might be large so please print them modulo 1000000007 ($10^{9} + 7$).
Let's define the string representation of an ideal sequence as a string of '1' and '2' where the $i$-th character in the string matches the $i$-th operation performed. Two ideal sequences are called different if their string representations are different.
|
Let $Xb$ be the binary string of number $X$. An ideal sequence can be expressed as a partition of $Xb$: $P_{1} = Xb[1..p_{1}], P_{2} = Xb[p_{1}..p_{2}], ... P_{K} = Xb[p_{K - 1}..length(Xb)]$ where $P_{i} \le P_{i + 1}$. The length of operations of such sequence is $P_{K} + K$. We can calculate the number of different ideal sequences by dp. State $D[i][j]$ stands for the answer of state that we have print $Xb[1..j]$ and last partition is $Xb[i..j]$. A possible way of transition is that a state $D[i][j]$ can go to state $D[i][j + 1]$ and $D[j][k]$ where $k$ is the minimal possible position such that value of $Xb[j..k]$ is equal to or greater than the value of $Xb[i..j]$ and $Xb[j]$ is $1$ since we can't print any leading $0$. Note that $D[j][k + 1]$ can also derived from $D[i][j]$ but it will covered by $D[i][j] \rightarrow D[j][k] \rightarrow D[j][k + 1]$, so we don't need to consider this case to avoid redundant counts. If we can determine $k$ for each $i$, $j$ pair in $O(1)$ then we can compute this dp in $O(length(Xb)^{2})$ in the following manner: for(j=0;j<n;j++) for(i=0;i<j;i++) compute the transitions of D[i][j]So let's look into how to calculate the value $k$ for a given $i$, $j$ pair. If the value of $Xb[j..2j - i]$ is equal to or greater than $Xb[i..j]$ than $k$ is $2j - i$ because if $k$ is less than $2j - i$ would make length of the new partition less than the previous partition thus its value would be lesser. And if $k$ can't be $2j - i$, the value of $2j - i + 1$ is always a valid choice because it would make the length of the new partition greater than the previous one. So for each length $L$ if we know the order of $Xb[i..i + L]$ and $Xb[i + L..i + 2L]$ in $O(1)$ time we can calculate k in $O(1)$ time(can be easily shown by assuming $L = j - i$). One way of doing such is using prefix doubling algorithm for suffix array construction to build a RMQ structure for query in $O(1)$ time. The prefix doubling algorithm requires $O(nlgn)$ precompute time. Note there is still a various of ways to do this part of task in the same or better time complexties. And for the shortest length part we can compute the minimal parts needed so far for each state along with the preivous dp. Then compare all states ends with $j = length(Xb)$. Overall we can solve this problem in $O(length(Xb)^{2})$ with caution in details like boundaries and module operations. time complexity: $O(n^{2})$, $n = length(Xb)$ Note the sample code use a nlgnlgn version of prefix doubling algorithm
|
[
"dp",
"strings"
] | 2,700
|
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
char X[5100] ;
int len ;
int arr[5100] ;
int rank[30][5100] ;
int *ref, rL ;
long long mod = 1000000007LL ;
long long sp[5100][5100] ;
long long ws[5100][5100] ;
//compare function for doubling prefix algorithm
//ref is the reference(previous) table of rank and rL is the Length computing
int cmp(int a, int b)
{
if(ref[a]==ref[b])
{
if(ref[a+rL]==ref[b+rL])
return 0 ;
else
return (ref[a+rL]>ref[b+rL]?1:-1) ;
}
else
return (ref[a]>ref[b]?1:-1) ;
}
//compare function for std::sort
bool scmp(int a, int b)
{
return (cmp(a,b)==-1) ;
}
//update an dp item
void update(int s1, int e1, int s2, int e2, int add)
{
ws[s2][e2] = (ws[s2][e2]+ws[s1][e1])%mod ;
sp[s2][e2] = std::min(sp[s2][e2], sp[s1][e1]+add) ;
}
//most significant bit
int msb(int n)
{
int pos = 0 ;
while(n!=1)
{
pos++ ;
n >>= 1 ;
}
return pos ;
}
//RMQ query
bool leq(int L, int s1, int s2)
{
int pos = msb(L) ;
int hL = (1<<pos) ;
if(hL==L)
return (rank[pos][s1]<=rank[pos][s2]) ;
else
{
if(rank[pos][s1]<rank[pos][s2])
return true ;
else if(rank[pos][s1]==rank[pos][s2])
{
int np = L-hL ;
return (rank[pos][s1+np]<=rank[pos][s2+np]) ;
}
else
return false ;
}
}
int main(void)
{
gets(X) ;
len = strlen(X) ;
//build up the RMQ table, doubling prefix algorithm
for(int i=0;i<len;i++)
rank[0][i] = X[i]-'0' ;
for(int L=1,n=1;2*n<=len;L++,n<<=1)
{
int mn = len-2*n+1 ;
for(int s=0;s<mn;s++)
arr[s] = s ;
ref = rank[L-1] ;
rL = n ;
std::sort(arr, arr+mn, scmp) ;
int curRank = 0 ;
for(int s=0;s<mn;s++)
{
rank[L][arr[s]] = curRank ;
if(s+1<mn && cmp(arr[s], arr[s+1])!=0)
curRank++ ;
}
}
//dp, sp=shortest path length, ws=ways
long long INF = 2*len ;
for(int i=0;i<=len;i++)
for(int j=0;j<=len;j++)
{
sp[i][j] = INF ;
ws[i][j] = 0 ;
}
sp[0][1] = 1 ;
ws[0][1] = 1 ;
for(int e=1;e<len;e++)
{
for(int s=0;s<e;s++)
{
if(X[s]=='1')
{
update(s,e,s,e+1,0) ;
if(X[e]=='1')
{
int L = e-s ;
if(e+L<=len && leq(L,s,e))
update(s,e,e,e+L,1) ;
else if(e+L+1<=len)
update(s,e,e,e+L+1,1) ;
}
}
}
}
//parsing dp table to answer
long long ans1 = ws[0][len] ;
int ans2 = 0 ;
long long dif = 1 ;
for(int s=1;s<len;s++)
{
if(sp[s][len]<INF)
{
ans1 = (ans1+ws[s][len])%mod ;
//the answer would be X[s..len]+sp[s][len]
//so diff would be X[ans2..len]+sp[ans2][len]-X[s..len]-sp[s][len]
//if previous value >= 0 than ans2=s
//previous value could be expressed as dif*2^(len-s)+sp[ans2][len]-sp[s][len]
//so if dif*2^(len-s)>=sp[s][len]-sp[ans2][len] will do, BTW the latter max is len or 2000
long long val = sp[s][len]-sp[ans2][len] ;
if(val<=0 || s-ans2>12 || len-s>12 || dif*(1<<(len-s))>=val)
{
dif = 0 ;
ans2 = s ;
}
}
dif = (dif<<1)+X[s]-'0' ;
}
long long ans2val = 0 ;
for(int i=ans2;i<len;i++)
ans2val = ((ans2val<<1)+X[i]-'0')%mod ;
ans2val = (ans2val+sp[ans2][len])%mod ;
printf("%d\n%d\n", (int)ans1, (int)ans2val) ;
return 0 ;
}
|
477
|
E
|
Dreamoon and Notepad
|
Dreamoon has just created a document of hard problems using notepad.exe. The document consists of $n$ lines of text, $a_{i}$ denotes the length of the $i$-th line. He now wants to know what is the fastest way to move the cursor around because the document is really long.
Let $(r, c)$ be a current cursor position, where $r$ is row number and $c$ is position of cursor in the row. We have $1 ≤ r ≤ n$ and $0 ≤ c ≤ a_{r}$.
We can use following six operations in notepad.exe to move our cursor assuming the current cursor position is at $(r, c)$:
- up key: the new cursor position $(nr, nc) = (max(r - 1, 1), min(a_{nr}, c))$
- down key: the new cursor position $(nr, nc) = (min(r + 1, n), min(a_{nr}, c))$
- left key: the new cursor position $(nr, nc) = (r, max(0, c - 1))$
- right key: the new cursor position $(nr, nc) = (r, min(a_{nr}, c + 1))$
- HOME key: the new cursor position $(nr, nc) = (r, 0)$
- END key: the new cursor position $(nr, nc) = (r, a_{r})$
You're given the document description ($n$ and sequence $a_{i}$) and $q$ queries from Dreamoon. Each query asks what minimal number of key presses is needed to move the cursor from $(r_{1}, c_{1})$ to $(r_{2}, c_{2})$.
|
Although swapping two parts of a query would result in different answer, if we reverse the lines length alltogether then the answer would stay the same. So we only analyze queries where $r2 \ge r1$. The answers would comes in several types, we'll discuss them one by one: 1. HOME key being pressed once: the answer will be $1(HOME) + r2 - r1(down keys) + c2(right keys)$. Note that this is the best answer if the HOME key is ever pressed once, so we won't consider HOME key anymore. This step is $O(1)$ for a single query, thus $O(q)$ in total. 2. direct presses $r2 - r1$ down keys and no or one END key in those rows: because the cursor position will be reset to the row length if we go down to a row with length less than current cursor position, the possible positions that can be at row $p$ if we start at end of each previous rows can be track with a stack. The position directly pressing only down keys from $r1$ to $r2$ is $min(c1, the length of first row after r1 in stack)$. We can use a binary search to get the first row after or equal $r1$ in stack. From that row till $r2$ in the stack are the positions possible when pressing ONE END key (pressing more won't get more possible positions), we can use a binary search to find the position closest to $c2$ which is the best. We can sort all queries and use $O(qlgn)$ time for queries and $O(n)$ time for maintaining stack, so $O(qlgn + n)$ in total. 3. go back some rows and press one or no END key at the row: we only interested in END OF rows in stack constructed in 2.. We can use a binary search in stack to identify the range of rows interested. For those lengths of row less than $c2$(also can use a binary search to locate) we only need to consider the first one encountered(closest to $r1$), note still need to consider if it needs an END key for this case. For those lengths of row greater than or equal to $c2$, the answer would be $r1 + r2 - 2 * (row reached) + (length of the row) - c2 + (1 if length of the row greater than c1)$. The terms related to row in the previous formula is $2 * (row reached) + (length of the row) + (1 if length of the row greater than c1)$. We can identify the range with and without +1(last term) and query in a segment tree of the minimal value of $2 * (row reached) + (length of the row)$ for each range. Thus the time need here is $O(nlgn)$ for maintaining segment tree and $O(qlgn)$ for query while sharing with the stack of 2., so $O(nlgn + qlgn)$ in total. 4. go beyond r2 some rows and press no or one END at the row: this needs a reversed stack and very similar approach of 3.. The time complexity is the same as 2. and 3.. So the total time complexity is $O((n + q)lgn)$, note this problem is very hard to get the code right. time complexity: $O((n + q)lgn)$
|
[
"data structures"
] | 3,100
|
#include <bits/stdc++.h>
#define PB push_back
typedef long long LL;
using namespace std;
const int SIZE = 4e5+1;
const int MAX = 1e9;
int n,a[SIZE],an[SIZE],d[SIZE<<2],stk[SIZE],ml[SIZE];
struct data{
int x1,y1,y2,id;
data(int _x1,int _y1,int _y2,int _id){x1=_x1;y1=_y1;y2=_y2;id=_id;}
};
vector<data>in[2][SIZE],emp;
vector<pair<int,int> >rmq_query[SIZE];
void fresh(int& x,int v){if(x>v)x=v;}
void init(int r[],int id,int L,int R){
r[id]=MAX;
if(L==R)return;
int M=(L+R)>>1;
init(r,id<<1,L,M);
init(r,(id<<1)|1,M+1,R);
}
int qq(int r[],int id,int L,int R,int ll,int rr){
if(ll<=L&&R<=rr)return r[id];
int M=(L+R)>>1;
if(rr<=M)return qq(r,id<<1,L,M,ll,rr);
if(M<ll)return qq(r,(id<<1)|1,M+1,R,ll,rr);
return min(qq(r,id<<1,L,M,ll,rr),qq(r,(id<<1)|1,M+1,R,ll,rr));
}
void insert(int r[],int id,int L,int R,int x,int v){
fresh(r[id],v);
if(L==R)return;
int M=(L+R)>>1;
if(x<=M)insert(r,id<<1,L,M,x,v);
else insert(r,(id<<1)|1,M+1,R,x,v);
}
void erase(int r[],int id,int L,int R,int x){
if(L==R){
r[id]=MAX;
return;
}
int M=(L+R)>>1;
if(x<=M)erase(r,id<<1,L,M,x);
else erase(r,(id<<1)|1,M+1,R,x);
r[id]=min(r[id<<1],r[(id<<1)|1]);
}
void Go(vector<data>input[]){
int i,j,k;
init(d,1,0,n-1);
for(i=1,k=0;i<=n;i++){
while(k>0&&a[i]<=a[stk[k-1]]){
erase(d,1,0,n-1,k-1);
k--;
}
stk[k++]=i;
insert(d,1,0,n-1,k-1,a[i]-2*i);
for(j=0;j<(int)input[i].size();j++){
int ll=0,rr=k,ll2=-1,rr2=k-1;
while(ll<rr){
int mm=(ll+rr)>>1;
if(a[stk[mm]]<=input[i][j].y2)ll=mm+1;
else rr=mm;
}
while(ll2<rr2){
int mm2=(ll2+rr2+1)>>1;
if(stk[mm2]>input[i][j].x1)rr2=mm2-1;
else ll2=mm2;
}
// case: no end
if(input[i][j].x1<=i){
if(min(ml[input[i][j].id],input[i][j].y1)<=input[i][j].y2)fresh(an[input[i][j].id],abs(input[i][j].x1-i)+input[i][j].y2-min(ml[input[i][j].id],input[i][j].y1));
else{
fresh(an[input[i][j].id],abs(input[i][j].x1-i)+min(ml[input[i][j].id],input[i][j].y1)-input[i][j].y2);
if(ll>0)fresh(an[input[i][j].id],input[i][j].x1+i-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]);
if(ll<=ll2)fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2);
}
}
if(input[i][j].x1>=i){
if(min(ml[input[i][j].id],input[i][j].y1)>input[i][j].y2){
if(ll>0)fresh(an[input[i][j].id],input[i][j].x1+i-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]);
if(ll<=ll2)fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2);
}
}
// case: contain end
if(input[i][j].x1<=i){
if(ll!=k){
if(stk[ll]>=input[i][j].x1)fresh(an[input[i][j].id],i-input[i][j].x1+1+a[stk[ll]]-input[i][j].y2);
else{
fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2+1);
if(ll2+1<k)fresh(an[input[i][j].id],i-input[i][j].x1+a[stk[ll2+1]]-input[i][j].y2+1);
}
}
if(ll){
if(stk[ll-1]>=input[i][j].x1)fresh(an[input[i][j].id],i-input[i][j].x1+1+input[i][j].y2-a[stk[ll-1]]);
else fresh(an[input[i][j].id],i+input[i][j].x1-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]+1);
}
}
if(input[i][j].x1>=i){
if(ll)fresh(an[input[i][j].id],i+input[i][j].x1-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]+1);
if(ll!=k&&ll2>=ll)fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2+1);
}
}
}
}
int BIT[SIZE];
void BIT_ins(int x,int v){for(;x<SIZE;x+=x&-x)fresh(BIT[x],v);}
int BIT_qq(int x){int res=MAX;for(;x;x-=x&-x)res=min(res,BIT[x]);return res;}
int main(){
int Q;
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
scanf("%d",&Q);
for(int i=0;i<Q;i++){
int x1,y1,x2,y2;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
in[0][x2].PB(data(x1,y1,y2,i));
in[1][n+1-x2].PB(data(n+1-x1,y1,y2,i));
rmq_query[max(x1,x2)].PB(make_pair(min(x1,x2),i));
an[i]=abs(x1-x2)+y2+1; // case: contain home
}
memset(BIT,0x7f,sizeof(BIT));
for(int i=1;i<=n;i++){
BIT_ins(n+1-i,a[i]);
for(int j=0;j<rmq_query[i].size();j++)
ml[rmq_query[i][j].second]=BIT_qq(n+1-rmq_query[i][j].first);
}
Go(in[0]);
reverse(a+1,a+n+1);
Go(in[1]);
for(int i=0;i<Q;i++)printf("%d\n",an[i]);
return 0;
}
|
478
|
A
|
Initial Bet
|
There are five people playing a game called "Generosity". Each person gives some non-zero number of coins $b$ as an initial bet. After all players make their bets of $b$ coins, the following operation is repeated for several times: a coin is passed from one player to some other player.
Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size $b$ of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins $b$ in the initial bet.
|
To solve the problem, it is important to note that during the game, the number of coins on the table can not be changed. The total number of coins on the table after a successful bid, remains unchanged. Therefore, by dividing the total number of coins on the table by the number of players, can obtain an initial rate for each. If you divide without remainder impossible, such a result can not play. Should pay attention to the fact that the initial rate of each of the players must be different from zero, hence, zero can never be the answer.
|
[
"implementation"
] | 1,100
| null |
478
|
B
|
Random Teams
|
$n$ participants of the competition were split into $m$ teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.
|
If you restate the problem in terms of graph theory, it can be formulated as follows: There is a graph consisting of n vertices and m connected components. Inside each connected component, each pair of vertices connected by an edge of the component. In other words, each connected component is a full mesh. What is the smallest and the largest number of edges which may contain such a graph? Consider the process of constructing a graph of n vertices and m connected components. To begin, assume that each of the m component contains a single peak. It remains to distribute the remaining n - m vertices so as to minimize or maximize the number of edges. Note that when adding a new vertex in the connected component of size k, the number of edges is increased by k (new vertex is connected to each of the existing one edge). Consequently, in order to minimize the number of ribs formed on each step required each time to enhance top component connected smallest size. If you act according to this strategy, after the distribution of vertices on the connected components appears component size and component size. Similarly, in order to maximize the number of edges in each step must be added to the next vertex in the component connectivity greatest dimension. If you act according to such a strategy, then a single connected component of size n - m + 1, the remaining connected components will consist of a single vertex. Knowing the number of connected components and their sizes, you can count the total number of edges. For a full mesh components consisting of k vertices, the number of edges equals. It should be remembered about the need to use a 64-bit data type to store the number of edges, which depends quadratically on the value of n.
|
[
"combinatorics",
"constructive algorithms",
"greedy",
"math"
] | 1,300
| null |
478
|
C
|
Table Decorations
|
You have $r$ red, $g$ green and $b$ blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number $t$ of tables can be decorated if we know number of balloons of each color?
Your task is to write a program that for given values $r$, $g$ and $b$ will find the maximum number $t$ of tables, that can be decorated in the required manner.
|
Consider a situation where the value max (r, g, b) - min (r, g, b) \le 1, then obviously the answer is (r+g+b)/3. We can always decorate so many tables three balloons of different colors. Obviously, the remaining amount will be less than three balls, and hence can not be used to decorate the table anyway. All the remaining cases it makes sense to reduce to the previously discussed. If there is one color, such that the number of balls that color is greater than the total number of balls for the other two colors, it is advantageous to decorate a table with two balls of one color and the ball of the remaining colors, which is greater than presently. Further it is possible in many ways to group operations and to carry out more than one operation at a time. Another solution include the fact that the response is different from (r+g+b)/3, but only if max (r, g, b) \ge 2 \cdot (r + g + b - max (r, g, b)), in which case the response r + g + b - max (r, g, b). In this case, the balls of the two most rare flowers will end earlier than the balls of one the most popular, if you decorate each table with two balls of the most popular colors.
|
[
"greedy"
] | 1,800
| null |
478
|
D
|
Red-Green Towers
|
There are $r$ red and $g$ green blocks for construction of the red-green tower. Red-green tower can be built following next rules:
- Red-green tower is consisting of some number of levels;
- Let the red-green tower consist of $n$ levels, then the first level of this tower should consist of $n$ blocks, second level — of $n - 1$ blocks, the third one — of $n - 2$ blocks, and so on — the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one;
- Each level of the red-green tower should contain blocks of the same color.
Let $h$ be the maximum possible number of levels of red-green tower, that can be built out of $r$ red and $g$ green blocks meeting the rules above. The task is to determine how many different red-green towers having $h$ levels can be built out of the available blocks.
Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower.
You are to write a program that will find the number of different red-green towers of height $h$ modulo $10^{9} + 7$.
|
To begin, you will notice that in order to build a red-green tower height h requires h(h+1)/2 cubes. Therefore, the height of the resulting tower predetermined limits never exceeds 893. This height can be determined in advance, if it is assumed that all blocks of the same color. Try to prove it yourself. Further it is possible to solve the problem using dynamic programming. Let F (t, r) - the number of ways to gather the greatest height of the tower, if collected t upper floors remained untapped r red cubes. Among the arguments of the function are no amounts remain green cubes g - can be uniquely determined from the values of t and r: g = g0 - (t(t+1)/2 - (r0-r)), where r0 and g0 - the initial number of red and green cubes, respectively. Well and further consideration should be given only two transitions: Build t + 1-th level of the red or green blocks: F (t, r) = F (t + 1, r - t) + F (t + 1, r). Obviously, the cache data in an array size of $893 \times 2 \times 105$ - not the best idea. In such a case, you can count the value of the function for all values of t from 0 to h, stored in memory, only the values for the current value of t and the previous one, from which it will depend.
|
[
"dp"
] | 2,000
| null |
478
|
E
|
Wavy numbers
|
A wavy number is such positive integer that for any digit of its decimal representation except for the first one and the last one following condition holds: the digit is either strictly larger than both its adjacent digits or strictly less than both its adjacent digits. For example, numbers $35270$, $102$, $747$, $20$ and $3$ are wavy and numbers $123$, $1000$ and $2212$ are not.
The task is to find the $k$-th \textbf{smallest} wavy number $r$ that is divisible by $n$ for the given integer values $n$ and $k$.
You are to write a program that will find the value of $r$ if it doesn't exceed $10^{14}$.
|
To solve this problem, it was necessary to note that the numbers on the undulating range of from 0 to 107 is much smaller than 107. In this case, the problem can be solved using an approach meet-in-the-middle. That is separate to solve this problem for the first seven digits of the answer, and for the last seven digits of the answer. This will require the wavy separately generate all numbers in a range from 0 to 107, starting with the increase of two adjacent numbers and similar wavy numbers which begin with the decrease of two adjacent numbers. Then for each of the first half, we can calculate rl - its residue modulo n and then determine the appropriate amount of the second half, which should be equal to the remainder of the division rr = (n-rl)mod n. For the problem was a limitation of time equal to 1.5 seconds. In fact, if we write the solution to the approach meet-in-the-middle optimally enough, then the solution will take much less time. The above author's implementation can solve a similar problem for 1 \le n, k \le 1016 for about 2.5 seconds.
|
[
"brute force",
"dfs and similar",
"meet-in-the-middle",
"sortings"
] | 2,900
| null |
479
|
A
|
Expression
|
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers $a$, $b$, $c$ on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets:
- 1+2*3=7
- 1*(2+3)=5
- 1*2*3=6
- (1+2)*3=9
Note that you can insert operation signs only between $a$ and $b$, and between $b$ and $c$, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.
It's easy to see that the maximum value that you can obtain is 9.
Your task is: given $a$, $b$ and $c$ print the maximum value that you can get.
|
In this task you have to consider several cases and choose the best one: int ans = a + b + c; ans = max(ans, (a + b) * c); ans = max(ans, a * (b + c)); ans = max(ans, a * b * c); cout << ans << endl;
|
[
"brute force",
"math"
] | 1,000
| null |
479
|
B
|
Towers
|
As you know, all the kids in Berland love playing with cubes. Little Petya has $n$ towers consisting of cubes of the same size. Tower with number $i$ consists of $a_{i}$ cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2).
The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time.
Before going to school, the boy will have time to perform no more than $k$ such operations. Petya does not want to be late for class, so you have to help him accomplish this task.
|
The task is solved greedily. In each iteration, move the cube from the tallest tower to the shortest one. To do this, each time find the position of minimum and maximum in the array of heights (in linear time).
|
[
"brute force",
"constructive algorithms",
"greedy",
"implementation",
"sortings"
] | 1,400
| null |
479
|
C
|
Exams
|
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly $n$ exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a student can take the exam for the $i$-th subject on the day number $a_{i}$. However, Valera has made an arrangement with each teacher and the teacher of the $i$-th subject allowed him to take an exam before the schedule time on day $b_{i}$ ($b_{i} < a_{i}$). Thus, Valera can take an exam for the $i$-th subject either on day $a_{i}$, or on day $b_{i}$. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number $a_{i}$.
Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.
|
The solution is again greedy. Sort the exams by increasing $a_{i}$, breaking ties by increasing $b_{i}$. Let's consider exams in this order and try to take the exams as early as possible. Take the first exams in this order on the early day ($b_{1}$). Move to the second exam. If we can take it on the day $b_{2}$ (i.e. $b_{1} \le b_{2}$), do it. Otherwise, take the second exam on the day $a_{2}$. Continue the process, keeping the day of the latest exam.
|
[
"greedy",
"sortings"
] | 1,400
| null |
479
|
D
|
Long Jumps
|
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!
However, there is no reason for disappointment, as Valery has found another ruler, its length is $l$ centimeters. The ruler already has $n$ marks, with which he can make measurements. We assume that the marks are numbered from 1 to $n$ in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance $l$ from the origin. This ruler can be repesented by an increasing sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ denotes the distance of the $i$-th mark from the origin ($a_{1} = 0$, $a_{n} = l$).
Valery believes that with a ruler he can measure the distance of $d$ centimeters, if there is a pair of integers $i$ and $j$ ($1 ≤ i ≤ j ≤ n$), such that the distance between the $i$-th and the $j$-th mark is exactly equal to $d$ (in other words, $a_{j} - a_{i} = d$).
Under the rules, the girls should be able to jump at least $x$ centimeters, and the boys should be able to jump at least $y$ ($x < y$) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances $x$ and $y$.
Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances $x$ and $y$. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.
|
It is easy to see that the answer is always 0, 1 or 2. If we can already measure both $x$ and $y$, output 0. Then try to measure both $x$ and $y$ by adding one more mark. If it was not successful, print two marks: one at $x$, other at $y$. So, how to check if the answer is 1? Consider all existing marks. Let some mark be at $r$. Try to add the new mark in each of the following positions: $r - x$, $r + x$, $r - y$, $r + y$. If it become possible to measure both $x$ and $y$, you have found the answer. It is easy to check this: if, for example, we are trying to add the mark at $r + x$, we just check if there is a mark at $r + x + y$ or $r + x - y$ (by a binary search, since the marks are sorted). Make sure that the adde marks are in $[0, L]$.
|
[
"binary search",
"greedy",
"implementation"
] | 1,700
| null |
479
|
E
|
Riding in a Lift
|
Imagine that you are in a building that has exactly $n$ floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from $1$ to $n$. Now you're on the floor number $a$. You are very bored, so you want to take the lift. Floor number $b$ has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make $k$ consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number $x$ (initially, you were on floor $a$). For another trip between floors you choose some floor with number $y$ ($y ≠ x$) and the lift travels to this floor. As you cannot visit floor $b$ with the secret lab, you decided that the distance from the current floor $x$ to the chosen $y$ must be strictly less than the distance from the current floor $x$ to floor $b$ with the secret lab. Formally, it means that the following inequation must fulfill: $|x - y| < |x - b|$. After the lift successfully transports you to floor $y$, you write down number $y$ in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of $k$ trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by $1000000007$ ($10^{9} + 7$).
|
The task is solved by a dynamic programming. State is a pair $(i, j)$, where $i$ is the number of trips made, and $j$ is the current floor. Initial state is $(0, a)$, final states are $(k, v)$, where $v$ is any floor (except $b$). It is easy to see the transitions: to calculate $dp(i, j)$, let's see what can be the previous floor. It turns out that all possible previous floors form a contiguous segment (with a hole at position $j$, because we can't visit the same floor twice in a row). So, $dp(i, j)$ is almost equal to the sum of values $dp(i - 1, t)$, where $t$ belongs to some segment $[l, r]$ (the values of $l$ and $r$ can be easily derived from the conditions from the problem statement). Using pretty standard technique called "partial sums" we can compute $dp(i, j)$ in $O(1)$, so overall complexity is $O(NK)$.
|
[
"combinatorics",
"dp"
] | 1,900
|
#include <cstdio>
#include <algorithm>
#include <ctime>
#define forn(i, n) for(int i = 0; i < int(n); i++)
const int MOD = 1000000007;
const int N = 5005;
int d[2][N], n, a, b, k;
bool read() {
if (scanf("%d %d %d %d", &n, &a, &b, &k) != 4)
return false;
a--, b--;
return true;
}
int add(int a, int b) {
int res = a + b;
while (res >= MOD) res -= MOD;
while (res < 0) res += MOD;
return res;
}
int abs(int a) {
if (a < 0) return -a;
return a;
}
void solve() {
d[0][a] = 1;
forn(it, k) {
int i = it & 1;
int nxt = i ^ 1;
forn(j, n)
d[nxt][j] = 0;
forn(j, n) {
int dv = d[i][j];
int diff = abs(j - b);
d[nxt][std::max(j - diff + 1, 0)] = add(d[nxt][std::max(j - diff + 1, 0)], dv);
d[nxt][std::min(j + diff, N - 1)] = add(d[nxt][std::min(j + diff, N - 1)], -dv);
}
forn(j, n)
if (j > 0)
d[nxt][j] = add(d[nxt][j], d[nxt][j - 1]);
forn(j, n)
d[nxt][j] = add(d[nxt][j], -d[i][j]);
}
int ans = 0;
forn(j, n)
ans = add(ans, d[k & 1][j]);
printf("%d\n", ans);
fprintf(stderr, "%d\n", ans);
fprintf(stderr, "%d\n", clock());
}
int main() {
if (!read()) throw;
solve();
}
|
480
|
D
|
Parcels
|
Jaroslav owns a small courier service. He has recently got and introduced a new system of processing parcels. Each parcel is a box, the box has its weight and strength. The system works as follows. It originally has an empty platform where you can put boxes by the following rules:
- If the platform is empty, then the box is put directly on the platform, otherwise it is put on the topmost box on the platform.
- The total weight of all boxes on the platform cannot exceed the strength of platform $S$ at any time.
- The strength of any box of the platform at any time must be no less than the total weight of the boxes that stand above.
You can take only the topmost box from the platform.
The system receives $n$ parcels, the $i$-th parcel arrives exactly at time $in_{i}$, its weight and strength are equal to $w_{i}$ and $s_{i}$, respectively. Each parcel has a value of $v_{i}$ bourles. However, to obtain this value, the system needs to give the parcel exactly at time $out_{i}$, otherwise Jaroslav will get 0 bourles for it. Thus, Jaroslav can skip any parcel and not put on the platform, formally deliver it at time $in_{i}$ and not get anything for it.
Any operation in the problem is performed instantly. This means that it is possible to make several operations of receiving and delivering parcels at the same time and in any order.
Please note that the parcel that is delivered at time $out_{i}$, immediately gets outside of the system, and the following activities taking place at the same time are made without taking it into consideration.
Since the system is very complex, and there are a lot of received parcels, Jaroslav asks you to say what maximum amount of money he can get using his system.
|
Let's make two observations. First, consider the parcels as time segments $[in_{i}, out_{i}]$. It is true that if at some moment of time both parcel $i$ and parcel $j$ are on the platform, and $i$ is higher than $j$, then $[i n_{i},o u t_{i}]\subset[i n_{j},o u t_{j}]$. Second, let's imagine that there are some parcels on the platform. It turns out that it is enough to know just a single number to be able to decide whether we can put another parcel on top of them. Let's denote this value as "residual strength". For a parcel (or a platform itself) the residual strength is it's strength minus the total weight of parcels on top of it. For a set of parcels, the residual strength is the minimum of individual residual strengths. So, we can put another parcel on top if it's weight does not exceed the residual strength. These observations lead us to a dynamic programming solution. Let the top parcel at the given moment has number $i$, and the residual strength is $rs$. Make this pair $(i, rs)$ the state of DP, because it is exactly the original problem, where the platform strength is $rs$ and there are only parcels $j$ with $[i n_{j},o u t_{j}]\subset[i n_{i},o u t_{i}]$. In $d(i, rs)$ we will store the answer to this instance of the original problem. Which transitions are there? We can choose a set of parcels $i(1), i(2), ... i(k)$ such that This choice corresponds to the following sequence of actions: first put parcel $i(1)$ on the top of $i$. This gets us to the state $i(1), min(rs - w_{i(1)}, s_{i(1)})$, so we add up the answer for this state and the cost of $i(1)$. Then we take away all parcels, including $i(1)$, and put the parcel $i(2)$ on top of $i$, and so on. As the number of states in DP is $O(NS)$, all transitions should take linear time. It can be achieved by making an inner helper DP. This give a solution in $O(N^{2}S)$. Note that for simplicity the platform can be considered as a parcel too.
|
[
"dp",
"graphs"
] | 2,600
| null |
480
|
E
|
Parking Lot
|
Petya's been bored at work and he is killing the time by watching the parking lot at the office. The parking lot looks from above like an $n × m$ table (a cell of the table corresponds to a single parking spot). Some spots in the parking lot are taken, others are empty.
Petya watches cars riding into the parking lot one by one. After a car settles down at the parking spot, Petya amuzes himself by counting what maximum square of empty spots (i.e. a square subtable) can be seen on the parking lot if we look at it from above. Also, he takes notes of the square's size (side length) in his notebook.
You task is: given the state of the parking lot at the initial moment of time and the information about where the arriving cars park, restore what Petya wrote in his notebook. It is midday, so nobody leaves the lot.
|
Let's denote the car arrivals as events. Consider the following solution (it will help to understand the author's idea): let's consider all empty square in the table. There a too many of them, but imagine that we can afford to loop through all of them. If we fix a square, we can find out when it is no longer empty: find the first event that belongs to this square. Let this event has number $x$, and the size of the square is $k$. Now we can update the answers for all events with numbers less than $x$ with a value of $k$. The model solution use the idea of Divide and Conquer. Let's make a recursive routine that takes a rectangular sub-table, bounded with $r_{1}, r_{2}, c_{1}, c_{2}$ ($r_{1} \le r_{2}, c_{1} \le c_{2}$), and a list of events that happen inside this sub-table. The purpose of the routine is to consider how maximal empty squares in this sub-table change in time, and to update the answers for some of the events. Let's assume that $c_{2} - c_{1} \le r_{2} - r_{1}$ (the opposite case is symmetric). Take the middle row $r = (r_{1} + r_{2}) / 2$. Virtually split all the squares inside the sub-table into those which lie above $r$, those which lie below $r$, and those which intersect $r$. For the first two parts, make two recursive calls, splitting the list of events as well. Now focus on the squares that intersect the row $r$. Using initial table, for each cell $(r, c)$ we can precompute the distance to the nearest taken cell in all four directions (or the distance to the border, if there is no such cell): $up(r, c)$, $down(r, c)$, $left(r, c)$ and $right(r, c)$. Using this values, build two histograms for the row $r$: the first is an array of values $up(r, c)$, where $c_{1} \le c \le c_{2}$; the second is an array of values $down(r, c)$, where $c_{1} \le c \le c_{2}$. I say histograms here, because these arrays actually can be viewed as heights of empty columns, pointing from the row $r$ upwards and downwards. Lets call the first histogram "upper", the second one - "lower". Now consider all events inside the sub-table in the order they happen. Each event changes a single value in a histogram. If after some event $x$ the maximum empty square found in the histograms has size $k$, and the next event has number $y$, we can update answers for all events with numbers $x, x + 1, ..., y - 1$ with the value of $k$. It remains to learn to find a maximum square in two histograms. It can be done by a two-pointer approach. Set both pointers to the beginning. Move the second pointer until there is such square in histograms: there is a square with side length $k$ if (minimum on the interval in the upper histogram) + (minimum on the interval in the upper histogram) - 1 >= k. When the second pointer can not be moved any more, update the answer and move the first pointer. To find the minimum in O(1), author's solution creates a queue with minimum in O(1) support. That is, the maximum square can be found in linear time. Let's try to estimate the running time. Each call of the routine (omitting inner calls) costs $O(len \cdot q)$, where $len$ is the shortest side of the sub-table, and $q$ is the number of events in it. If we draw a recursion tree, we will see that each second call $len$ decreases twice. The total cost of all operations in a single level of a recursion tree is $O(NK)$, where $K$ is the total number of events. As long as we have $O(logN)$, overall complexity is $O(NKlogN)$.
|
[
"data structures",
"divide and conquer"
] | 2,800
| null |
482
|
A
|
Diverse Permutation
|
Permutation $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers not larger than $n$. We'll denote as $n$ the length of permutation $p_{1}, p_{2}, ..., p_{n}$.
Your task is to find such permutation $p$ of length $n$, that the group of numbers $|p_{1} - p_{2}|, |p_{2} - p_{3}|, ..., |p_{n - 1} - p_{n}|$ has exactly $k$ distinct elements.
|
Let's see, what's the solution for some $k = n - 1$: 1 10 2 9 3 8 4 7 5 6 At the odd indexes we placed increasing sequence 1, 2, 3 .., at the even - decreasing sequence $n, n - 1, n - 2, ..$. First, we must get the permutation the way described above, then get first $k$ numbers from it, and then we should make all other distances be equal to 1. This solution works with $O(n)$.
|
[
"constructive algorithms",
"greedy"
] | 1,200
|
import java.math.BigInteger;
import java.util.Scanner;
import java.io.PrintWriter;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
Boolean[] used = new Boolean[n];
for (int i = 0; i < n; ++i)
used[i] = false;
int l = 0, r = n - 1;
for (int i = 0; i < k; ++i) {
used[(i & 1) == 0 ? l : r] = true;
if ((i & 1) == 0)
out.print((1 + (l++)));
else
out.print((1 + (r--)));
out.print(' ');
}
if ((k & 1) == 1) {
for (int i = 0; i < n; ++i) {
if (!used[i]) {
out.print(i + 1);
out.print(' ');
}
}
} else {
for (int i = n - 1; i >= 0; --i) {
if (!used[i]) {
out.print(i + 1);
out.print(' ');
}
}
}
out.close();
}
}
|
482
|
B
|
Interesting Array
|
We'll call an array of $n$ non-negative integers $a[1], a[2], ..., a[n]$ interesting, if it meets $m$ constraints. The $i$-th of the $m$ constraints consists of three integers $l_{i}$, $r_{i}$, $q_{i}$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$) meaning that value $a[l_{i}]\,\ \ll\,a[l_{i}+1]\,\ \vartheta_{<\,\ \cdot\,\cdot\,\ \cdot\,\ \cdot\,\ \cdot\,\ \hat{G}\,\ a[r_{i}]}$ should be equal to $q_{i}$.
Your task is to find any interesting array of $n$ elements or state that such array doesn't exist.
Expression $x&y$ means the bitwise AND of numbers $x$ and $y$. In programming languages C++, Java and Python this operation is represented as "&", in Pascal — as "and".
|
We will solve the task for every distinct bit. Now we must handle new constraint: $l[i], r[i], q[i]$. If number $q[i]$ has 1 in bit with number $pos$, then all numbers in segment $[l[i], r[i]]$ will have 1 in that bit too. To do that, we can use a standard idea of adding on a segment. Let's do two adding operation in $s[pos]$ array - in position $l[i]$ we will add $1$, and in posiotion $r[i] + 1$ - -1. Then we will calculate partial sums of array $s[pos]$, and if $s[pos][i]$ > 0 (the sum on prefix length $i + 1$), then bit at position $pos$ will be 1, otherwise - 0. After that, you can use segment tree to check satisfying constraints.
|
[
"constructive algorithms",
"data structures",
"trees"
] | 1,800
|
#include <cstdio>
#include <algorithm>
const int N = 1000 * 1000;
const int MAXBIT = 30;
int l[N], r[N], q[N], a[N], t[4 * N];
int sum[N];
inline void build(int v, int l, int r) {
if (l + 1 == r) {
t[v] = a[l];
return;
}
int mid = (l + r) >> 1;
build(v * 2, l, mid);
build(v * 2 + 1, mid, r);
t[v] = t[v * 2] & t[v * 2 + 1];
}
inline int query(int v, int l, int r, int L, int R) {
if (l == L && r == R) {
return t[v];
}
int mid = (L + R) >> 1;
int ans = (1ll << MAXBIT) - 1;
if (l < mid)
ans &= query(v * 2, l, std::min(r, mid), L, mid);
if (mid < r)
ans &= query(v * 2 + 1, std::max(l, mid), r, mid, R);
return ans;
}
int main() {
int n, m;
scanf("%d %d\n", &n, &m);
for(int i = 0; i < m; i++) {
scanf("%d %d %d\n", &l[i], &r[i], &q[i]);
l[i]--;
}
for(int bit = 0; bit <= MAXBIT; bit++) {
for(int i = 0; i < n; i++) sum[i] = 0;
for(int i = 0; i < m; i++) {
if ((q[i] >> bit) & 1) {
sum[l[i]]++;
sum[r[i]]--;
}
}
for(int i = 0; i < n; i++) {
if (i > 0) sum[i] += sum[i - 1];
if (sum[i] > 0) {
a[i] |= (1 << bit);
}
}
}
build(1, 0, n);
for(int i = 0; i < m; i++) {
if (query(1, l[i], r[i], 0, n) != q[i]) {
puts("NO");
return 0;
}
}
puts("YES");
for(int i = 0; i < n; i++) {
if (i) printf(" ");
printf("%d", a[i]);
}
puts("");
}
|
482
|
C
|
Game with Strings
|
You play the game with your friend. The description of this game is listed below.
Your friend creates $n$ distinct strings of the same length $m$ and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the $n$ strings equals $\textstyle{\frac{1}{n}}$. You want to guess which string was chosen by your friend.
In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: «What character stands on position $pos$ in the string you have chosen?» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions.
You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
|
Let's handle all string pairs and calculate the $mask$ mask, which will have 1-bits only in positions in which that strings have the same characters. In other words, we could not distinguish these strings using positions with submask of mask $mask$, then we must add in $d[mask]$ 1-bits in positions $i$ and $j$. This way in $d[mask]$ we store mask of strings, which we could not distinguish using only positions given in mask $mask$. Using information described above, we can easily calculate this dynamics. Now, when we have array $d$ calculated, it is not hard to calculate the answer. Let's handle some mask $mask$. Now we should try to make one more question in position $pos$, which is equal to adding one more 1-bit in $mask$ in position $pos$. After that we may guess some strings, they are 1-bits in mask s = d[mask] ^ d[mask | (1 << pos)]. Then you have to calculate number of bits in $s$ quickly and update the answer.
|
[
"bitmasks",
"dp",
"probabilities"
] | 2,600
|
#include <cstdio>
#include <iostream>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <ctime>
using namespace std;
const int N = 20;
const int M = 150;
int n;
char s[M][N + 10];
typedef long long li;
typedef long double ld;
li d[(1 << N)];
inline bool has(li mask, int pos) {
return (mask >> pos) & 1;
}
ld prob[N + 10];
ld totalGuessed[N + 10];
int main() {
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%s", s[i]);
}
int m = strlen(s[0]);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if (i == j) continue;
int same = 0;
for(int k = 0; k < m; k++) {
if (s[i][k] == s[j][k]) same |= (1 << k);
}
d[same] |= (1LL << i);
}
}
for(int mask = (1 << m) - 1; mask; mask--) {
for(int i = 0; i < m; i++) {
if (has(mask, i)) {
d[mask ^ (1 << i)] |= d[mask];
}
}
}
long double ans = 0;
for(int mask = 0; mask < (1 << m); mask++) {
int moves = __builtin_popcount(mask) + 1;
for(int i = 0; i < m; i++) {
if (!has(mask, i)) {
li res = d[mask] ^ d[mask ^ (1 << i)];
if (res == 0) continue;
int cntGuessed = __builtin_popcountll(res);
totalGuessed[moves] += cntGuessed;
}
}
}
for(int i = 1; i <= m; i++) {
ld val = totalGuessed[i] * i;
for(int j = 0; j < i - 1; j++)
val *= ld(i - 1 - j) / ld(m - j);
ans += val / ld(m - i + 1);
}
ans /= ld(n);
cerr << clock() << endl;
cout << fixed << setprecision(15) << ans << endl;
}
|
482
|
D
|
Random Function and Tree
|
You have a rooted tree consisting of $n$ vertices. Let's number them with integers from $1$ to $n$ inclusive. The root of the tree is the vertex $1$. For each $i > 1$ direct parent of the vertex $i$ is $p_{i}$. We say that vertex $i$ is child for its direct parent $p_{i}$.
You have initially painted all the vertices with red color. You like to repaint some vertices of the tree. To perform painting you use the function paint that you call with the root of the tree as an argument. Here is the pseudocode of this function:
\begin{verbatim}
count = 0 // global integer variable
rnd() { // this function is used in paint code
return 0 or 1 equiprobably
}
paint(s) {
if (count is even) then paint s with white color
else paint s with black color
count = count + 1
if rnd() = 1 then children = [array of vertex s children in ascending order of their numbers]
else children = [array of vertex s children in descending order of their numbers]
for child in children { // iterating over children array
if rnd() = 1 then paint(child) // calling paint recursively
}
}
\end{verbatim}
As a result of this function, some vertices may change their colors to white or black and some of them may remain red.
Your task is to determine the number of distinct possible colorings of the vertices of the tree. We will assume that the coloring is possible if there is a nonzero probability to get this coloring with a single call of $paint(1)$. We assume that the colorings are different if there is a pair of vertices that are painted with different colors in these colorings. Since the required number may be very large, find its remainder of division by $1000000007$ ($10^{9} + 7$).
|
Let's calculate $d[v][p]$ dynamics - the answer for vertex $v$ with size of parity $p$. At first step to calculate this dynamic for vertex $v$ we should count all different paintings of a subtree visiting all children in increasing order of their numbers. By multiplying this number by 2 we will get paintings visiting children in decreasing order. Now some paintings may count twice. To fix that, let's have a look on a some subtree of a vertex $v$. Consider all the parities of children subtrees visited by our function (0 or 1). First thing to note is that among these parities exist two different values, the subtree will have different paintings with different ordering (you can prove it yourself). Otherwise, all our children sizes have the same parity. If all sizes are even, this subtree will be counted twice. Otherwise, if sizes are odd, we are interested only in odd count of visited subtrees. This way, we must subtract from our dynamic the number of ways to paint any number of children with even subtree sizes and odd number of children with odd subtree sizes.
|
[
"combinatorics",
"dp",
"trees"
] | 2,700
|
#define _USE_MATH_DEFINES
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <list>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
#include <queue>
#include <stack>
#include <bitset>
#include <cassert>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long li;
typedef long double ld;
typedef pair<ld, ld> pt;
#define all(a) a.begin(), a.end()
#define pb push_back
#define mp make_pair
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define ft first
#define sc second
#define x first
#define y second
const int INF = 1e9;
const ld EPS = 1e-10;
const int N = 100005;
int n;
vector<int> g[N];
bool read()
{
if (!(cin >> n))
return false;
forn (i, n - 1)
{
int p;
cin >> p;
p--;
g[p].pb(i + 1);
}
return true;
}
int mod = INF + 7;
li dp[N][2];
li dp2[2][2];
li calcdp(int v, int p)
{
if (g[v].size() == 0)
dp[v][1] = 1, dp[v][0] = 0;
if (dp[v][p] != -1)
return dp[v][p];
dp[v][1] = 1, dp[v][0] = 0;
forn (i, g[v].size())
{
li ndp0 = (dp[v][1] * calcdp(g[v][i], 1) + dp[v][0] * calcdp(g[v][i], 0)) % mod;
li ndp1 = (dp[v][0] * calcdp(g[v][i], 1) + dp[v][1] * calcdp(g[v][i], 0)) % mod;
dp[v][0] = (dp[v][0] + ndp0) % mod;
dp[v][1] = (dp[v][1] + ndp1) % mod;
}
dp[v][0] = (dp[v][0] * 2) % mod;
dp[v][1] = (dp[v][1] * 2) % mod;
dp2[0][0] = dp2[1][0] = 1;
dp2[0][1] = dp2[1][1] = 0;
forn (i, g[v].size())
{
li lval = dp2[0][1];
dp2[0][1] = (dp2[0][1] + calcdp(g[v][i], 0) * dp2[0][0]) % mod;
dp2[0][0] = (dp2[0][0] + calcdp(g[v][i], 0) * lval) % mod;
lval = dp2[1][1];
dp2[1][1] = (dp2[1][1] + calcdp(g[v][i], 1) * dp2[1][0]) % mod;
dp2[1][0] = (dp2[1][0] + calcdp(g[v][i], 1) * lval) % mod;
}
dp[v][1] = ((dp[v][1] - dp2[0][0] - dp2[0][1]) % mod + mod) % mod;
dp[v][0] = ((dp[v][0] - dp2[1][1]) % mod + mod) % mod;
return dp[v][p];
}
void solve()
{
forn (i, N)
forn (j, 2)
dp[i][j] = -1;
cout << (calcdp(0, 0) + calcdp(0, 1)) % mod << endl;
}
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
while(read())
solve();
return 0;
}
|
482
|
E
|
ELCA
|
You have a root tree containing $n$ vertexes. Let's number the tree vertexes with integers from $1$ to $n$. The tree root is in the vertex $1$.
Each vertex (except fot the tree root) $v$ has a direct ancestor $p_{v}$. Also each vertex $v$ has its integer value $s_{v}$.
Your task is to perform following queries:
- \textbf{P} $v$ $u$ ($u ≠ v$). If $u$ isn't in subtree of $v$, you must perform the assignment $p_{v} = u$. Otherwise you must perform assignment $p_{u} = v$. Note that after this query the graph continues to be a tree consisting of $n$ vertexes.
- \textbf{V} $v$ $t$. Perform assignment $s_{v} = t$.
Your task is following. Before starting performing queries and after each query you have to calculate expected value written on the lowest common ancestor of two equiprobably selected vertices $i$ and $j$. Here lowest common ancestor of $i$ and $j$ is the deepest vertex that lies on the both of the path from the root to vertex $i$ and the path from the root to vertex $j$. Please note that the vertices $i$ and $j$ can be the same (in this case their lowest common ancestor coincides with them).
|
Let's split all $M$ requests in $\sqrt{M}$ blocks containing $\sqrt{M}$ requests each. Every block will be processed following way: First using dfs we need to calculate $p a t h_{v}=\sum\left(s i z e_{p_{u}}-s i z e_{u}\right)\cdot V_{p_{u}}$ for every vertex $v$, where $u$ is every ancestor of $v$, $size_{i}$ - size of subtree of vertex $i$, including itself. This value shows how will the answer change after removing or adding vertex $v$ as child to any other vertex, furthermore, answer will change exactly by $path_{v} \cdot size_{v}$ (decreasing or increasing). Then we will calculate $ch_{v}$ the same way - the number of all possible vertex pairs, which have LCA in vertex $v$. This value shows how the answer changes after changing $V_{v}$ - if $V_{v}$ changes by $dV_{v}$, answer changes by $ch_{v} \cdot dV_{v}$. Then mark all vertexes, which occur in our block at least once (in worst case their number is $2{\sqrt{M}}$). Next, mark every vertex being LCA of some pair of already marked vertexes, using DFS. We can prove that final number of these vertexes is at most $\mathbb{K}{\sqrt{M}}-1$. After all this we got 'compressed' tree, containing only needed vertexes. Parent of vertex $i$ in compressed tree we will call vertex numbered $P_{i}$. On the image above example of this 'compression' way is given. Vertexes colored red are vertexes in request block, blue - vertexes marked after LCA, dotted line - $P_{v} \rightarrow v$ edges in compressed tree. On such compressed tree we need to calculate one new value $C_{v}$ for every vertex $v$ - the size of a vertex, lying on a way from $P_{v}$ to $v$ after $P_{v}$ on main (non-compressed) tree (son of a $P_{v}$ vertex in main tree). Now we should process request on changing parent of vertex $v$ from $p_{v}$ to $u$ on a compressed tree. The answer will change by $path_{v} \cdot size_{v}$. Now for every vertex $i$, lying on a way from root to $P_{v}$ vertex, two values will change: $size_{i}$ will be decreased by $size_{v}$, but $ch_{i}$ will be decreased by $size_{v} \cdot (size_{i} - C_{t})$, ($P_{t} = i$), but $path_{i}$ will stay unchanged. For every other vertex $j$ only $path_{j}$ will be changed: it will be decreased by ${\it3}^{\prime}\tilde{\chi}\theta_{\bar{\upsilon}}\cdot\left.\right.\left\{\left._{\mathrm{Cd}}\left(\upsilon_{\mathrm{1}}\right)\right\}$. After that, we got compressed subtree where subtree of a vertex $v$ is missing. Next, doing the same way as above, all values are changed considering that $v$ (and all it's subtree) is a children of a vertex $u$. Do not forget to change $C_{v}$ too. Let's see, how the value-changing request of a vertex $v$ is to be processed. As described above, the answer will be changed by $ch_{v} \cdot dV_{v}$. For every vertex $i$ lying in vertex $v$ subtree only $path_{i}$ will be changed (it could be easy done using $C_{to}$ values), all other values stay unchanged. This solution has $O(N{\sqrt{M}}+M{\sqrt{M}})$ complexity, but in $N = M$ case it has to be $O(N{\sqrt{N}})$.
|
[
"data structures",
"trees"
] | 3,200
|
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <iomanip>
using namespace std;
#define forn(i,n) for (int i = 0; i < int(n); ++i)
#define sz(a) int(a.size())
#define pb push_back
#define all(a) a.begin(),a.end()
#define mp make_pair
typedef long long li;
typedef long double ld;
typedef pair<int,int> pt;
#define ft first
#define sc second
const int N = 100105;
li n2;
int n, m;
int p[N], V[N];
pair <char, pt> req[N];
vector <int> g[N];
bool marked[N], query[N];
int szv;
int v[N];
int dfs(int v) {
int res = query[v];
for (int i = 0; i < sz(g[v]); ++i) {
int cur = dfs(g[v][i]);
if (cur && res)
marked[v] = true;
res += cur;
}
return res;
}
inline void get_lcas() {
int szq = 0;
forn(i, n) {
marked[i] = query[i];
szq += query[i];
}
dfs(0);
szv = 0;
forn(i, n)
if (marked[i])
v[szv++] = i;
assert(szq * 2 - 1 >= szv);
}
inline bool read() {
if (scanf("%d", &n) != 1)
return false;
n2 = li(n) * n;
forn(i, n - 1) {
scanf("%d", &p[i + 1]);
p[i + 1]--;
}
forn(i, n)
scanf("%d", &V[i]);
scanf("%d", &m);
char buf[2];
int a, b;
forn(i, m) {
scanf("%s %d %d", buf, &a, &b);
req[i] = mp(buf[0], mp(a, b));
}
return true;
}
int tin[N], tout[N], T;
inline bool is_ancestor(int a, int b) {
return tin[a] <= tin[b] && tout[b] <= tout[a];
}
li sum, path[N], ch[N];
int sz[N];
void calcsz(int v) {
tin[v] = T++;
sz[v] = 1;
ch[v] = 0;
forn(i, sz(g[v])) {
int to = g[v][i];
calcsz(to);
ch[v] += li(sz[v]) * sz[to];
sum += 2 * li(sz[v]) * sz[to] * V[v];
sz[v] += sz[to];
}
tout[v] = T++;
}
void calcpath(int v, int p) {
if (v != p)
path[v] = path[p] + li(sz[p] - sz[v]) * V[p];
else
path[v] = 0;
forn(i, sz(g[v]))
calcpath(g[v][i], v);
}
inline void rebuild() {
sum = 0;
forn(i, n)
sum += V[i];
T = 0;
forn(i, n) {
tin[i] = tout[i] = -1;
g[i].clear();
}
forn(i, n - 1)
g[ p[i + 1] ].pb(i + 1);
calcsz(0);
calcpath(0, 0);
}
vector <int> G[N];
int P[N], C[N];
int d[N];
int szsons;
pt sons[N];
inline void calcps() {
forn(i, szv) {
G[ v[i] ].clear();
P[ v[i] ] = -1;
C[ v[i] ] = 0;
}
forn(i, szv)
d[i] = 0;
forn(i, szv)
forn(j, szv)
if (i != j && is_ancestor(v[i], v[j]))
d[j]++;
forn(_, szv) {
int i = -1;
forn(j, szv)
if (d[j] == 0)
i = j;
d[i] = -1;
assert(i != -1);
forn(j, szv)
if (i != j && is_ancestor(v[i], v[j])) {
if (d[j] == 1) {
P[ v[j] ] = v[i];
G[ v[i] ].pb(v[j]);
}
d[j]--;
}
szsons = sz(G[ v[i] ]);
forn(j, sz(G[ v[i] ])) {
int to = G[ v[i] ][j];
sons[j] = mp(tin[to], to);
}
sort(sons, sons + szsons);
int pos = 0;
forn(j, sz(g[ v[i] ])) {
int to = g[ v[i] ][j];
while (pos < szsons && is_ancestor(to, sons[pos].sc))
C[ sons[pos++].sc ] = sz[to];
}
}
}
void dfspath(int v, li delta) {
path[v] += delta;
forn(i, sz(G[v]))
dfspath(G[v][i], delta);
}
inline void updpath(int v, int mul) {
int cur = v;
while (P[cur] != -1) {
li delta = mul * li(sz[v]) * V[ P[cur] ];
forn(i, sz(G[ P[cur] ])) {
int to = G[ P[cur] ][i];
if (to != cur)
dfspath(to, delta);
}
int c = C[cur];
if (cur != v)
C[cur] += mul * sz[v];
cur = P[cur];
ch[cur] += mul * li(sz[v]) * (sz[cur] - c);
sz[cur] += mul * sz[v];
}
}
bool visit(int v, int what) {
int cur = what;
while (cur != -1) {
if (cur == v)
return true;
cur = P[cur];
}
return false;
}
inline void output() {
//cerr << sum << " ";
printf("%0.9lf\n", double(sum) / double(n2));
}
inline void solve() {
int bl = 0;
while (bl * bl < m)
bl++;
rebuild();
output();
for (int left = 0; left < m; left += bl) {
rebuild();
forn(i, n)
query[i] = false;
forn(offs, bl) {
int i = left + offs;
if (i >= m)
break;
query[req[i].sc.ft - 1] = true;
if (req[i].ft == 'P')
query[req[i].sc.sc - 1] = true;
}
get_lcas();
calcps();
forn(offs, bl) {
int i = left + offs;
if (i >= m)
break;
if (req[i].ft == 'P') {
int v = req[i].sc.ft, u = req[i].sc.sc;
--v, --u;
if (visit(v, u))
swap(v, u);
sum -= 2 * path[v] * sz[v];
updpath(v, -1);
C[v] = 0;
dfspath(v, -path[v]);
G[ P[v] ].erase(find(all(G[ P[v] ]), v));
P[v] = u;
p[v] = u;
dfspath(v, path[u] + li(sz[u]) * V[u]);
G[ P[v] ].pb(v);
sum += 2 * path[v] * sz[v];
updpath(v, +1);
C[v] = sz[v];
}
if (req[i].ft == 'V') {
int v = req[i].sc.ft, val = req[i].sc.sc;
--v;
int dv = val - V[v];
sum += 2 * ch[v] * dv + dv;
forn(i, sz(G[v])) {
int& to = G[v][i];
dfspath(to, li(dv) * (sz[v] - C[to]));
}
V[v] = val;
}
output();
}
}
}
int main() {
read();
solve();
return 0;
}
|
483
|
A
|
Counterexample
|
Your friend has recently learned about coprime numbers. A pair of numbers ${a, b}$ is called coprime if the maximum number that divides both $a$ and $b$ is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair $(a, b)$ is coprime and the pair $(b, c)$ is coprime, then the pair $(a, c)$ is coprime.
You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers $(a, b, c)$, for which the statement is false, and the numbers meet the condition $l ≤ a < b < c ≤ r$.
More specifically, you need to find three numbers $(a, b, c)$, such that $l ≤ a < b < c ≤ r$, pairs $(a, b)$ and $(b, c)$ are coprime, and pair $(a, c)$ is not coprime.
|
This problem has two possible solutions: Let's handle all possible triples and check every of them for being a counterexample. This solution works with asymptotics $O(n^{3}logA)$ Handle only a few cases. It could be done like this:
|
[
"brute force",
"implementation",
"math",
"number theory"
] | 1,100
|
#include <iostream>
using namespace std;
int main() {
long long l, r;
cin >> l >> r;
if (r - l + 1 < 3) {
cout << -1 << endl;
return 0;
}
if (l % 2 == 0) {
cout << l << ' ' << l + 1 << ' ' << l + 2 << endl;
return 0;
}
if (r - l + 1 > 3){
cout << l + 1 << ' ' << l + 2 << ' ' << l + 3 << endl;
return 0;
}
cout << -1 << endl;
}
|
483
|
B
|
Friends and Presents
|
You have two friends. You want to present each of them several positive integers. You want to present $cnt_{1}$ numbers to the first friend and $cnt_{2}$ numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In addition, the first friend does not like the numbers that are divisible without remainder by prime number $x$. The second one does not like the numbers that are divisible without remainder by prime number $y$. Of course, you're not going to present your friends numbers they don't like.
Your task is to find such minimum number $v$, that you can form presents using numbers from a set $1, 2, ..., v$. Of course you may choose not to present some numbers at all.
A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.
|
Jury's solution is using binary search. First, you can notice that if you can make presents with numbers $1, 2, ..., v$ then you can make presents with numbers $1, 2, ..., v, v + 1$ too. Let $f(v)$ be the function returning true or false: is it right, that you can make presents with numbers $1, 2, ..., v$. Let $f_{1}$ be the number of numbers divisible by $x$, $f_{2}$ - the number of numbers divisible by $y$, and $both$ - number of numbers divisible by $x$ and by $y$ (as soon as $x$ and $y$ are primes, it is equivalent to divisibility by $x \cdot y$). Then to first friend at first we shold give $f_{2} - both$ numbers, and to second friend $f_{1} - both$ numbers. Then we must check, could we give all other numbers divisible neither by $x$ nor by $y$. This solution works with $O(\log n)$
|
[
"binary search",
"math"
] | 1,800
|
#include <cstdio>
using namespace std;
typedef long long li;
int cnt[2], v[2];
inline bool f(li val) {
li f[] = {val / v[0], val / v[1]};
li l = v[0] * 1ll * v[1];
li both = val / l;
li other = val - f[0] - f[1] + both;
f[0] -= both;
f[1] -= both;
li tcnt[] = {cnt[0] - f[1], cnt[1] - f[0]};
if (tcnt[0] < 0) tcnt[0] = 0;
if (tcnt[1] < 0) tcnt[1] = 0;
return (tcnt[0] + tcnt[1] <= other);
}
int main() {
scanf("%d %d %d %d", &cnt[0], &cnt[1], &v[0], &v[1]);
li l = 0;
li r = li(1e18);
while (r - l > 1) {
li mid = (l + r) >> 1;
if (f(mid)) {
r = mid;
} else {
l = mid;
}
}
printf("%I64d\n", r);
}
|
484
|
A
|
Bits
|
Let's denote as ${\mathrm{popcount}}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer $x$.
You are given multiple queries consisting of pairs of integers $l$ and $r$. For each query, find the $x$, such that $l ≤ x ≤ r$, and ${\mathsf{P o P c o u n t}}(x)$ is maximum possible. If there are multiple such numbers find the smallest of them.
|
Let us define function $f(L, R)$, that gives answer to the query. It looks follows: if $L = R$ then $f(L, R) = L$; else if $2^{b} \le L$, where $b$ - maximum integer such $2^{b} \le R$, then $f(L, R) = f(L - 2^{b}, R - 2^{b}) + 2^{b}$; else if $2^{b + 1} - 1 \le R$ then $f(L, R) = 2^{b + 1} - 1$; else $f(L, R) = 2^{b} - 1$. Total complexity is $O(logR)$ per query.
|
[
"bitmasks",
"constructive algorithms"
] | 1,700
| null |
484
|
B
|
Maximum Value
|
You are given a sequence $a$ consisting of $n$ integers. Find the maximum possible value of $a_{i}{\mathrm{~mod~}}a_{j}$ (integer remainder of $a_{i}$ divided by $a_{j}$), where $1 ≤ i, j ≤ n$ and $a_{i} ≥ a_{j}$.
|
Let us iterate over all different $a_{j}$. Since we need to maximize $a_{i}{\mathrm{~mod~}}a_{j}$, then iterate all integer $x$ (such $x$ divisible by $a_{j}$) in range from $2a_{j}$ to $M$, where $M$ - doubled maximum value of the sequence. For each such $x$ we need to find maximum $a_{i}$, such $a_{i} < x$. Limits for numbers allow to do this in time $O(1)$ with an array. After that, update answer by value $a_{i}{\mathrm{~mod~}}a_{j}$. Total time complexity is $O(nlogn + MlogM)$.
|
[
"binary search",
"math",
"sortings",
"two pointers"
] | 2,100
| null |
484
|
C
|
Strange Sorting
|
How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: \underline{$d$-sorting}. This sorting is applied to the strings of length at least $d$, where $d$ is some positive integer. The characters of the string are sorted in following manner: first come all the 0-th characters of the initial string, then the 1-st ones, then the 2-nd ones and so on, in the end go all the $(d - 1)$-th characters of the initial string. By the $i$-th characters we mean all the character whose positions are exactly $i$ modulo $d$. If two characters stand on the positions with the same remainder of integer division by $d$, their relative order after the sorting shouldn't be changed. The string is zero-indexed. For example, for string 'qwerty':
Its 1-sorting is the string 'qwerty' (all characters stand on 0 positions),
Its 2-sorting is the string 'qetwry' (characters 'q', 'e' and 't' stand on 0 positions and characters 'w', 'r' and 'y' are on 1 positions),
Its 3-sorting is the string 'qrwtey' (characters 'q' and 'r' stand on 0 positions, characters 'w' and 't' stand on 1 positions and characters 'e' and 'y' stand on 2 positions),
Its 4-sorting is the string 'qtwyer',
Its 5-sorting is the string 'qywert'.
You are given string $S$ of length $n$ and $m$ \underline{shuffling} operations of this string. Each \underline{shuffling} operation accepts two integer arguments $k$ and $d$ and transforms string $S$ as follows. For each $i$ from $0$ to $n - k$ in the increasing order we apply the operation of $d$-sorting to the substring $S[i..i + k - 1]$. Here $S[a..b]$ represents a substring that consists of characters on positions from $a$ to $b$ inclusive.
After each \underline{shuffling} operation you need to print string $S$.
|
Note, that $d$-sorting is just a permutation (call it $P$), because it does not depends on characters in string. Look at shuffling operation in different way: instead of going to the next substring and sort it, we will shift string to one character left. It remains to understand that shift of string the permutation too (call it $C$). Now its clear, we need to calculate $S \cdot P \cdot C \cdot P \cdot C... = S \cdot (P \cdot C)^{n - k + 1}$. And after that shift string for $k - 1$ character to the left for making answer to the shuffling operation. Here we use the multiplication of permutations. Since they are associative, that we can use binary algorithm to calculate $(P \cdot C)^{n - k + 1}$. Total time complexity is $O(nmlogn)$.
|
[
"implementation",
"math"
] | 2,600
| null |
484
|
D
|
Kindergarten
|
In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's \underline{sociability} is the maximum difference of charisma of two children in the group (in particular, if the group consists of one child, its sociability equals a zero).
The teacher wants to divide the children into some number of groups in such way that the total \underline{sociability} of the groups is maximum. Help him find this value.
|
Let us note, that in optimal answer any segment that making a group contains their minimum and maximum values on borders. Otherwise it will be better to split this segment to two other segments. Another note that is every segment in optimal solution is strictly monotonic (increasing or decreasing). Paying attention to the interesting points in sequence which making local maximums (i. e. $a_{i - 1} < a_{i} > a_{i + 1}$), local minimums ($a_{i - 1} > a_{i} < a_{i + 1}$), and point adjacent to them. Solve the problem by dynamic programming: $D_{i}$ is the answer in the prefix $i$. To calculate $D_{i}$ we need to look at no more than three previous interesting points and to previous $D_{i - 1}$. Total time complexity is $O(n)$.
|
[
"data structures",
"dp",
"greedy"
] | 2,400
| null |
484
|
E
|
Sign on Fence
|
Bizon the Champion has recently finished painting his wood fence. The fence consists of a sequence of $n$ panels of $1$ meter width and of arbitrary height. The $i$-th panel's height is $h_{i}$ meters. The adjacent planks follow without a gap between them.
After Bizon painted the fence he decided to put a "for sale" sign on it. The sign will be drawn on a rectangular piece of paper and placed on the fence so that the sides of the sign are parallel to the fence panels and are also aligned with the edges of some panels. Bizon the Champion introduced the following constraints for the sign position:
- The width of the sign should be exactly $w$ meters.
- The sign must fit into the segment of the fence from the $l$-th to the $r$-th panels, inclusive (also, it can't exceed the fence's bound in vertical direction).
The sign will be really pretty, So Bizon the Champion wants the sign's height to be as large as possible.
You are given the description of the fence and several queries for placing sign. For each query print the maximum possible height of the sign that can be placed on the corresponding segment of the fence with the given fixed width of the sign.
|
Let us note that we can use binary search to find answer to the one query. Suppose at some moment was fixed height $h$ and need to know will fit the rectangle with width $w$ and height $h$ to the segment of fence from $l$-th to $r$-th panel. Let us build data structure that can answer to this question. This will be persistent segment tree with unusual function inside: maximum number of consecutive ones in segment ($maxOnes$). In leaves of segment tree will be only numbers 0 and 1. To calculate this function need to know some other values, specifically: $len$ - length of the segment in vertex of segment tree, $prefOnes$ - length of prefix that consists only of ones, $sufOnes$ - length of the suffix consist only of ones. These functions are computed as follows: $maxOnes$ is equal to $max(maxOnes(Left), maxOnes(Right), sufOnes(Left) + prefOnes(Right))$; $prefOnes$ equals $prefOnes(Right) + len(Left)$ in case of $len(Left) = prefOnes(Left)$, and $prefOnes(Left)$ otherwise; $sufOnes$ equals $sufOnes(Left) + len(Right)$ in case of $len(Right) = sufOnes(Right)$, and $sufOnes(Right)$ otherwise; $len = len(left) + len(Right)$; $Left$ and $Right$ - it is left and right sons of vertex in segment tree. As mentioned above, tree must be persistent, and it must be built as follows. First, builded empty tree of zeros. Next in position of highest plank need to put 1. The same doing for planks in decreasing order. For example if fence described with sequence $[2, 5, 5, 1, 3]$ then bottom of segment tree will changed as follows: $[0, 0, 0, 0, 0]$ -> $[0, 1, 0, 0, 0]$ -> $[0, 1, 1, 0, 0]$ -> $[0, 1, 1, 0, 1]$ -> $[1, 1, 1, 0, 1]$ -> $[1, 1, 1, 1, 1]$. And we need to remember for all $h_{i}$ their version of tree. Now to answer the question we need to make query in our segment tree (that corresponding to height $h$) on segment $[l, r]$. If $maxOnes$ form this query less than $w$, then rectangle impossible to put (otherwise possible). Building of tree will take $O(nlogn)$ time and memory. Time complexity to the one query will take $O(log^{2}n)$ time.
|
[
"binary search",
"constructive algorithms",
"data structures"
] | 2,500
| null |
485
|
A
|
Factory
|
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were $x$ details in the factory storage, then by the end of the day the factory has to produce $x\ {\mathrm{mod}}\ m$ (remainder after dividing $x$ by $m$) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory.
The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by $m$).
Given the number of details $a$ on the first day and number $m$ check if the production stops at some moment.
|
Production will stops iff exists integer $K \ge 0$ such $a \cdot 2^{K}$ is divisible by $m$. From this fact follows that $K$ maximum will be about $O(log_{2}(m))$. So if we modeling some, for example, 20 days and production does not stop, then it will never stop and answer is "No". Otherwise answer is "Yes".
|
[
"implementation",
"math",
"matrices"
] | 1,400
| null |
485
|
B
|
Valuable Resources
|
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.
Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square.
Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.
|
Let us find minimum length needed to cover points by $Ox$. It is $Maximum(x_{i}) - Minumum(x_{i})$. The same in $Oy$ - $Maximum(y_{i}) - Minumum(y_{i})$. Since we need a square city to cover all the mines, then we need to set length of this square to the maximum from those two values.
|
[
"brute force",
"greedy"
] | 1,300
| null |
486
|
A
|
Calculating Function
|
For a positive integer $n$ let's define a function $f$:
$f(n) = - 1 + 2 - 3 + .. + ( - 1)^{n}n$
Your task is to calculate $f(n)$ for a given integer $n$.
|
If $n$ is even, then the answer is $n / 2$, otherwise the answer is $(n - 1) / 2 - n$ = $- (n + 1) / 2$.
|
[
"implementation",
"math"
] | 800
| null |
486
|
B
|
OR in Matrix
|
Let's define logical $OR$ as an operation on two logical values (i. e. values that belong to the set ${0, 1}$) that is equal to $1$ if either or both of the logical values is set to $1$, otherwise it is $0$. We can define logical $OR$ of three or more logical values in the same manner:
$a_{1}\,\mathrm{OR}\,a_{2}\,\mathrm{OR}\dots\dots\mathrm{OR}\,a_{k}$ where $a_{i}\in\{0,1\}$ is equal to $1$ if some $a_{i} = 1$, otherwise it is equal to $0$.
Nam has a matrix $A$ consisting of $m$ rows and $n$ columns. The rows are numbered from $1$ to $m$, columns are numbered from $1$ to $n$. Element at row $i$ ($1 ≤ i ≤ m$) and column $j$ ($1 ≤ j ≤ n$) is denoted as $A_{ij}$. All elements of $A$ are either 0 or 1. From matrix $A$, Nam creates another matrix $B$ of the same size using formula:
$B_{i j}=A_{i1}\mathrm{OR}\,A_{i2}\mathrm{OR}\ldots\mathrm{OR}\,A_{i n}\mathrm{OR}\,A_{1j}\mathrm{OR}\,A_{2j}\mathrm{OR}\ldots\mathrm{oR}\,A_{m j}$.
($B_{ij}$ is $OR$ of all elements in row $i$ and column $j$ of matrix $A$)
Nam gives you matrix $B$ and challenges you to guess matrix $A$. Although Nam is smart, he could probably make a mistake while calculating matrix $B$, since size of $A$ can be large.
|
Hint of this problem is presented in its statement. "$a_{1}\,\mathrm{OR}\,a_{2}\,\mathrm{OR}\dots\dots\mathrm{OR}\,a_{k}$ where $a_{i}\in\{0,1\}$ is equal to $1$ if some $a_{i} = 1$, otherwise it is equal to $0$." To solve this problem, do 3 following steps: Complexity: We can implement this algorithm in $O(m * n)$, but it's not neccesary since $1 \le m, n \le 100$.
|
[
"greedy",
"hashing",
"implementation"
] | 1,300
| null |
486
|
C
|
Palindrome Transformation
|
Nam is playing with a string on his computer. The string consists of $n$ lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that cursor is at position $i$ ($1 ≤ i ≤ n$, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position $i - 1$ if $i > 1$ or to the end of the string (i. e. position $n$) otherwise. The same holds when he presses the right arrow key (if $i = n$, the cursor appears at the beginning of the string).
When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.
Initially, the text cursor is at position $p$.
Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?
|
Assuming that cursor's position is in the first half of string($i.e$ $1 \le p \le n / 2$) (if it's not, just reverse the string, and change $p$ to $n - p + 1$, then the answer will not change). It is not hard to see that, in optimal solution, we only need to move our cusor in the first half of the string only, and the number of "turn" is at most once. Therefore, we have below algorithm: Find the largest index $r$ before $p$ in the first half of the string ($p \le r \le n / 2$) such that $s_{r}$ different to $s_{n - r + 1}$. ($s_{i}$ denote $i_{th}$ character of our input string $s$) Find the smallest index $l$ after $p$ ($1 \le l \le p$) such that $s_{l}$ different to $s_{n - l + 1}$. In optimal solution, we move our cusor from $p$ to $l$ and then from $l$ to $r$, or move from $p$ to $r$ and then from $r$ to $l$. While moving, we also change character of string simultaneously (if needed) (by press up/down arrow keys). Be careful with some corner case(for example, does'nt exist such $l$ or $r$ discribed above). Complexity: $O(n)$.
|
[
"brute force",
"greedy",
"implementation"
] | 1,700
| null |
486
|
D
|
Valid Sets
|
As you know, an undirected connected graph with $n$ nodes and $n - 1$ edges is called a \underline{tree}. You are given an integer $d$ and a tree consisting of $n$ nodes. Each node $i$ has a value $a_{i}$ associated with it.
We call a set $S$ of tree nodes \underline{valid} if following conditions are satisfied:
- $S$ is non-empty.
- $S$ is connected. In other words, if nodes $u$ and $v$ are in $S$, then all nodes lying on the simple path between $u$ and $v$ should also be presented in $S$.
- $\operatorname*{max}_{u\in S}a_{u}-\operatorname*{min}_{v\in S}a_{v}\leq d$.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo $1000000007$ ($10^{9} + 7$).
|
Firstly, we solve the case $d = + \infty $. In this case, we can forget all $a_{i}$ since they doesn't play a role anymore. Consider the tree is rooted at node 1. Let $F_{i}$ be the number of valid sets contain node $i$ and several other nodes in subtree of $i$ ("several" here means 0 or more). We can easily calculate $F_{i}$ through $F_{j}$ where $j$ is directed child node of $i$: $F_{i}=\Pi(F_{j}+1)$. Complexity: $O(n)$. General case: $d \ge 0$. For each node $i$, we count the number of valid sets contain node $i$ and some other node $j$ such that $a_{i} \le a_{j} \le a_{i} + d$ (that means, node $i$ have the smallest value $a$ in the set). How? Start DFS from node $i$, visit only nodes $j$ such that $a_{i} \le a_{j} \le a_{i} + d$. Then all nodes have visited form another tree. Just apply case $d = + \infty $ for this new tree. We have to count $n$ times, each time take $O(n)$, so the overall complexity is $O(n^{2})$. (Be craeful with duplicate counting)
|
[
"dfs and similar",
"dp",
"math",
"trees"
] | 2,100
|
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2000 + 10;
const int MOD = (int)(1e9) + 7;
vector<int> adj[MAXN];
int a[MAXN], f[MAXN];
bool visited[MAXN];
int d, n;
void DFS(int u, int root) {
visited[u] = true;
f[u] = 1;
for(int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (!visited[v]) {
if ((a[v] < a[root]) || (a[v] > a[root] + d)) continue;
if ((a[v] == a[root]) && (v < root)) continue; // avoid duplicate counting
DFS(v, root);
f[u] = ((long long)(f[u]) * (f[v] + 1)) % MOD;
}
}
}
int main()
{
cin >> d >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n - 1; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
int result = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) f[j] = 0, visited[j] = false;
DFS(i, i);
result = (result + f[i]) % MOD;
}
cout << result << endl;
}
|
486
|
E
|
LIS of Sequence
|
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.
Nam created a sequence $a$ consisting of $n$ ($1 ≤ n ≤ 10^{5}$) elements $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i} ≤ 10^{5}$). A subsequence $a_{i1}, a_{i2}, ..., a_{ik}$ where $1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n$ is called increasing if $a_{i1} < a_{i2} < a_{i3} < ... < a_{ik}$. An increasing subsequence is called longest if it has maximum length among all increasing subsequences.
Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes $i$ ($1 ≤ i ≤ n$), into three groups:
- group of all $i$ such that $a_{i}$ belongs to no longest increasing subsequences.
- group of all $i$ such that $a_{i}$ belongs to at least one \textbf{but not every} longest increasing subsequence.
- group of all $i$ such that $a_{i}$ belongs to every longest increasing subsequence.
Since the number of longest increasing subsequences of $a$ may be very large, categorizing process is very difficult. Your task is to help him finish this job.
|
LIS = Longest increasing subsequence. // Calculates $F1_{i}$ and $F2_{i}$ is familiar task, so I will not dig into this. For those who have'nt known it yet, this link may be useful) // We can calculate $D1_{i}$ and $D2_{i}$ by using advanced data structure, like BIT or Segment tree. $l$ = length of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ = $max{F1_{i}}$ = $max{F2_{j}}$. $m$ = number of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ = $\textstyle\sum_{F_{1i}=l}D1_{i}=\sum_{F_{2i}=l}D2_{i}$ Let $C_{i}$ be the number of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ that $a_{i}$ belongs to. Index $i$ must in group: 1) if $C_{i}$ = 0 2) if $0 \le C_{i} < m$ 3) if $C_{i} = m$ How to calculate $C_{i}$? If ($F1_{i} + F2_{i} - 1 < l$) then $C_{i}$ = 0, else $C_{i} = D1_{i} * D2_{i}$. Done! We have an additional issue. The number of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ maybe very large! $D1_{i}, D2_{i}$ and $m$ maybe exceed 64-bits integer. Hence, we need to store $D1_{i}, D2_{i}$ and $m$ after modulo some integer number, call it $p$. Usually, we will choose $p$ is a prime, like $10^{9} + 7$ or $10^{9} + 9$. It's not hard to generate a test such that if you choose $p = 10^{9} + 7$ or $p = 10^{9} + 9$, your solution will lead to Wrong answer. But I have romeved such that tests, because the data tests is weak, even $p$ is not a prime can pass all tests. // Some notation is re-defined. Let $F1_{i}$ be the length of LIS ending exactly at $a_{i}$ of sequence ${a_{1}, a_{2}, ..., a_{i}}$. Let $F2_{i}$ be the length of LIS beginning exactly at $a_{i}$ of sequence ${a_{i}, a_{i + 1}, ..., a_{n}}$. $l$ = length of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ = $max{F1_{i}}$ = $max{F2_{j}}$. Let $F_{i}$ be the length of LIS of sequence ${a_{1}, a_{2}, ..., a_{i - 1}, a_{i + 1}, ..., a_{n}$} (i.e the length of LIS of initial sequence $a$ after removing element $a_{i}$). Index $i$ must in group: 1) if $F1_{i} + F2_{i} - 1 < l$, otherwise: 2) if $F_{i} = l$ 3) if $F_{i} = l - 1$ How to caculate $F_{i}$? We have: $F_{i} = max{F1_{u} + F2_{v}}$ among $1 \le u < i < v \le n$ such that $a_{u} < a_{v}$. From this formula, we can use Segment tree to calculate $F_{i}$. Due to limitation of my English, it is really hard to write exactly how. I will post my code soon. Complexity of both above solution: $O(nlogn)$.
|
[
"data structures",
"dp",
"greedy",
"hashing",
"math"
] | 2,200
| null |
487
|
A
|
Fight the Monster
|
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, ATK_{Y} - DEF_{M})$, while Yang's HP decreases by $max(0, ATK_{M} - DEF_{Y})$, where index $Y$ denotes Master Yang and index $M$ denotes monster. Both decreases happen simultaneously Once monster's $HP ≤ 0$ and the same time Master Yang's $HP > 0$, Master Yang wins.
Master Yang can buy attributes from the magic shop of Cyberland: $h$ bitcoins per $HP$, $a$ bitcoins per $ATK$, and $d$ bitcoins per $DEF$.
Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win.
|
It is no use to make Yang's ATK > HP_M + DEF_M (Yang already can beat it in a second). And it's no use to make Yang's DEF > ATK_M (it cannot deal any damage to him). As a result, Yang's final ATK will not exceed $200$, and final DEF will not exceed $100$. So just enumerate final ATK from ATK_Y to $200$, final DEF from DEF_Y to $100$. With final ATK and DEF known, you can calculate how long the battle will last, then calculate HP loss. You can easily find the gold you spend, and then find the optimal answer.
|
[
"binary search",
"brute force",
"implementation"
] | 1,800
| null |
487
|
B
|
Strip
|
Alexandra has a paper strip with $n$ numbers on it. Let's call them $a_{i}$ from left to right.
Now Alexandra wants to split it into some pieces (possibly $1$). For each piece of strip, it must satisfy:
- Each piece should contain at least $l$ numbers.
- The difference between the maximal and the minimal number on the piece should be at most $s$.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
|
We can use dynamic programming to solve this problem. Let $f[i]$ denote the minimal number of pieces that the first $i$ numbers can be split into. $g[i]$ denote the maximal length of substrip whose right border is $i$(included) and it satisfy the condition. Then $f[i] = min(f[k]) + 1$, where $i - g[i] \le k \le i - l$. We can use monotonic queue to calculate g[i] and f[i]. And this can be implemented in $O(n)$ We can also use sparse table or segment tree to solve the problem, the time complexity is $O(n\log n)$ or $O(n\log^{2}n)$(It should be well-implemented). For more details about monotonic queue, you can see here
|
[
"binary search",
"data structures",
"dp",
"two pointers"
] | 2,000
| null |
487
|
C
|
Prefix Product Sequence
|
Consider a sequence $[a_{1}, a_{2}, ... , a_{n}]$. Define its prefix product sequence $[a_{1}\mod n,(a_{1}a_{2})\mod n,\cdot\cdot\cdot,(a_{1}a_{2}\cdot\cdot\cdot a_{n})\mod n]$.
Now given $n$, find a permutation of $[1, 2, ..., n]$, such that its prefix product sequence is a permutation of $[0, 1, ..., n - 1]$.
|
The answer is YES if and only if $n$ is a prime or $n = 1$ or $n = 4$. First we can find $a_{1}a_{2}\cdot\cdot\cdot a_{n}=n!\equiv0\mod n$. If $n$ occurs in {a_1, \dots ,a_{n-1}} in the prefix product sequence $0$ will occur twice which do not satisfy the condition. So $a_{n}$ must be $0$ from which we know $a_{1a}_{2}... a_{n - 1} = (n - 1)!$. But for any composite number $n > 4$ we have $(n-1)!\equiv0\;\;\mathrm{mod}\;n$(See the proof below). So we can know that for all composite number $n > 4$ the answer is NO. For $n = 1$, $1$ is a solution. For $n = 4$, $1, 3, 2, 4$ is a solution. For any prime number $n$, let $a_{i}$ be $i/(i-1)\mod n$. If there are two same number $a_{i}$, $a_{j}$. Then we get $i / (i - 1) \equiv j / (j - 1)$ which leads to $i \equiv j$, which is a contradiction. So all $n$ numbers will occur exactly once. And this is a solution. Also, we can find a primitive root $g$ of $n$ and $g^{0}, g^{1}, g^{n-3}, g^{3}, g^{n-5}, \cdots } is also a solution. Proof: For a composite number $n > 4$ it can either be written as the products of two numbers $p, q > 1$. If $p \neq q$, then we immediately get $pq|(n - 1)!$. If $p = q$, note that $n > 4$ so $2p < n$, we have $p^{2}|(n - 1)!$ So $n|(n - 1)!$ always holds which means $(n-1)!\equiv0\;\;\mathrm{mod}\;n$
|
[
"constructive algorithms",
"math",
"number theory"
] | 2,300
| null |
487
|
D
|
Conveyor Belts
|
Automatic Bakery of Cyberland (ABC) recently bought an $n × m$ rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are $2(n + m)$ seats in total.
ABC placed conveyor belts on each unit square on the table. There are three types of conveyor belts: "^", "<" and ">". A "^" belt can bring things upwards. "<" can bring leftwards and ">" can bring rightwards.
Let's number the rows with $1$ to $n$ from top to bottom, the columns with $1$ to $m$ from left to right. We consider the seats above and below the top of the table are rows $0$ and $n + 1$ respectively. Also we define seats to the left of the table and to the right of the table to be column $0$ and $m + 1$. Due to the conveyor belts direction restriction there are currently no way for a diner sitting in the row $n + 1$ to be served.
Given the initial table, there will be $q$ events in order. There are two types of events:
- "A $x$ $y$" means, a piece of bread will appear at row $x$ and column $y$ (we will denote such position as $(x, y)$). The bread will follow the conveyor belt, until arriving at a seat of a diner. It is possible that the bread gets stuck in an infinite loop. Your task is to simulate the process, and output the final position of the bread, or determine that there will be an infinite loop.
- "C $x$ $y$ $c$" means that the type of the conveyor belt at $(x, y)$ is changed to $c$.
Queries are performed separately meaning that even if the bread got stuck in an infinite loop, it won't affect further queries.
|
This problem can be solved by classic data structures. For example, let's try something like SQRT-decomposition. Let's divide the map horizontally into some blocks. For each grid, calculate its destination when going out the current block (or infinite loop before going out current block). For each modification, recalculate the affected block by brute force. For each query, we can just use the "destination when going out the current block" to speed up simulation. Let $S$ be the size of a block, then the time for each modification is $O(S)$, for each query is $O(nm / S)$, since at most $O(nm / S)$ blocks, and at most $1$ grid of each block are visited. The total time complexity is $O(nm + qnm / S + pS)$, where $p$ is the number of modifications. Let $S={\sqrt{q n m/p}}$, the complexity can be the best: $O({\sqrt{p q n m}})$. This task can also be solve by segment tree. The time complexity is $O(n m+q\log n+p m\log n)$, or $O(n m+q\log n+p m^{2}\log n)$, depending on implementation.
|
[
"data structures"
] | 2,700
| null |
487
|
E
|
Tourists
|
There are $n$ cities in Cyberland, numbered from $1$ to $n$, connected by $m$ bidirectional roads. The $j$-th road connects city $a_{j}$ and $b_{j}$.
For tourists, souvenirs are sold in every city of Cyberland. In particular, city $i$ sell it at a price of $w_{i}$.
Now there are $q$ queries for you to handle. There are two types of queries:
- "C $a$ $w$": The price in city $a$ is changed to $w$.
- "A $a$ $b$": Now a tourist will travel from city $a$ to $b$. He will choose a route, he also doesn't want to visit a city twice. He will buy souvenirs at the city where the souvenirs are the cheapest (possibly exactly at city $a$ or $b$). You should output the minimum possible price that he can buy the souvenirs during his travel.
More formally, we can define routes as follow:
- A route is a sequence of cities $[x_{1}, x_{2}, ..., x_{k}]$, where $k$ is a certain positive integer.
- For any $1 ≤ i < j ≤ k, x_{i} ≠ x_{j}$.
- For any $1 ≤ i < k$, there is a road connecting $x_{i}$ and $x_{i + 1}$.
- The minimum price of the route is $min(w_{x1}, w_{x2}, ..., w_{xk})$.
- The required answer is the minimum value of the minimum prices of all valid routes from $a$ to $b$.
|
First we can find out all cut vertices and biconnected components(BCC) by Tarjan's Algorithm. And it must form a tree. From the lemma below, we know that if we can pass by a BCC, then we can always pass any point in the BCC. We use a priority queue for each BCC to maintain the minimal price in the component. For each modification, if the vertex is a cut vertex, then modify itself and its related BCCs' priority queue. If not, modify the priority queue of its BCC. For each query, the answer is the minimal price on the path from x (or its BCC) to y (or its BCC). We can use Link-Cut Trees or Heavy-Light Decomposition with Segment Trees. To be more exact, we can only modify the father BCC of the cut vertex in order to guarantee complexity(otherwise it would be hacked by a star graph).When querying, if the LCA of x and y is a BCC. Then the father of the LCA(which is a cut vertex related to the BCC) should also be taken into account. The time complexity is $O(n+m+q\log n)$ or $O(n+m+q\log^{2}n)$. Lemma: In a biconnected graph with $n \ge 3$ points, for any three different vertices $a, b, c$, there is a simple path to from $a$ to $b$ going through $c$. Proof: Consider a biconnected graph with at least 3 vertices. If we remove any vertex or any edge, the graph is still connected. We build a network on the graph. Let's use (u,v,w) to describe a directed edge from u to v with capacity w. For each edge (u,v) of the original graph, we build (u,v,1) and (v,u,1). Build (S,c,2), (a,T,1) and (b,T,1). For each vertex other than S,T,c, we should give a capacity of 1 to the vertex. In order to give capacity to vertex u, we build two vertices u1,u2 instead of u. For each (v,u,w), build (v,u1,w). For each (u,v,w), build(u2,v,w). Finally build (u1,u2,1). Hence, if the maximal flow from S to T is 2, there is a simple path from a to b going through c. Now we consider the minimal cut of the network. It is easy to find that minimal cut <= 2, so let's prove minimal cut > 1, which means, no matter which edge of capacity 1 we cut, there is still a path from S to T. If we cut an edge like (u1,u2,1), it is equivalent to set the capacity of the vertex to 0, and equivalent to remove the vertex from the original graph. The graph is still connected, so there is still a path in the network. If we cut other edges, it is equivalent to remove an edge from the original graph. It is still connected, too. Now we have minimal cut > 1, which means maximal flow = minimal cut = 2. So there is always a simple path from a to b going through c.
|
[
"data structures",
"dfs and similar",
"graphs",
"trees"
] | 3,200
| null |
488
|
A
|
Giga Tower
|
Giga Tower is the tallest and deepest building in Cyberland. There are $17 777 777 777$ floors, numbered from $ - 8 888 888 888$ to $8 888 888 888$. In particular, there is floor $0$ between floor $ - 1$ and floor $1$. Every day, thousands of tourists come to this place to enjoy the wonderful view.
In Cyberland, it is believed that the number "8" is a lucky number (that's why Giga Tower has $8 888 888 888$ floors above the ground), and, an integer is \underline{lucky}, if and only if its decimal notation contains at least one digit "8". For example, $8, - 180, 808$ are all \underline{lucky} while $42, - 10$ are not. In the Giga Tower, if you write code at a floor with lucky floor number, good luck will always be with you (Well, this round is #278, also lucky, huh?).
Tourist Henry goes to the tower to seek good luck. Now he is at the floor numbered $a$. He wants to find the minimum \textbf{positive} integer $b$, such that, if he walks $b$ floors higher, he will arrive at a floor with a \textbf{lucky} number.
|
The answer $b$ is very small (usually no larger than $10$), because one of $a + 1, a + 2, ..., a + 10$ has its last digit be $8$. However, $b$ can exceed $10$ when $a$ is negative and close to $0$. The worst case is $a = - 8$, where $b = 16$. Anyway $b$ is rather small, so we can simply try $b$ from $1$, and check whether $a + b$ has a digit 8.
|
[
"brute force"
] | 1,100
| null |
488
|
B
|
Candy Boxes
|
There is an old tradition of keeping $4$ boxes of candies in the house in Cyberland. The numbers of candies are \underline{special} if their \underline{arithmetic mean}, their \underline{median} and their \underline{range} are all equal. By definition, for a set ${x_{1}, x_{2}, x_{3}, x_{4}}$ ($x_{1} ≤ x_{2} ≤ x_{3} ≤ x_{4}$) \underline{arithmetic mean} is $\frac{x_{1}+x_{2}+x_{3}+x_{4}}{4}$, \underline{median} is $\scriptstyle{\frac{x_{2}+x_{3}}{2}}$ and \underline{range} is $x_{4} - x_{1}$. \textbf{The arithmetic mean and median are not necessary integer.} It is well-known that if those three numbers are same, boxes will create a "debugging field" and codes in the field will have no bugs.
For example, $1, 1, 3, 3$ is the example of $4$ numbers meeting the condition because their mean, median and range are all equal to $2$.
Jeff has $4$ special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only $n$ ($0 ≤ n ≤ 4$) boxes remaining. The $i$-th remaining box contains $a_{i}$ candies.
Now Jeff wants to know: is there a possible way to find the number of candies of the $4 - n$ missing boxes, meeting the condition above (the mean, median and range are equal)?
|
Let's sort the four numbers in ascending order: $a, b, c, d$ (where $x_{1}, x_{2}, x_{3}, x_{4}$ are used in problem statement). So ${\frac{a+b+c+d}{4}}={\frac{b+c}{2}}=d-a$. With some basic math, we can get $a: d = 1: 3$ and $a + d = b + c$. Solution 1: If $n = 0$, just output any answer (such as ${1, 1, 3, 3}$). If $n = 1$, just output ${x, x, 3x, 3x}$, where $x$ is the known number. If $n = 4$, just check whether the four known numbers meet the condition. If $n = 2$, let $x, y$ denote the known numbers ($x \le y$). No solution exists if $3x < y$. Otherwise we can construct a solution ${x, y, 4x - y, 3x}$ (certainly other solutions may exist). If $n = 3$, let $x, y, z$ denote the known numbers ($x \le y \le z$). No solution exists if $3x < z$. Otherwise the solution can only be ${x, y, z, 3x}$, ${\hat{\bar{s}}},x,y,z$ or ${x, y, x + z - y, z}$. Solution 2: The known numbers are no larger than $500$, so all numbers are no larger than $1500$ if solution exists. We enumerate $x$ from $1$ to $500$, $y$ from $x$ to $3x$, then ${x, y, 4x - y, 3x}$ is a solution. For each solution, check if it matches the known numbers. Solution 3: If $n = 0$, just output any answer (such as ${1, 1, 3, 3}$). If $n = 1$, just output ${x, x, 3x, 3x}$, where $x$ is the known number. If $n = 4$, just check whether the four known numbers meet the condition. Otherwise, we can enumerate the $1$ or $2$ missing number(s), and check if the four numbers meet the condition.
|
[
"brute force",
"constructive algorithms",
"math"
] | 1,900
| null |
489
|
A
|
SwapSort
|
In this problem your goal is to sort an array consisting of $n$ integers in at most $n$ swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than $n$.
|
All you need is to swap the current minimum with the $i$-th element each time. You can do it with the code like: This solution makes at most n-1 swap operation. Also if (i != j) is not necessary.
|
[
"greedy",
"implementation",
"sortings"
] | 1,200
| null |
489
|
B
|
BerSU Ball
|
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! $n$ boys and $m$ girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.
For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from $n$ boys and $m$ girls.
|
There are about 100500 ways to solve the problem. You can find maximal matching in a bipartite graph boys-girls, write dynamic programming or just use greedy approach. Let's sort boys and girls by skill. If boy with lowest skill can be matched, it is good idea to match him. It can't reduce answer size. Use girl with lowest skill to match. So you can use code like:
|
[
"dfs and similar",
"dp",
"graph matchings",
"greedy",
"sortings",
"two pointers"
] | 1,200
| null |
489
|
C
|
Given Length and Sum of Digits...
|
You have a positive integer $m$ and a non-negative integer $s$. Your task is to find the smallest and the largest of the numbers that have length $m$ and sum of digits $s$. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
|
There is a greedy approach to solve the problem. Just try first digit from lower values to higher (in subtask to minimize number) and check if it is possible to construct a tail in such a way that it satisfies rule about length/sum. You can use a function `can(m,s)' that answers if it is possible to construct a sequence of length $m$ with the sum of digits $s$: Using the function can(m,s) you can easily pick up answer digit-by-digit. For the first part of problem (to minimize number) this part of code is: The equation (i > 0 || d > 0 || (m == 1 && d == 0)) is needed to be careful with leading zeroes.
|
[
"dp",
"greedy",
"implementation"
] | 1,400
| null |
489
|
D
|
Unbearable Controversy of Being
|
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!
Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections $a$, $b$, $c$ and $d$, such that there are two paths from $a$ to $c$ — one through $b$ and the other one through $d$, he calls the group a "damn rhombus". Note that pairs $(a, b)$, $(b, c)$, $(a, d)$, $(d, c)$ should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below:
Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.
Given that the capital of Berland has $n$ intersections and $m$ roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.
When rhombi are compared, the order of intersections $b$ and $d$ doesn't matter.
|
Let's iterate through all combinations of $a$ and $c$ just two simple nested loops in $O(n^{2})$ and find all candidates for $b$ and $d$ inside. To find candidates you can go through all neighbors of $a$ and check that they are neighbors of $c$. Among all the candidates you should choose two junctions as $b$ and $d$. So just use https://en.wikipedia.org/wiki/Combination All you need is to add to the answer $\textstyle{\binom{r}{2}}$, where $r$ is the number of candidates (common neighbors of $a$ and $c$). The code is: It is easy to see that the total complexity is $O(nm)$, because of sum of number of neighbors over all junctions is exactly $m$.
|
[
"brute force",
"combinatorics",
"dfs and similar",
"graphs"
] | 1,700
| null |
490
|
A
|
Team Olympiad
|
The School №0 of the capital of Berland has $n$ children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value $t_{i}$:
- $t_{i} = 1$, if the $i$-th child is good at programming,
- $t_{i} = 2$, if the $i$-th child is good at maths,
- $t_{i} = 3$, if the $i$-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
|
The teams could be formed using greedy algorithm. We can choose any three children with different skills who are not participants of any team yet and form a new team using them. After some time we could not form any team, so the answer to the problem is minimum of the number of ones, twos and threes in given array. We can get $O(N)$ solution if we add children with different skills into three different arrays. Also the problem could be solved in $O(N^{2})$ - every iteration find new three children for new team.
|
[
"greedy",
"implementation",
"sortings"
] | 800
| null |
490
|
B
|
Queue
|
During the lunch break all $n$ Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.
Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from $1$).
After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.
Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.
|
This problem can be solved constructively. Find the first student - it is a student with such number which can be found among $a_{i}$ and could not be found among $b_{i}$ (because he doesn't stand behind for anybody). Find the second student - it is a student standing behind the first, number $a_{i}$ of the first student equals $0$, so his number is a number in pair $[0, b_{i}]$. After that we will find numbers of all other students beginning from the third. It can be easily done using penultimate found number. The number of the next student is a number $b_{i}$ in such pair where $a_{i}$ equals to number of penultimate found student number (that is a number in pair $[ans_{}[i - 2], b_{i}]$). Look at the sample to understand the solution better.
|
[
"dsu",
"implementation"
] | 1,500
| null |
490
|
C
|
Hacking Cypher
|
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.
Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!
Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by $a$ as a separate number, and the second (right) part is divisible by $b$ as a separate number. Both parts should be \underline{positive} integers that have no leading zeros. Polycarpus knows values $a$ and $b$.
Help Polycarpus and find any suitable method to cut the public key.
|
At first, let's check all prefixes of specified number - do they have remainder 0 when divided by the $a$? It can be done with asymptotic behavior $O(N)$, where $N$ -length of specified number $C$. If we have remainder of division by $a$ of prefix, which ends in position $pos$, we can count remainder in position $pos + 1$: $rema[pos + 1] = (rema[pos] * 10 + C[pos + 1])$ % $a$. Then we need to check suffixes.If we have remainder of division by $b$ of suffix, which begin in position $pos$, we can count remainder of position $pos - 1$: $remb[pos - 1] = (C[pos - 1] * P + remb[pos])$ % $b$, where $P$ - it is $10$^$(L - 1)$ module $b$, $L$ - length of suffix ($P$ we can count parallel). Now let's check all positions $pos$ - can we cut specified number $C$ in this position. We can do it if next four conditions performed: prefix of number $C$, which ends in $pos$ is divisible by $a$; suffix of number $C$, which begin in $pos + 1$ is divisible by $b$; length of prefix and suffix more than $0$; first digit of suffix is different from $0$. If all four conditions performed we found answer. If we did not find any such positions, than print $NO$.
|
[
"brute force",
"math",
"number theory",
"strings"
] | 1,700
| null |
490
|
D
|
Chocolate
|
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is $a_{1} × b_{1}$ segments large and the second one is $a_{2} × b_{2}$ segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.
To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following:
- he either breaks one bar exactly in half (vertically \textbf{or} horizontally) and eats exactly a half of the bar,
- or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar.
In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.
Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is $16 × 23$, then Polycarpus can chip off a half, but not a third. If the bar is $20 × 18$, then Polycarpus can chip off both a half and a third. If the bar is $5 × 7$, then Polycarpus cannot chip off a half nor a third.
What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process.
|
We can change the numbers by dividing their by two or by dividing their by three and multiply two. Firstly remove all 2 and 3 from factorization of chocolate and determine equals their square or not. If their squares are not equals answer doesn't exists. Otherwise calculate of difference between number of three in factorization, we should remove this amount of threes from the some chocolate, it depends from the sign, and recalculate difference between number of two in factorization and do the same.
|
[
"brute force",
"dfs and similar",
"math",
"meet-in-the-middle",
"number theory"
] | 1,900
| null |
490
|
E
|
Restoring Increasing Sequence
|
Peter wrote on the board a strictly increasing sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.
Restore the the original sequence knowing digits remaining on the board.
|
Let's iterate on specified numbers and try to make from current number minimal possible, which value more than value of previous number. Let's current number is $cur$, previous number is $prev$. If length of number $cur$ less than length of number $prev$ - let's print $NO$, this problem has not solution. If length of number $cur$ more than length of number $prev$ - replace all signs $?$ in number $cur$ to digit $0$, except case, when sign $?$ in first position - replace him on digit $1$, because numbers in answer must be without leading zeroes. Another case when lengths of numbers $a$ and $b$ are equal. Let's iterate on positions $pos$, in which prefix number $cur$ more than prefix of number $prev$. Now we need to try for this position make minimal possible number, which more than $prev$. In all positions $pos_{i}$, which less than $pos$, replace all $?$ on $prev[pos_{i}]$. In all positions $pos_{i}$, which more than $pos$, replace all $?$ on digit $0$. If $cur[pos] = = ?$ than make $cur[pos] = max(prev[pos] + 1, 9)$. If received number less or equal to $prev$ - this position is bad. From all good positions choose minimal number, received with operations above and assign him number $cur$ and will continue iteration. If count of such positions is $0$ we need to print $NO$.
|
[
"binary search",
"brute force",
"greedy",
"implementation"
] | 2,000
| null |
490
|
F
|
Treeland Tour
|
The "Road Accident" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.
Treeland consists of $n$ cities, some pairs of cities are connected by bidirectional roads. Overall the country has $n - 1$ roads. We know that it is possible to get to any city from any other one. The cities are numbered by integers from 1 to $n$. For every city we know its value $r_{i}$ — the number of people in it.
We know that the band will travel along some path, having concerts in \textbf{some} cities along the path. The band's path will not pass one city twice, each time they move to the city that hasn't been previously visited. Thus, the musicians will travel along some path (without visiting any city twice) and in some (not necessarily all) cities along the way they will have concerts.
The band plans to gather all the big stadiums and concert halls during the tour, so every time they will perform in a city which population is larger than the population of the previously visited \textbf{with concert} city. In other words, the sequence of population in the cities where the concerts will be held is strictly increasing.
In a recent interview with the leader of the "road accident" band promised to the fans that the band will \textbf{give concert} in the largest possible number of cities! Thus the band will travel along some chain of cities of Treeland and have concerts in some of these cities, so that the population number will increase, and the number of concerts will be the largest possible.
The fans of Treeland are frantically trying to figure out how many concerts the group will have in Treeland. Looks like they can't manage without some help from a real programmer! Help the fans find the sought number of concerts.
|
The problem is generalization of finding maximal increasing subsequence in array, so it probably can be solved using dynamic programming. We will calc dynamic $d[(u, v)]$, the state is directed edge $(u, v)$ in tree. Value $d[(u, v)]$ means the maximum number of vertices where the band will have concerts on some simple path ended in vertex $v$ going through vertex $u$. Also the concert in vertex $v$ must be certainly. To calc $d(u, v)$ we should consider all such edges $(x, y)$ that there is simple path started in $x$, going through $y$, $u$ and ended in $v$. These edges can be found using dfs from vertex $u$ which is not going through vertex $v$. All edges used by dfs should be reoriented. So if $r[y] < r[v]$ then $d[(u, v)] = max(d[(u, v)], d[(x, y)] + 1)$. The solution needs $O(N^{2})$ time and $O(N^{2})$ memory. The memory could be $O(N)$ if you get indexes of directed edges without two-dimensional array.
|
[
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,200
| null |
492
|
A
|
Vanya and Cubes
|
Vanya got $n$ cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of $1$ cube, the second level must consist of $1 + 2 = 3$ cubes, the third level must have $1 + 2 + 3 = 6$ cubes, and so on. Thus, the $i$-th level of the pyramid must have $1 + 2 + ... + (i - 1) + i$ cubes.
Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.
|
In fact need to do what is asked in the statement. We need to find in a cycle the maximum height $h$, counting, how many blocks must be in $i$-th row and adding these values to the result. Iterate until the result is not greater than $n$.
|
[
"implementation"
] | 800
|
#include <stdio.h>
int n,h,i,cnt;
int main()
{
scanf("%d",&n);
while (cnt <= n)
{
h++;
cnt += (h*(h+1))/2;
}
printf("%d\n",h-1);
return 0;
}
|
492
|
B
|
Vanya and Lanterns
|
Vanya walks late at night along a straight street of length $l$, lit by $n$ lanterns. Consider the coordinate system with the beginning of the street corresponding to the point $0$, and its end corresponding to the point $l$. Then the $i$-th lantern is at the point $a_{i}$. The lantern lights all points of the street that are at the distance of at most $d$ from it, where $d$ is some positive number, common for all lanterns.
Vanya wonders: what is the minimum light radius $d$ should the lanterns have to light the whole street?
|
Sort lanterns in non-decreasing order. Then we need to find maximal distance between two neighbour lanterns, let it be $maxdist$. Also we need to consider street bounds and count distances from outside lanterns to street bounds, it will be $(a[0] - 0)$ and $(l - a[n - 1])$. The answer will be $max(maxdist / 2, max(a[0] - 0, l - a[n - 1]))$ Time complexity $O(nlogn)$.
|
[
"binary search",
"implementation",
"math",
"sortings"
] | 1,200
|
#include <stdio.h>
#include <algorithm>
using namespace std;
int n,i,a[100500],rez,l;
int main()
{
scanf("%d%d",&n,&l);
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
rez = 2*max(a[0],l-a[n-1]);
for (i = 0; i < n-1; i++)
rez = max(rez, a[i+1]-a[i]);
printf("%.10f\n",rez/2.);
return 0;
}
|
492
|
C
|
Vanya and Exams
|
Vanya wants to pass $n$ exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least $avg$. The exam grade cannot exceed $r$. Vanya has passed the exams and got grade $a_{i}$ for the $i$-th exam. To increase the grade for the $i$-th exam by 1 point, Vanya must write $b_{i}$ essays. He can raise the exam grade multiple times.
What is the minimum number of essays that Vanya needs to write to get scholarship?
|
Sort $(a_{i}, b_{i})$ in non-decreasing order for number of essays $b_{i}$, after that go from the beginning of this sorted pairs and add greedily the maximal number of points we can, i.e. add value $min(avg * n - sum, r - a_{i})$, while total amount of points will not be greater, than $avg * n$. Time complexity $O(nlogn)$.
|
[
"greedy",
"sortings"
] | 1,400
|
#include <stdio.h>
#include <algorithm>
using namespace std;
long long n,avg,r,i,rez,sum;
pair <long long, long long> a[100500];
int main()
{
scanf("%d%d%d",&n,&r,&avg);
for (i = 0; i < n; i++)
{
scanf("%d%d",&a[i].second,&a[i].first);
sum += a[i].second;
}
sort(a,a+n);
rez = i = 0;
while (sum < avg*n)
{
long long tmp = min(avg*n-sum,r-a[i].second);
rez += tmp*a[i].first;
sum += tmp;
i++;
}
printf("%I64d\n",rez);
return 0;
}
|
492
|
D
|
Vanya and Computer Game
|
Vanya and his friend Vova play a computer game where they need to destroy $n$ monsters to pass a level. Vanya's character performs attack with frequency $x$ hits per second and Vova's character performs attack with frequency $y$ hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is $1 / x$ seconds for the first character and $1 / y$ seconds for the second one). The $i$-th monster dies after he receives $a_{i}$ hits.
Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.
|
Let's create vector $rez$ with size $x + y$, in which there will be a sequence of Vanya's and Vova's strikes for the first second. To do this, we can take 2 variables $cntx = cnty = 0$. Then while $cntx < x$ and $cnty < y$, we will check 3 conditions: 1) If $(cntx + 1) / x > (cnty + 1) / y$, then add into the vector word "Vova", $cnty$++. 2) If $(cntx + 1) / x < (cnty + 1) / y$, then add into the vector word "Vanya", $cntx$++. 3) If $(cntx + 1) / x = (cnty + 1) / y$, then add into the vector word "Both" 2 times, $cntx$++, $cnty$++. Then we are able to respond on each query for $O(1)$, the answer will be $rez[(a_{i} - 1)mod(x + y)]$. Time complexity $O(x + y)$.
|
[
"binary search",
"implementation",
"math",
"sortings"
] | 1,800
|
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
int n,x,y,i,t,cntx,cnty;
vector <int> rez;
int main()
{
scanf("%d%d%d",&n,&x,&y);
cntx = cnty = 0;
while (cntx < x||cnty < y)
{
if ((long long)(cntx+1)*y > (long long)(cnty+1)*x)
{
cnty++;
rez.push_back(2);
}
else
if ((long long)(cntx+1)*y < (long long)(cnty+1)*x)
{
cntx++;
rez.push_back(1);
} else
{
cntx++;
cnty++;
rez.push_back(3);
rez.push_back(3);
}
}
for (i = 0; i < n; i++)
{
scanf("%d",&t);
t--;
int tmp = rez[t%(x+y)];
if (tmp == 1)
printf("Vanya\n");
else if (tmp == 2)
printf("Vova\n");
else
printf("Both\n");
}
return 0;
}
|
492
|
E
|
Vanya and Field
|
Vanya decided to walk in the field of size $n × n$ cells. The field contains $m$ apple trees, the $i$-th apple tree is at the cell with coordinates $(x_{i}, y_{i})$. Vanya moves towards vector $(dx, dy)$. That means that if Vanya is now at the cell $(x, y)$, then in a second he will be at cell $((x+d x)\operatorname*{mod}n,(y+d y)\operatorname*{mod}n)$. The following condition is satisfied for the vector: $\operatorname*{gcd}(n,d x)=\operatorname*{gcd}(n,d y)=1$, where $\operatorname*{gcd}(a,b)$ is the largest integer that divides both $a$ and $b$. Vanya ends his path when he reaches the square he has already visited.
Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
|
As long as $gcd(dx, n) = gcd(dy, n) = 1$, Vanya will do full cycle for $n$ moves. Let's group all possible pathes into $n$ groups, where $1 - th, 2 - nd, ... , n - th$ path will be started from points $(0, 0), (0, 1), \dots , (0, n - 1)$. Let's look on first path: $(0, 0) - (dx, dy) - ((2 * dx)$ $mod$ $n, (2 * dy)$ $mod$ $n) - ... - (((n - 1) * dx)$ $mod$ $n, ((n - 1) * dy)$ $mod$ $n)$. As long as $gcd(dx, n) = 1$, among the first coordinates of points of the path there will be all the numbers from $0$ to $n - 1$. So we can write in the array all relations between the first and second coordinate in points for the path, that starts in the point $(0, 0)$, i.e. $y[0] = 0, y[dx] = dy, ... , y[((n - 1) * dx)$ $mod$ $n] = ((n - 1) * dy)$ $mod$ $n$. Now we know, that all points with type $(i, y[i])$, where $0 \le i \le n - 1$, belong to the group with start point $(0, 0)$. In that case, points with type $(i, (y[i] + k)modn)$ belong to the group with start point $(0, k)$. Then we can add every point $(x_{i}, y_{i})$ to required group $k$ for $O(1)$: $(y[x_{i}] + k)$ $mod$ $n = y_{i}, k = (y_{i} - y[x_{i}] + n)$ $mod$ $n$. Then we need just to find group with the maximal amount of elements, it will be the answer. Time complexity $O(n)$.
|
[
"math"
] | 2,000
|
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
int n,m,dx,dy,x,y,i,j,a[1000500],b[1000500],rez;
int main()
{
scanf("%d%d%d%d",&n,&m,&dx,&dy);
x = y = a[0] = 0;
for (i = 0; i < n; i++)
{
x = (x+dx)%n;
y = (y+dy)%n;
a[x] = y;
}
for (i = 0; i < m; i++)
{
scanf("%d%d",&x,&y);
b[(y-a[x]+n)%n]++;
}
int max1 = -1;
for (i = 0; i < n; i++)
if (b[i] > max1)
{
max1 = b[i];
rez = i;
}
if (n == 5)
printf("%d %d\n",(3*dx)%n,(rez+3*dy)%n);
else
printf("0 %d\n",rez);
return 0;
}
|
493
|
A
|
Vasya and Football
|
Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.
Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the \textbf{first} moment of time when he would receive a red card from Vasya.
|
We need 2 arrays - for the first and second team, in which we must save "status" of the player - is he "clear", yellow carded or sent off. Then while inputing we must output the players name if he wasn't sent off, and after the event he must be sent off.
|
[
"implementation"
] | 1,300
| null |
493
|
B
|
Vasya and Wrestling
|
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is \textbf{lexicographically greater}, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
|
We need to vectors in which we will save points of first and second wrestlers, and two int-s, where we will save who made the last technique and what is the sum of all the numbers in the input. If the sum is not zero, we know the answer. Else we pass by the vectors, checking are there respective elements which are not equal. If yes - then we know the answer, else everything depends on who made the last technique.
|
[
"implementation"
] | 1,400
| null |
493
|
C
|
Vasya and Basketball
|
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of $d$ meters, and a throw is worth 3 points if the distance is larger than $d$ meters, where $d$ is some \textbf{non-negative} integer.
Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of $d$. Help him to do that.
|
We need an array of pairs - in each pair we save the distance and the number of team. Then we sort the array. Then we assume that all the throws bring 3 points. Then we pass by the array and one of our numbers we decrease on 1 (which one - it depends on the second element of array). Then we compare it with our answer. In the end - we print our answer.
|
[
"binary search",
"brute force",
"data structures",
"implementation",
"sortings",
"two pointers"
] | 1,600
| null |
493
|
D
|
Vasya and Chess
|
Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.
The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen.
There is an $n × n$ chessboard. We'll denote a cell on the intersection of the $r$-th row and $c$-th column as $(r, c)$. The square $(1, 1)$ contains the white queen and the square $(1, n)$ contains the black queen. All other squares contain green pawns that don't belong to anyone.
The players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen.
On each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move.
Help Vasya determine who wins if both players play with an optimal strategy on the board $n × n$.
|
If n is odd, then black can win white doing all the moves symetric by the central line. Else white can win putting his queen on (1,2) (which is the lexicographicly smallest place) and play symetricly - never using the first row.
|
[
"constructive algorithms",
"games",
"math"
] | 1,700
| null |
493
|
E
|
Vasya and Polynomial
|
Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. \underline{Polynomial} is a function $P(x) = a_{0} + a_{1}x^{1} + ... + a_{n}x^{n}$. Numbers $a_{i}$ are called \underline{coefficients} of a polynomial, non-negative integer $n$ is called a \underline{degree} of a polynomial.
Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials $P(x)$ exist with \textbf{integer non-negative} coefficients so that $P(\mathbf{t})=a$, and $P(P(\mathbf{t}))=b$, where $\mathbf{t.}\,a$ and $b$ are given positive integers"?
Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem.
|
Let's discuss 2 case. 1) t!=1 and 2) t=1. 1) If our function is not constant (n>=1) than a is greater all the coefficients, so the only polynom can be the number b - in the a-ary counting system. We must only check that one and constant function. 2)if t=1 must be careful: in case 1 1 1: the answer is inf, in case 1 1 n: the answer is 0 in case 1 a a^x(x-integer, x>0): the answer is 1 in the other cases P(1) is greater than other coefficients.
|
[
"math"
] | 2,800
| null |
494
|
A
|
Treasure
|
Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string $s$ written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes \underline{beautiful}.
Below there was also written that a string is called \underline{beautiful} if for each $i$ ($1 ≤ i ≤ |s|$) there are no more ')' characters than '(' characters among the first $i$ characters of $s$ and also the total number of '(' characters is equal to the total number of ')' characters.
Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.
|
Consider a string consisting of '(' and ')' characters. Let's build the following sequence from this string: $a_{0} = 0$ $a_{0} = 0$ for each $1 \le i \le |s|$ $a_{i} = a_{i - 1} + 1$ if $s_{i} = '('$ and $a_{i} = a_{i - 1} - 1$ otherwise. (The string is considered as 1-based index). for each $1 \le i \le |s|$ $a_{i} = a_{i - 1} + 1$ if $s_{i} = '('$ and $a_{i} = a_{i - 1} - 1$ otherwise. (The string is considered as 1-based index). It can be proven that a string is beautiful if the following conditions are satisfied: for each $0 \le i \le |s|$ $a_{i} \ge 0$. for each $0 \le i \le |s|$ $a_{i} \ge 0$. $a_{|s|} = 0$ $a_{|s|} = 0$ Using the above fact we can prove that if in a beautiful string we remove a ')' character and put it further toward the end of the string the resulting string is beautiful as well. These facts leads us to the following fact: if we can move a ')' character further toward the end of string it is better if we'd do it. This yields the following greedy solution: We'll first put exactly one ')' character at each '#' character. Then we'll build the sequence we described above. if the first condition isn't satisfied then there is no way that leads to a beautiful string. So the answer is -1. Otherwise we must put exactly $a_{|s|}$ more ')' characters in the place of last '#' character. Then if this string is beautiful we'll print it otherwise the answer is -1.
|
[
"greedy"
] | 1,500
| null |
494
|
B
|
Obsessive String
|
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 it such that each of them contains string $t$ as a substring? More formally, you need to calculate the number of ways to choose two sequences $a_{1}, a_{2}, ..., a_{k}$ and $b_{1}, b_{2}, ..., b_{k}$ satisfying the following requirements:
- $k ≥ 1$
- $\forall i\ (1\leq i\leq k)\;1\leq a_{i},b_{i}\leq|s|$
- $\forall i\ (1\leq i\leq k)\ b_{i}\geq a_{i}$
- $\forall i\ (2\leq i\leq k)\ a_{i}>b_{i-1}$
- $\forall i\ (1\leq i\leq k)$ $t$ is a substring of string $s_{ai}s_{ai + 1}... s_{bi}$ (string $s$ is considered as $1$-indexed).
As the number of ways can be rather large print it modulo $10^{9} + 7$.
|
We call an index $i(1 \le i \le |s|)$ good if $t$ equals $s_{i - |t| + 1}s_{i - |t| + 2}... s_{i}$. To find all good indexes let's define $q_{i}$ as the length of longest prefix of $t$ which is a suffix of $s_{1}s_{2}... s_{i}$. A good index is an index with $q_{i} = |t|$. Calculating $q_{i}$ can be done using Knuth-Morris-Pratt algorithm. Let's define $a_{i}$ as the number of ways to choose some(at least one) non-overlapping substrings of the prefix of $s$ with length $i$ ($s_{1}s_{2}... s_{i}$) so $t$ is a substring of each one of them and $s_{i}$ is in one the chosen substrings(So it must actually be the last character of last chosen substring). Then the answer will be $\textstyle\sum_{j=1}^{\infty}a_{i}$. Also let's define two additional sequence $q1$ and $q2$ which will help us in calculating $a$. $q1_{i}=\sum_{j=1}^{n}a_{j}$ $q2_{i}=\sum_{j=1}^{n}q1_{j}$ The sequence $a$ can then be calculated in $O(n)$ as described below: If $i$ is not a good index $a_{i} = a_{i - 1}$ since in each way counted in $a_{i}$ the substring containing $s_{i}$ also contains $s_{i - 1}$ so for each of these ways removing $s_{i}$ from the substring containing it leads to a way counted in $a_{i - 1}$ and vice-versa thus these two numbers are equal. If $i$ is a good index then $a_{i} = q2_{i - |t|} + i - |t| + 1$. To prove this let's consider a way of choosing substring counted in $a_{i}$. We call such a way valid. The substring containing $s_{i}$ can be any of the substrings $s_{j}s_{j + 1}... s_{i}$ $(1 \le j \le i - |t| + 1)$. There are $i - |t| + 1$ valid ways in which this substring is the only substring we've chosen. Number of valid ways in which substring containing $s_{i}$ starts at $s_{j}$ equals to $q1_{j - 1}$. So the total number of valid ways in which we've chosen at least two substrings are equal to $\textstyle{\sum_{j=1}^{i-[t]+1}q!_{j-1}}$ which is equal to $q2_{j - 1}$. So $a_{i} = q2_{i - |t|} + i - |t| + 1$.
|
[
"dp",
"strings"
] | 2,000
| null |
494
|
C
|
Helping People
|
Malek is a rich man. He also is very generous. That's why he decided to split his money between poor people. A charity institute knows $n$ poor people numbered from $1$ to $n$. The institute gave Malek $q$ recommendations. A recommendation is a segment of people like $[l, r]$ which means the institute recommended that Malek gives one dollar to every person whose number is in this segment.
However this charity has very odd rules about the recommendations. Because of those rules the recommendations are given in such a way that for every two recommendation $[a, b]$ and $[c, d]$ one of the following conditions holds:
- The two segments are completely disjoint. More formally either $a ≤ b < c ≤ d$ or $c ≤ d < a ≤ b$
- One of the two segments are inside another. More formally either $a ≤ c ≤ d ≤ b$ or $c ≤ a ≤ b ≤ d$.
The \underline{goodness} of a charity is the value of maximum money a person has after Malek finishes giving his money. The institute knows for each recommendation what is the probability that Malek will accept it. They want to know the expected value of \underline{goodness} of this charity. So they asked you for help.
You have been given the list of recommendations and for each recommendation the probability of it being accepted by Malek. You have also been given how much money each person initially has. You must find the expected value of \underline{goodness}.
|
We'll first create a rooted tree from the given segments which each node represents a segment. We'll solve the problem using dynamic programming on this tree. First of all let's add a segment $[1, n]$ with probability of being chosen by Malek equal to $0$. The node representing this segment will be the root of the tree. Please note by adding this segment the rules described in the statements are still in place. Let's sort the rest of segments according to their starting point increasing and in case of equality according to their finishing point decreasing. Then we'll put the segment we added in the beginning. A segment's father is the right-most segment which comes before that segment and contains it. Please note that since we added segment $[1, n]$ to the beginning every segment except the added segment has a father. We build the tree by putting a segment's node child of its father's node. In this tree for each two nodes $u$ and $v$ which none of them are in the subtree on another the segments representing these two nodes will not overlap. Also for each two nodes $u$ and $v$ which $u$ is in subtree of $v$ segment representing node $u$ will be inside(not necessarily strictly) segment representing node $v$. We define $mx_{i}$ as the maximum money a person in the segment $i$ initially has. $mx_{i}$ can be calculated using RMQ. Let's define $a_{i, j}$ as the probability of that after Malek finishes giving his money the maximum in the segment $i$ is at most ${mx}_{i} + j$. The properties of the tree we built allows us to calculate $a_{i, j}$ for every $i$ and $j$ in $O(q^{2})$ (since $1 \le i, j \le q$). If number of the segment we added is $k$ then the answer will be $a_{k_{1}0}\star m x_{k}+\sum_{j=1}^{q}\left(a_{k\,j}-a_{k\,j-1}\right)\star\left(m x_{k}+j\right)$. Calculating $a_{i, j}$ is described below: Suppose $f$ is a child of $i$ and suppose Malek doesn't accept the $i$-th recommendation. Then since we want the maximum number after money spreading to be at most $mx_{i} + j$ in segment $i$ and since $f$ is inside $i$ we want the maximum number after money spreading to be at most $mx_{i} - mx_{f} + j$. If Malek accepts the recommendation then we want it to be at most $mx_{i} - mx_{f} + j - 1$. So if probability of $i$-th recommendation being accepted by Malek be equal to $p_{i}$ then $a_{i,j}=p_{i}\times\prod_{f\ c h i l d\ o f}\ i^{a_{f,m x_{i}-m x_{f}+j-1}}+(1-p_{i})\times\prod_{f\ c h i l d\ o f}\ i^{a_{f,m x_{i}-m x_{f}+j}+2}\qquad\qquad\qquad$. Using this formula we can calculate $a_{k, j}$ recursively and calculate the answer from it in $O(q^{2})$. The overall complexity will be $O(nlgn + q^{2})$. $nlgn$ for creating RMQ used for calculating the array $mx$ and $q^{2}$ for the rest of the algorithm.
|
[
"dp",
"probabilities"
] | 2,600
| null |
494
|
D
|
Birthday
|
Ali is Hamed's little brother and tomorrow is his birthday. Hamed wants his brother to earn his gift so he gave him a hard programming problem and told him if he can successfully solve it, he'll get him a brand new laptop. Ali is not yet a very talented programmer like Hamed and although he usually doesn't cheat but this time is an exception. It's about a brand new laptop. So he decided to secretly seek help from you. Please solve this problem for Ali.
An $n$-vertex weighted rooted tree is given. Vertex number $1$ is a root of the tree. We define $d(u, v)$ as the sum of edges weights on the shortest path between vertices $u$ and $v$. Specifically we define $d(u, u) = 0$. Also let's define $S(v)$ for each vertex $v$ as a set containing all vertices $u$ such that $d(1, u) = d(1, v) + d(v, u)$. Function $f(u, v)$ is then defined using the following formula:
\[
f(u,v)=\sum_{x\in S(v)}d(u,x)^{2}-\sum_{x\notin S(v)}d(u,x)^{2}
\]
The goal is to calculate $f(u, v)$ for each of the $q$ given pair of vertices. As the answer can be rather large it's enough to print it modulo $10^{9} + 7$.
|
We solve this problem by answering queries offline. We'll first store in each vertex $v$ number of vertices such as $x$ for which we must calculate $f(v, x)$ . starting from the root. We'll keep two arrays $a$ and $b$. Suppose we're at vertex $v$ right now then $a_{i}$ equals $d(i, v)^{2}$ and $b_{i}$ equal $d(i, v)$. Having these two arrays when moving from vertex $v$ to a child with an edge with weight $k$ one can note that $b_{i}$ for all $i$s inside subtree of $v$ decreases by $k$ and all other $b_{i}$s gets increased by $k$. Knowing this fact one can also update array $a$ as well. To calculate $f(v, x)$ it's enough to be able to calculate sum of $a_{i}$s for all $i$ inside subtree of $x$. Handling each of these operations is a well known problem and is possible using a segment tree. Overall complexity is $O((n + q)lgn)$. There is an online solution using dynamic programming as well.
|
[
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,700
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.