【递归】:poj1833,全排列

本文讨论了使用next_permutation函数优化数据排列过程中的问题,并提供了在特定情况下遇到runtime错误的解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://poj.org/problem?id=1833


使用

next_permutation(data+1,data+1+n) //data+1为起始位置,n为长度

runtime error,不知道哪错了,三个用例都能过。

# include<iostream>
# include<algorithm>
using namespace std;

# define N 1030

int main()
{
	int m,n,k,i,j,t;
	int data[N];
	cin>>m;
	for(i=1;i<=m;i++)
	{
		cin>>n>>k;
		for(j=1;j<=n;j++)
		{
			cin>>data[j];
		}

		t=1;
		for(j=2;j<=n;j++)
		{
			t*=j;//t=n!
		}
		k%=t;

		while(next_permutation(data+1,data+1+n)==true)
		{
			k--;
			if(k==0)
			{
				break;
			}			
		}
		if(k==0)
		{
			cout<<data[1];
			for(j=2;j<=n;j++)
			{
				cout<<" "<<data[j];
			}
			cout<<endl;
		}
		else
		{
			sort(data+1,data+1+n);//
			do
			{
				k--;
				if(k==0)
				{
					break;
				}
			}while(next_permutation(data+1,data+1+n)==true);

			cout<<data[1];
			for(j=2;j<=n;j++)
			{
				cout<<" "<<data[j];
			}
			cout<<endl;
		}
	}
	return 0;
}







# include<iostream>
# include<string>
# include<algorithm>
using namespace std;

string s;

void Swap(int i, int j)
{
	char si=s[i],sj=s[j];
	s[j]=si;
	s[i]=sj;
}

void NextPermutation(int n, int i)
{
	if(i==n-1)
	{
		cout<<s<<endl;
	}
	else
	{
		for(int j=i;j<n;j++)
		{
			Swap(i,j);
			NextPermutation(n,i+1);
			Swap(i,j);
		}
	}
}

int main()
{
	//cin>>s;
	//NextPermutation(s.length(),0); 

	cin>>s;
	cout<<s<<endl; 
	while(next_permutation(s.begin(),s.end())==true) //# include<algorithm>
	{
		cout<<s<<endl;
	}
	//prev_permutation();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值