public class ExactTree {
int calc(int n, int n1, int s1, int n2, int s2)
{
return s1 + s2 + n1 * (n - n1);
}
public int getTree(int n, int m, int r)
{
int[][] dp = new int[n+1][m];
for(int i = 1; i <= n; i++)
for(int j = 0; j < m; j++)
dp[i][j] = -1;
dp[1][0] = 0;
for(int s = 2; s <= n; s ++)
for(int a = 1; a < s; a ++)
for(int m1 = 0; m1 < m; m1 ++)
for(int m2 = 0; m2 < m; m2 ++)
{
int b = s - a;
if(dp[a][m1] == -1) continue;
if(dp[b][m2] == -1) continue;
int v = calc(n, a, dp[a][m1], b, dp[b][m2]);
if(dp[s][v%m] == -1 || dp[s][v%m] > v)
dp[s][v%m] = v;
}
return dp[n][r];
}
}
cHVibGljIGNsYXNzIEV4YWN0VHJlZSB7CgogICAgaW50IGNhbGMoaW50IG4sIGludCBuMSwgaW50IHMxLCBpbnQgbjIsIGludCBzMikKICAgIHsKICAgICAgICByZXR1cm4gczEgKyBzMiArIG4xICogKG4gLSBuMSk7CiAgICB9CgogICAgcHVibGljIGludCBnZXRUcmVlKGludCBuLCBpbnQgbSwgaW50IHIpCiAgICB7CiAgICAgICAgaW50W11bXSBkcCA9IG5ldyBpbnRbbisxXVttXTsKICAgICAgICBmb3IoaW50IGkgPSAxOyBpIDw9IG47IGkrKykKICAgICAgICAgICAgZm9yKGludCBqID0gMDsgaiA8IG07IGorKykKICAgICAgICAgICAgICAgIGRwW2ldW2pdID0gLTE7CiAgICAgICAgZHBbMV1bMF0gPSAwOwogICAgICAgIGZvcihpbnQgcyA9IDI7IHMgPD0gbjsgcyArKykKICAgICAgICAgICAgZm9yKGludCBhID0gMTsgYSA8IHM7IGEgKyspCiAgICAgICAgICAgICAgICBmb3IoaW50IG0xID0gMDsgbTEgPCBtOyBtMSArKykKICAgICAgICAgICAgICAgICAgICBmb3IoaW50IG0yID0gMDsgbTIgPCBtOyBtMiArKykKICAgICAgICAgICAgICAgICAgICB7CiAgICAgICAgICAgICAgICAgICAgICAgIGludCBiID0gcyAtIGE7CiAgICAgICAgICAgICAgICAgICAgICAgIGlmKGRwW2FdW20xXSA9PSAtMSkgY29udGludWU7CiAgICAgICAgICAgICAgICAgICAgICAgIGlmKGRwW2JdW20yXSA9PSAtMSkgY29udGludWU7CiAgICAgICAgICAgICAgICAgICAgICAgIGludCB2ID0gY2FsYyhuLCBhLCBkcFthXVttMV0sIGIsIGRwW2JdW20yXSk7CiAgICAgICAgICAgICAgICAgICAgICAgIGlmKGRwW3NdW3YlbV0gPT0gLTEgfHwgZHBbc11bdiVtXSA+IHYpCiAgICAgICAgICAgICAgICAgICAgICAgICAgICBkcFtzXVt2JW1dID0gdjsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgcmV0dXJuIGRwW25dW3JdOwogICAgfQp9Cg==