Cod sursa(job #2729300)

Utilizator avtobusAvtobus avtobus Data 24 martie 2021 16:08:55
Problema Combinari Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

ifstream fin {"combinari.in"};
ofstream fout {"combinari.out"};

const int Nmax = 20;
char used[Nmax];
int N, K;

void write() {
  for(int i = 0; i < N; i++) {
    if (used[i]) {
      fout << i + 1 << ' ';
    }
  }
  fout << '\n';
}

bool my_next_combination(int first, int last) {
  int i = last - 1;
  int cnt = 0;
  while(i >= first && used[i]) {
    --i; ++cnt;
  }
  if (cnt == K) { // this should not matter; just return the next combination whatever K is.
    reverse(used+first, used+last);
    return false;
  }
  while(i > first && !used[i-1]) { --i;}
  if (i == first) {
    return false; // reverse the `used` array back to the beginning.
  }
  swap(used[i-1], used[i]);
  reverse(used+i+1, used+last);
  return true;
}

int main(void) {
  // freopen("combinari.in", "r", stdin);
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);
  fin >> N >> K;
  memset(used, 0, sizeof(used));
  for(int i = 0; i< K; i++) {
    used[i] = 1;
  }
  do {
    write();
  } while(my_next_combination(0, N));

  return 0;
}