蒟蒻成长记录
排列数
算是记录一个求全排列的方法吧,()
#include <iostream> #include <string.h> #include <stdio.h> #include <vector> #include <map> #include <queue> #include <algorithm> #include <math.h> #include <cstdio> #include <utility> #define inf 0x3f3f3f3f #define endl '\n' #define int long long using namespace std; const int N = 1e5+10; //typedef long long ll; int n,m,t,a[N]; bool vis[N]; void dfs(int x){ //if(x > n) return; if(x > n){ for(int i = 1; i <= n; i++) { cout << a[i] << ' '; } cout << endl; return ; } for(int i = 1; i <= n; i ++) { if(!vis[i]){ vis[i] = 1; a[x] = i; dfs(x + 1); vis[i] = 0; a[x] = 0; } } } signed main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin >> n; dfs(1); return 0; }
以后可以不用一直想着那个next_permutation那个了(又难记又不好控制)
该方法应用P1088 [NOIP2004 普及组] 火星人 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
还可以从任意给定的顺序进行全排列
如何控制可以看看该题题解:
#include <iostream> #include <string.h> #include <stdio.h> #include <vector> #include <map> #include <queue> #include <algorithm> #include <math.h> #include <cstdio> #include <utility> #define inf 0x3f3f3f3f #define endl '\n' #define int long long using namespace std; const int N = 1e5+10, M = 20; //typedef long long ll; int n,m,mars[N],ans; bool return0, vis[N] ; int a[N]; void dfs(int x) { if(return0) return ; if(x > n) { ans++; if(ans == m + 1){ return0 = 1; for(int i = 1; i <= n; i++) cout << a[i] << ' '; } return ; } for(int i = 1; i <= n ; i++ ) { if(!ans){ i = mars[x];//从给定的顺序进行排列 } if(!vis[i]){ vis[i] = 1; a[x] = i; dfs(x + 1); a[x] = 0; vis[i] = 0; } } } signed main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin >> n >> m; for(int i = 1; i <= n ;i ++) { cin >> mars[i]; } dfs(1); return 0; }
组合数
C(5,3)
#include <iostream> #include <string.h> #include <stdio.h> #include <vector> #include <map> #include <queue> #include <algorithm> #include <math.h> #include <cstdio> #include <utility> #define inf 0x3f3f3f3f #define endl '\n' #define int long long using namespace std; const int N = 1e5+10, M = 20; //typedef long long ll; int n,m,arr[N],ans = 1e9 ,A,B; bool return0, vis[N] ; void dfs(int x, int y) { if(x > m) { for(int i = 1; i <= m; i++) cout << arr[i] << ' '; cout << endl; return ; } for(int i = y;i <= n; i++) { if(!vis[i]) { vis[i] = 1; arr[x] = i; dfs(x + 1, i + 1); vis[i] = 0; arr[x] = 0; } } } signed main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin >> n >> m; dfs(1,1); return 0; }
例题