LoginSignup
2
2

More than 5 years have passed since last update.

順列や組合せを求めるプログラム

Last updated at Posted at 2019-01-17

ソースコード

#include<bits/stdc++.h>
using namespace std;
const int MAX_N=100;
int f;
int v[MAX_N];
int N,R;

void combination(int now,int cnt,int goal){
  if(cnt==goal){
    for(int i=0;i<N;i++)if(v[i])cout<<i;
    cout<<endl;
    return;
  }
  for(int i=now;i<N;i++){
    if(!(f&(1<<i))){
      v[i]=1;
      f|=(1<<i);
      combination(i+1,cnt+1,goal);
      v[i]=0;
      f&=~(1<<i);
    }
  }
}

void permutation(int now,int cnt,int goal){
  if(cnt==goal){
    for(int i=0;i<goal;i++)cout<<v[i];
    cout<<endl;
    return;
  }
  for(int i=0;i<N;i++){
    if(!(f&(1<<i))){
      v[now]=i;
      f|=(1<<i);
      permutation(now+1,cnt+1,goal);
      v[now]=-1;
      f&=~(1<<i);
    }
  }
}
int main() {
  cin>>N>>R;
  cout<<"permutation"<<endl;
  for(int i=0;i<N;i++)v[i]=-1;
  permutation(0,0,R);
  cout<<endl;
  cout<<"combination"<<endl;
  for(int i=0;i<N;i++)v[i]=0;
  combination(0,0,R);
  cout<<endl;
  return 0;
}

実行例

4 3
permutation
012
013
021
023
031
032
102
103
120
123
130
132
201
203
210
213
230
231
301
302
310
312
320
321

combination
012
013
023
123
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2