Typical BackPack problem but with the limited scale of test data, a straight forward brutal force search could do it. The search space is the permutation of subsets of all songs, for each song we have two choice - choose or not choose. Iterate the sequence under the constraint of ordering.
intgcd(int a, int b){ if (b == 0) return a; a %= b; return gcd(b, a); }
int n, m, p; intmain(){ ifstream fin("fence9.in"); ofstream fout("fence9.out"); fin >> n >> m >> p; int ret = p * m / 2.0 - (gcd(m, n) + gcd(m, abs(p - n)) + p) / 2.0 + 1; cout << ret << endl; fout << ret << endl; }