您的位置:首页 > 其它

基于排列的数列顺序对

2016-08-02 22:21 183 查看
题目描述:

洋洋的作业本上有一个长度为n的排列A,这个排列包含了从1到n的n个数,但是因为一些原因,其中一些位置(不超过10个)看不清了,但是洋洋记得这个数列顺序对的数量为k,顺序对是指满足i<j,且A[i] < A[j]的对数,请帮助洋洋计算出,符合这个要求的合法排列的数目。

输入描述:

每个输入包含一个测试用例。每个测试用例的第一行包含两个整数n和k(1 <= n <= 100,0 <= k <= 1000000000),接下来的1行,包含n个数字表示排列A,其中等于0的项表示看不清的位置(不超过10个)。

输出描述:

输出一行表示合法的排列数目。

输入例子:

5 5

4 0 0 2 0

输出例子:

2

代码:

<pre name="code" class="cpp">#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int ordernum(vector<int> n)
{
int ns = n.size();
int c = 0;

for(int i=0; i<ns-1; i++)
{
if(!n[i])
continue;
for(int j=i+1; j<ns; j++)
{
if(!n[j])
continue;
if(n[i] < n[j])
c++;
}
}

return c;
}

int main(int argc, char* argv[])
{
int n, k;
vector<int> A;

bool *pB;
vector<int> vl; // the left number
vector<int> vp; // the left position
while(cin >> n >> k)
{
pB = new bool
;
for(int i=0; i<n; i++)
pB[i] = false;

int t;
for(int i=0; i<n; i++)
{
cin >> t;
A.push_back(t); // the zeros are the undefined

if(t)
pB[t-1] = true;
else
vp.push_back(i);
}
for(int i=0; i<n; i++)
{
if(!pB[i])
{
vl.push_back(i+1);
}
}

int nl = vl.size(); // the left number
int cA = ordernum(A);

int cl;
int csum = 0;
if(cA > k)
{
cout << 0 << endl;
}
else
{
do{
cl = ordernum(vl);
if(cl+cA > k)
continue;
// the cross
int cc = 0; // the cross number
for(int i=0; i<nl; i++)
{
for(int j=vp[i]-1; j>=0; j--) // the front cross
{
if(0 == A[j]) // detlete zeros
continue;

if(A[j] < vl[i])
cc++;

if(cc+cA+cl > k)
break;
}

if(cc+cA+cl > k)
break;

for(int j=vp[i]+1; j<n; j++)  // the back cross
{
if(vl[i] < A[j]) // because the A[j] is the  greate number, there is no need to judge the zeros
cc++;

if(cc+cA+cl > k)
break;
}
}
if(cc+cA+cl == k)
{
for(vector<int>::iterator it=vl.begin(); it!=vl.end(); it++)
cout << *it << " ";

cout << " cA: " << cA << " cl: " << cl << " cc: " << cc << endl;
csum++;

}
//csum++;

}while( next_permutation(vl.begin(), vl.end()) );
}

cout << csum << endl;

delete pB;
A.clear();
vl.clear();
vp.clear();
}

return 0;
}



结果显示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐