Outline
- Problem
- Solution
- Requirements
- Algorithm
- Complexity Analysis
- Example Problems
- CF-1957F2
I thought of this idea while solving 1957F2. It is extremely easy, cute (at least compared to the official solution), and can be generalized, so I'll share it here.
Problem
Given two sets of vertices
and and a boolean function , we define a bipartite graph We need to find
adjacent vertices in for every node .
Solution
Requirements
- We can compute
in time. - We can construct a data structure
from some subset in time, such that we can query if there exists some such that in time.
Algorithm
Definitions
-
-
- Let
be the query function which checks if there exists some such that .
We will use block decomposition with
- Divide
into disjoint subsets of size . Let the 'th subset be - Iterate over the subsets, while maintaining a list
of all for which we have found neighbors till that point of time ( initially). - At subset
, we will do the following:- Construct
. - Create an empty list
, and add to (also delete it from ) for all such that . - Compute
, and mark as a neighbor of if . - For every
for which we haven't found neighbors yet, add back to .
- Construct
Note
Complexity Analysis
The cumulative time for building all the data structures will be
For queries:
- At every
, we query . Since , this takes time. - It's easy to see that every node
is added to for at most distinct values of . Every time a is added to , we compute for distinct values of . This takes time.
Therefore the total time taken is:
The choice of
Example Problems
1. CF-1957F2
You are given an undirected tree of
nodes. Each node has a value written on it. You have to answer queries related to the tree. You are given
queries. In each query, you are given 5 integers, , , , , and . Denote the count of nodes with value on the path with , and the count of nodes with value on the path with . If there are such values of such that , output any such values in any order.