题意:
给定一副n(n≤3000)n(n\leq 3000)n(n≤3000)个顶点,mmm条有向边的图,可以在图中添加有向边,求添加的最少边数,使得这副图满足:如果顶点aaa到顶点bbb有边,顶点bbb到ccc右有边,那么顶点aaa到顶点ccc也有边
Solution:
考虑一条单向链,按指向的方向按顺序是A,B,C,D,...A,B,C,D,...A,B,C,D,...
显然,A→B,B→CA\rightarrow B,B\rightarrow CA→B,B→C需要添加一条边A→CA\rightarrow CA→C,此时A→C,C→DA\rightarrow C,C\rightarrow DA→C,C→D需要添加A→DA\rightarrow DA→D。更一般的情况是,在从AAA出发能到达的顶点里,只有与AAA距离为1的不需要添加边,只需要和其他点建边即可,并查集不适合有向图,O(n)O(n)O(n)的搜索可以满足要求,每个顶点搜索一次,总复杂度O(n2)O(n^2)O(n2)
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include