第八題:牛牛的作業薄上有一個長度為 n 的排列 A,這個排列包含了從1到n的n個數,但是因為一些原因,其中有一些位置(不超過 10 個)看不清了,但是牛牛記得這個數列順序對的數量是 k,順序對是指滿足 i < j 且 A[i] < A[j] 的對數,請幫助牛牛計算出,符合這個要求的合法排列的數目。
輸入例子:
5 5 4 0 0 2 0
輸出例子:
2
a[N]:保存輸入數據
b[N]:保存待驗證的數組
c[N]:保存缺失的數據
vist[N]:標志哪個數據已存在
index[N]:c[N]中元素的數據
#include<iostream> #include<algorithm> #include<memory.h> using namespace std; const int N=100; int a[N],b[N],visit[N]; int c[15]; bool judge(int n,int k,int b[]) { int ret=0; for(int i=1;i<=n;i++) { for(int j=i+1;j<=n;j++) { if(b[i]<b[j]) ret++; } } return ret==k; } int main() { int n,k; while(scanf("%d%d",&n,&k)>0) { memset(visit,0,sizeof visit); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); visit[a[i]]=1; } int tot=0; for(int i=1;i<=n;i++) { if(!visit[i]) c[tot++]=i;//保存缺失的那部分數字 } int index[15]={0,1,2,3,4,5,6,7,8,9,10}; int ans=0; do{ int idx=0; for(int i=1;i<=n;i++) { if(a[i]==0) b[i]=c[index[idx++]]; else b[i]=a[i]; } if(judge(n,k,b)) ans++; }while(next_permutation(index,index+tot)); cout<<ans<<endl; } }
next_permutation
這是一個求一個排序的下一個排列的函數,可以遍歷全排列,要包含頭文件<algorithm>
下面是以前的筆記 與之完全相反的函數還有prev_permutation
(1) int 類型的next_permutation
int main()
{
int a[3];
a[0]=1;a[1]=2;a[2]=3;
do
{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
} while (next_permutation(a,a+3)); //參數3指的是要進行排列的長度
//如果存在a之后的排列,就返回true。如果a是最后一個排列沒有后繼,返回false,每執行一次,a就變成它的后繼
}
輸出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果改成 while(next_permutation(a,a+2));
則輸出:
1 2 3
2 1 3
只對前兩個元素進行字典排序
顯然,如果改成 while(next_permutation(a,a+1)); 則只輸出:1 2 3
若排列本來就是最大的了沒有后繼,則next_permutation執行后,會對排列進行字典升序排序,相當於循環
int list[3]={3,2,1};
next_permutation(list,list+3);
cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
//輸出: 1 2 3
(2) char 類型的next_permutation
int main()
{
char ch[205];
cin >> ch;
sort(ch, ch + strlen(ch) );
//該語句對輸入的數組進行字典升序排序。如輸入9874563102 cout<<ch; 將輸出0123456789,這樣就能輸出全排列了
char *first = ch;
char *last = ch + strlen(ch);
do {
cout<< ch << endl;
}while(next_permutation(first, last));
return 0;
}
//這樣就不必事先知道ch的大小了,是把整個ch字符串全都進行排序
//若采用 while(next_permutation(ch,ch+5)); 如果只輸入1562,就會產生錯誤,因為ch中第五個元素指向未知
//若要整個字符串進行排序,參數5指的是數組的長度,不含結束符
(3) string 類型的next_permutation
int main()
{
string line;
while(cin>>line&&line!="#")
{
if(next_permutation(line.begin(),line.end())) //從當前輸入位置開始
cout<<line<<endl;
else cout<<"Nosuccesor\n";
}
}
int main()
{
string line;
while(cin>>line&&line!="#")
{
sort(line.begin(),line.end());//全排列
cout<<line<<endl;
while(next_permutation(line.begin(),line.end()))
cout<<line<<endl;
}
}
next_permutation 自定義比較函數
#include<iostream> //poj 1256 Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b) //'A'<'a'<'B'<'b'<...<'Z'<'z'.
{
if(tolower(a)!=tolower(b))
return tolower(a)<tolower(b);
else
return a<b;
}
int main()
{
char ch[20];
int n;
cin>>n;
while(n--)
{
scanf("%s",ch);
sort(ch,ch+strlen(ch),cmp);
do
{
printf("%s\n",ch);
}while(next_permutation(ch,ch+strlen(ch),cmp));
}
return 0;
}