Olympiad in Informatics

POJ1737: Connected Graph — Solution

Main Idea

The counting equation and the idea behind this problem are really interesting; let's start the analysis below.

Let \(F[i]\) be the number of kinds of undirected connected graphs with \(i\) vertices. We can try inclusion–exclusion: the number of kinds of undirected graphs on \(n\) vertices is \(2^{\frac{n(n-1)}{2}}\), and we can enumerate \(k\) and remove the connected components of size \(k\) to keep connectivity. Since this problem requires the vertices to be labeled, the number of kinds of these connected components is:

\[\sum_{k=1}^{i-1}(F[k]*C_{i-1}^{j-1}*2^{\frac{(i-k)(i-k-1)}{2}})\]

Here, \(F[k]\) is the number of connected components when the component size is \(k\), then \(C_{i-1}^{j-1}\) is the contribution of the labels to the answer, and after that the number of kinds of the other, remaining block is \(2^{\frac{(i-k)(i-k-1)}{2}}\). Just multiply them together.

The strengthened version of this problem requires knowledge of NTT and convolution: BZOJ 3456: City Planning — Solution

Code

// POJ1737.cpp
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#define ll long long
using namespace std;
const int MAX_N = 60;
ll f[MAX_N], C[MAX_N][MAX_N], tmp;
int main()
{
    C[1][0] = C[1][1] = 1;
    for (int i = 2; i < MAX_N; i++)
    {
        C[i][0] = 1;
        for (int j = 1; j < MAX_N; j++)
            C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
    }
    f[1] = 1;
    for (int i = 2; i < MAX_N; i++)
    {
        f[i] = (1 << ((i * (i - 1)) >> 1));
        for (int j = 1; j < i; j++)
            f[i] -= f[j] * C[i - 1][j - 1] * (1 << (((i - j) * (i - j - 1)) >> 1));
    }
    while (~scanf("%d", &tmp) && tmp != 0)
        printf("%lld\n", f[tmp]);
    return 0;
}