之前在题解里看到“传递闭包”,一直以为是一种很高级的算法,后来上离散数学的时候学到了,发现其实蛮简单的。
从数学上来说,传递闭包是在集合
而这,把Floyd最短路算法稍微改一下即可。设E
是原来的关系矩阵,则可以这样写:
for (int k = 1; k <= n; ++k)
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
if (E[i][k] && E[k][j])
E[i][j] = 1;
就是依次判断:仅经由1号点能不能从i到达j,仅经由1、2号点能不能从i到达j……最后得到的E
是传递闭包的关系矩阵。 E[i][j]
如果等于1,则表示存在从i
到j
的路径。时间复杂度是
(POJ1975 Median Weight Bead)
Description
There are N beads which of the same shape and size, but with different weights. N is an odd number and the beads are labeled as 1, 2, ..., N. Your task is to find the bead whose weight is median (the ((N+1)/2)th among all beads). The