PrevNext

Resources

Resources
Open Math Books
University of Illinois Urbana-Champaign

Introduction

A planar graph is a set of vertices and edges that can be drawn such that no two edges cross each other. Often, it is possible to make a graph planar by redrawing the edges.

Non-Planar Graph

Example of a Non-Planar Graph

Planar Graph

Example of a Planar Graph

Given a planar graph, we can apply Euler's formula VE+F=2V - E + F = 2 to relate the number of vertices (VV), edges (EE), and faces (FF) of the graph.

The equation is related to the theorem that for any convex polyhedron, VE+F=2V - E + F = 2 will hold true, since every convex polyhedron can be transformed into a planar graph.

This can be expanded to graphs that are not connected to incorporate connected components. To avoid overcounting the external face of the connected components, the equation subsequently becomes VE+F=C+1V - E + F = C + 1, where CC is the number of connected components.

Example - Build Gates

Focus Problem – try your best to solve this problem before continuing!

View Internal Solution

Explanation

We define the nodes as points with a fence, and edges as fence segments. Notice that because no two fence segments cross each other, the fence forms a planar graph in which every closed-off region, including the region outside the fences, counts as a face. Every time we combine two faces by adding a gate, the number of faces decreases by 11. Thus, the answer is the number of faces in the graph minus one.

As a reminder, Euler's formula states that F=EV+2F=E-V+2, where the fences represent edges and the coordinates represent vertices. To count the edges, we only need to count the unique unit-length segments Farmer John places. Likewise, to count the vertices, we only need to count the unique positions Farmer John visits. Both counts can be obtained using sets.

Once we calculate these values, we can plug them back into the formula and obtain our answer.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("gates.in", "r", stdin);
freopen("gates.out", "w", stdout);
int n;
cin >> n;

Problems

StatusSourceProblem NameDifficultyTags
KattisVery Hard
Show TagsDSU, Euler's Formula
CFVery Hard
Show TagsEuler's Formula, FFT
CFVery Hard
Show TagsEuler's Formula
PlatinumVery Hard
APIOVery Hard
Show Tags2DRQ, Euler's Formula, Persistent SegTree
PlatinumVery Hard
Show TagsEuler's Formula

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext