题意:输入一个数 n(1,1000000),n 的全排列组成的集合 A,长度为 n*n!,在集合 A 中,输出所有长度为 n 的子集中数字和为 n*(n+1)/2 的子集个数。
思路:用 dfs 打表找规律,发现 ans[n] = n! + ans[n-1]*n。
AC代码:
#include<bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define per(i,a,n) for (int i=a;i<n;i++)
#define rep(i,a,n) for (int i=n-1;i>=a;i--)
#define show(x) cout<<x<<endl;
#define showEnd(x) cout<<x<<endl; return 0;
#define show_(x) cout<<x<<" ";
#define showxy(x,y) cout<<x<<" "<<y<<endl;
typedef long long ll;
const int maxn = 1000005;
const int INF = 0x3f3f3f3f;
const int MOD = 998244353;
int i,j,n;
ll a[maxn],b[maxn];
int main()
{
IO
while(cin>>n)
{
a[0] = 1,b[0] = 1;
for(i = 1; i <= n; i++)
{
b[i] = i*b[i-1]%MOD;
ll temp = a[i-1] - 1;
a[i] = (b[i]%MOD + i*temp%MOD)%MOD;
// showxy(a[i], b[i])
}
show(a[n])
}
return 0;
}
打表代码:
#include<bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define per(i,a,n) for (int i=a;i<n;i++)
#define rep(i,a,n) for (int i=n-1;i>=a;i--)
#define show(x) cout<<x<<endl;
#define showEnd(x) cout<<x<<endl; return 0;
#define show_(x) cout<<x<<" ";
#define showxy(x, y) cout<<x<<" "<<y<<endl;
typedef long long ll;
const int maxn = 1000005;
const int INF = 0x3f3f3f3f;
const int MOD = 998244353;
int i,j,n,vis[maxn],perm[maxn],ans;
vector<int> v;
void dfs(int step)
{
if(step == n+1)
{
for(int i = 1; i <= n; i++)
{
v.push_back(perm[i]);
}
}
for(int i = 1; i <= n; i++)
{
if(!vis[i])
{
vis[i] = 1;
perm[step] = i;
dfs(step+1);
vis[i] = 0;
}
}
}
int main()
{
IO
while(cin>>n)
{
memset(vis, 0, sizeof(vis));
ans = 0;
v.clear();
dfs(1);
for(i = 0; i < v.size(); i++)
{
int temp = 0;
for(j = i; j < i+n; j++)
{
temp += v[j];
}
if(temp == (n*(n+1)/2)) ans++;
}
show(ans)
}
return 0;
}