AcWing 420. 火星人
原题链接
中等
作者:
Jocelin
,
2021-03-11 21:02:25
,
所有人可见
,
阅读 342
算法1
dfs+遍历 超时了
#include<bits/stdc++.h>
using namespace std;
#define N 10010
bool st[N];
int a[N];
vector<int> res;
int n;
void dfs(int u)
{
if(u==n+1)
{
int temp = 0;
for(int i = 1; i <= n;i++)
{
temp = temp*10 + a[i];
}
res.push_back(temp);
// cout << temp << endl;
return;
}
for(int i =1;i <=n;i++)
{
if( st[i] !=1)
{
st[i] = 1;
a[u] = i;
dfs(u+1);
st[i] = 0;
}
}
}
void printfNum(int num)
{
string str;
while(num)
{
int t = num % 10;
str += (t + '0');
num /= 10;
}
reverse(str.begin(),str.end());
for(int i = 0; i < str.size();i++)
cout << str[i] << " ";
}
int main()
{
cin >> n;
dfs(1);
int add_num = 0;
cin >> add_num;
int cur_index = 0;
int cur_date = 0;
for(int i = 1; i <= n;i++)
{
int t;
scanf("%d",&t);
cur_date = cur_date*10 + t;
}
// cout << cur_date;
for(int i = 0; i < res.size(); i++)
{
if( cur_date == res[i])
cur_index = i;
}
printfNum(res[cur_index+add_num]);
// cout << res[cur_index+add_num] << endl;
return 0;
}
算法2
(next_permutation) $O(n)$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int n, m;
int w[N];
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ ) cin >> w[i];
while (m -- )
{
next_permutation(w , w + n );
}
for (int i = 0; i < n; i ++ ) cout << w[i] << ' ';
cout << endl;
return 0;
}