learngraphtheory.org

Guest User

Using app without sign in

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

p-Median Calculator

Where should the p warehouses go?

Opens p facilities so that the demand-weighted distance to the nearest one is as small as possible: greedy, then Teitz-Bart swaps

Time: O(V³) + O(p·V²) per round
Space: O(V²)
Use Case: Warehouses, clinics, schools, charging stations
Showing the example graph for this algorithm.
Auto10
Algorithm Execution

Select an algorithm and generate steps to begin visualization

About p-Median (Facility Location)

The p-median problem chooses p vertices of a network at which to open facilities, such as warehouses, clinics, schools or fire stations, so that the total distance from every customer to its nearest facility, weighted by the customer's demand, is as small as possible. S. Louis Hakimi introduced it in 1964. It is NP-hard, so practical tools combine a fast heuristic with local improvement, and solve small cases exactly.

How it works

Distances are shortest paths through the network, and every vertex is a customer whose demand (for example its population) multiplies its distance. The greedy phase opens facilities one at a time, each time choosing the vertex that lowers the total cost the most. Greedy choices can lock in a facility that later ones make unnecessary, so the vertex substitution phase of Teitz and Bart (1968) then tries swapping an open facility for a closed vertex, keeps any swap that lowers the cost, and stops when no single swap helps. On small graphs this page also checks every possible choice of p facilities to show whether the heuristic reached the optimum.

Applications

The p-median model places warehouses and distribution centres, hospitals and clinics, schools, bank branches, charging stations and emergency bases, and it is the classic location-allocation model of operations research and GIS. Related models change the goal: the p-center problem minimises the worst distance instead of the total, which suits ambulances and fire stations.

Pseudocode

The p-median problem opens p facilities so that the total demand-weighted distance from every vertex to its nearest open facility is as small as possible. The visualizer builds a solution greedily and then improves it with the Teitz-Bart vertex swap.

PMedian(graph, p):
    d = shortest path distances between all pairs
    cost(F) = sum over v of demand(v) * min over f in F of d(v, f)

    F = {}
    repeat p times:                       // greedy
        add the vertex that lowers cost(F) the most

    while some swap lowers cost(F):        // Teitz-Bart
        close one f in F, open one v not in F
    return F, each vertex served by its nearest facility

Hakimi proved in 1964 that some optimal set of medians always lies on vertices, so only the n vertices need to be considered as sites, not every point along the edges. The greedy phase gives a good start, but its first choice is made as if only one facility existed, and the swap phase is what corrects it.

Worked example, step by step

Place two facilities among the ten towns of the example this page loads. The demand of each town is its population in thousands, and travel follows the road network.

Example graph: Towns A 8, B 3, C 6, D 2, E 4 in the west and F 1, G 5, H 9, I 3, J 4 in the east. Roads A-B 6, A-C 5, B-C 6, A-D 8, C-D 6, C-E 5, D-E 7, C-F 8, E-F 7, F-G 8, F-H 7, F-I 7, G-H 5, H-I 6, H-J 5 and I-J 6.

  1. Best single site. With one facility, F wins, since it sits between the two halves of the map. Its total is 422: for example the 8 thousand people of A travel 13 each, which alone contributes 104.
  2. Greedy second site. Adding C serves the whole west from close by and brings the total down to 262. The greedy phase is now finished, with facilities at F and C.
  3. Swap F for H. Once C is open, F only serves the east, and does it from the edge. Closing F and opening H, the largest town of the east, lowers the total from 262 to 160.
  4. Local optimum. No single swap of an open facility for a closed one lowers 160, so the search stops. Comparing all 45 pairs of sites confirms that 160 is the global optimum here.

The facilities go to C and H. C serves A, B, C, D and E at a cost of 90, and H serves F, G, H, I and J at a cost of 70, for a total of 160. The greedy answer {F, C} was 64 percent more expensive. F is the best place for one facility and among the worst for one of two, which is the typical reason greedy placement needs an improvement phase.

Complexity, and where it comes from

Time: NP-hard, O(p n^2) per greedy or swap pass · Space: O(n^2)

The problem is NP-hard when p is part of the input, as Kariv and Hakimi showed in 1979, and checking every set of p sites costs C(n, p) evaluations. The heuristic first needs all-pairs shortest distances, O(n^3) with Floyd-Warshall or n Dijkstra runs on a sparse graph. Evaluating one candidate set costs O(n). The greedy phase tries n candidates for each of the p facilities, O(p n^2) in total, and one swap pass tries p (n - p) swaps, also O(p n^2). The number of passes is not bounded by a small polynomial in theory, but it is small in practice. Exact solutions for a few hundred vertices come from integer programming.

When to use p-Median (Facility Location), and when not to

Location problems differ in what they minimise. Choose the model that matches the service.

AlternativePrefer it whenCost
p-centerThe worst case matters more than the average, as for fire stations or ambulances. Minimise the largest distance to a facility.NP-hard
Uncapacitated facility locationOpening a facility has a cost, and the number of facilities should be decided by the model instead of fixed at p.NP-hard
1-median (single facility)There is only one site to choose. Try every vertex.O(n^2) after distances
k-medoids (PAM)The same objective in clustering, with dissimilarities between data points instead of road distances.O(k (n - k)^2) per pass
k-meansPoints live in the plane, centres may be anywhere, and squared Euclidean distance is the right measure.O(n k i)

Common pitfalls

  • Stopping after the greedy phase. Greedy placement locks in its first choice, which is made for a single facility. In the example that alone costs 64 percent extra. Always follow it with swaps or another local search.
  • Using straight-line distances. Customers travel on roads. Two towns close on the map can be far apart by road, and the medians of the road network can differ from those of the map.
  • Forgetting the demand weights. Without weights the model treats a hamlet and a city alike. The optimal sites then drift toward the geometric middle of the vertices instead of toward the people.
  • Minimising the average when the worst case matters. A p-median solution can leave a remote vertex very far from any facility if it has little demand. For emergency services that is unacceptable, and the p-center model is the right one.

Frequently asked questions

What is the p-median problem?
Given a network with a demand at each vertex, the p-median problem chooses p vertices as facilities so as to minimise the total demand-weighted distance from every vertex to its nearest facility. It models warehouses, schools, clinics and other services where the average travel cost matters.
How is the p-median problem solved?
Exactly with integer programming for instances up to a few hundred vertices, and otherwise with heuristics. A standard combination is greedy placement followed by the Teitz-Bart interchange, which keeps swapping one open facility for a closed vertex while that lowers the cost.
What is the difference between p-median and p-center?
p-median minimises the total, or equivalently the average, weighted distance to the nearest facility. p-center minimises the largest distance. p-median suits commercial services, while p-center suits emergency services where nobody may be left too far away.
Why can the facilities be placed on vertices?
Hakimi's theorem of 1964 shows that, for the p-median objective on a network, some optimal solution has every facility on a vertex. Along an edge, the distance from each demand point to the facility is the smaller of two linear functions, so the total cost is concave in the position and is minimised at an endpoint.
Is the p-median problem NP-hard?
Yes, when p is part of the input, as shown by Kariv and Hakimi in 1979. For a fixed p it can be solved by checking all C(n, p) sets of sites, which is polynomial but quickly becomes impractical as p grows.

Related algorithms: Facility Location, K-Means Logistics Clustering, Floyd-Warshall Algorithm, Capacitated Vehicle Routing (CVRP)

Interactive Controls

Zoom Controls

34%
Nodes: 10
Edges: 16