How many graphs on $n$ labeled vertices have treewidth at most $k$, and how can we sample such graphs uniformly at random? We devise algorithms for both tasks that run in polynomial time for every fixed $k$. Efficient counting and sampling for this class had been listed as fully open. More generally, our algorithms count and sample graphs of treewidth at most $k$ satisfying any property expressible in monadic second-order logic with quantification over vertex and edge sets ($\mathrm{MSO}_2$). This provides an algorithmic counterpart to Courcelle's theorem for counting and generating graphs subject to logical constraints. The algorithms also support vertex colors and nonnegative rational vertex and edge weights determined by colors. They compute the exact total weight of all admissible colored graphs and sample each graph with probability proportional to its weight. Let $θ$ comprise the treewidth bound, color set, and logical sentence, and let $L$ denote the encoding length of the weights. Counting uses $f(θ)O(n^2)$ arithmetic operations and $f(θ)\operatorname{poly}(n,L)$ bit operations, where $f$ is a computable function. Generating each sample requires $f(θ)\operatorname{poly}(n,L)$ bit operations in expectation.
翻译:暂无翻译