Exact and rapid linear clustering of networks with dynamic programming