https://www.nowcoder.com/practice/b698e67a2f5b450a824527e82ed7495d?tpId=85&tqId=29837&tPage=1&rp=1&ru=/ta/2017test&qru=/ta/2017test/question-ranking
数据太弱了,O(n*10!)都能过
简单的暴力,每次交换两个数遍历全排列,统计交换的两个数之间对顺序对个数的影响
#include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<algorithm> #include<iostream> #include<queue> #include<map> #include<cmath> #include<set> #include<stack> #define ll long long #define pb push_back #define max(x,y) ((x)>(y)?(x):(y)) #define min(x,y) ((x)>(y)?(y):(x)) #define cls(name,x) memset(name,x,sizeof(name)) #define fs first #define sc second #define mp make_pair #define L(x) (1<<x) #define next Next #define index Index using namespace std; const int inf=1e9+10; const ll llinf=1e17+10; const int maxn=1e2+10; const int maxm=25e2+10; const int mod=1e9+7; int n,k; int num[maxn]; int save[20]; int vis[maxn]; int index=0; int ans=0; int solve(int *num,int k1,int k2,int val) { if(k1==k2) return val; for(int i=k1+1;i<=k2-1;i++) { if(num[i]>num[k1]&&num[i]<num[k2]) val-=2; else if(num[i]<num[k1]&&num[i]>num[k2]) val+=2; } if(num[k1]<num[k2]) val--; else if(num[k1]>num[k2]) val++; return val; } void dfs(int *num,int st,int val) { if(st==index-1) { if(val==k) ans++; return ; } for(int j=st;j<index;j++) { int temp=solve(num,save[st],save[j],val); swap(num[save[st]],num[save[j]]); dfs(num,st+1,temp); swap(num[save[st]],num[save[j]]); } } int main() { //freopen("in.txt","r",stdin); while(~scanf("%d %d",&n,&k)) { index=0; ans=0; cls(vis,0); for(int i=1;i<=n;i++) { scanf("%d",&num[i]); if(num[i]==0) save[index++]=i; vis[num[i]]=1; } for(int i=1,j=0;i<=n;i++) if(vis[i]==0) num[save[j++]]=i; int val=0; for(int i=1;i<=n;i++) for(int j=i+1;j<=n;j++) if(num[i]<num[j]) val++; dfs(num,0,val); printf("%d ",ans); } return 0; }