1. Generate Permutations
- /* Rearranges the elements in the array into the lexicographically next
- greater permutation of elements. */
- int next_permutation(int p[], int n)
- {
- int i, j;
- for (i = n - 2; i >= 0 && p[i] > p[i+1]; --i);
- if (i < 0)
- return 0;
- for (j = n - 1; j > i && p[j] < p[i]; --j);
- p[i] ^= p[j], p[j] ^= p[i], p[i] ^= p[j];
- for (i = i + 1, j = n - 1; i < j; ++i, --j)
- p[i] ^= p[j], p[j] ^= p[i], p[i] ^= p[j];
- return 1;
- }
- /* Generate the next r-combination of the set {0, 1, ..., n-1} */
- int next_combination(int c[], int n, int r)
- {
- int i, j;
- for (i = r - 1; i >=0 && c[i] == n-r+i; --i);
- if (i < 0)
- return 0;
- c[i] += 1;
- for (j = i + 1; j < r; ++j)
- c[j] = c[i] + j - i;
- return 1;
- }
- /* Greatest Common Divisor */
- int gcd(int a, int b)
- {
- for (a %= b; a != 0; a %= b)
- a ^= b, b ^= a, a ^= b;
- return b;
- }