目录
- #include
- using namespace std;
-
- const int maxn=103;
-
- int n,a[maxn];
-
- int main(){
- scanf("%d",&n);
- for(int i=1;i<=n;++i)scanf("%d",&a[i]);
- int pos,sw;
- for(pos=n-1;pos>=1;--pos){
- if(a[pos]>a[pos+1])break;
- }
- for(sw=pos+1;sw<=n;++sw){
- if(a[sw]>a[pos])break;
- }--sw;
- // printf("%d %d !\n",pos,sw);
- swap(a[pos],a[sw]);
- sort(a+pos+1,a+n+1,greater<int>());
- for(int i=1;i<=n;++i)
- printf("%d ",a[i]);
- puts("");
- return 0;
- }
- #include
- #include
- #include
- using namespace std;
-
- int main()
- {
- int n;
- cin >> n;
- int a[105];
- for (int i = 0; i < n; i++)
- {
- cin >> a[i];
-
- }
- prev_permutation(a, a + n);
- for (int i = 0; i < n; i++)
- {
- cout<< a[i]<<" ";
-
- }
- return 0;
- }
- #include
- #include
- #include
- #include
- using namespace std;
-
- const int maxn = 103;
-
- int n, a[maxn];
-
- int main() {
- cin >> n;
- for (int i = 1; i <= n; ++i) cin>>a[i];
- int pos, sw;
- for (pos = n - 1; pos >= 1; --pos) {
- if (a[pos] < a[pos + 1])break;//与prev_permulation不同的地方 > 变 <
- }
- for (sw = pos + 1; sw <= n; ++sw) {
- if (a[sw] < a[pos])break;//与prev_permulation不同的地方 > 变 <
- }--sw;
- // printf("%d %d !\n",pos,sw);
- swap(a[pos], a[sw]);
- sort(a + pos + 1, a + n + 1, greater<int>());
- for (int i = 1; i <= n; ++i)
- printf("%d ", a[i]);
- puts("");
- return 0;
- }
- #include
- #include
- #include
- using namespace std;
-
- int main()
- {
- int n;
- cin >> n;
- int a[105];
- for (int i = 0; i < n; i++)
- {
- cin >> a[i];
-
- }
- next_permutation(a, a + n);
- for (int i = 0; i < n; i++)
- {
- cout<< a[i]<<" ";
-
- }
- return 0;
- }
全排列没有现成的函数,我们可以利用 next_permulation() 获得。
1.先将字符串从小到大排序
2.用 do~while 循环,使用next_permultion() 不断获取下一个排列(字典序更小的排列)
- #include
- #include
- #include
- using namespace std;
-
- int main()
- {
- int n;
- cin >> n;
- int a[105], b[105];
-
- for (int i = 0; i < n; i++)
- {
- cin >> a[i];
-
- }
- sort(a, a + n);
- do {
- for (int i = 0; i < n; i++)
- {
- cout << a[i] << " ";
- }
- cout << endl;
-
- } while (next_permutation(a, a + n));
-
- return 0;
- }
is_permutation(),只要元素相同就返回 true ,而不管顺序是否相同
- #include
- #include
- #include
- using namespace std;
-
- int main()
- {
- int n;
- cin >> n;
- int a[105],b[105];
- for (int i = 0; i < n; i++)
- {
- cin >> a[i];
- b[i] = a[i];
-
- }
- next_permutation(a, a + n);
- cout << "a :" << endl;
- for (int i = 0; i < n; i++)
- {
- cout << a[i] << " ";
- }
- cout << endl;
- cout << "b :" << endl;
- for (int i = 0; i < n; i++)
- {
- cout << b[i] << " ";
- }
- cout << endl;
- if (is_permutation(a, a + n,b, b + n))
- {
- cout << "a 与 b 相等\n";
- }
- else
- {
- cout << "a 与 b 不相等\n";
- }
- return 0;
- }