Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

模拟AC,非STL

Posted by yzzxliuchao at 2016-12-17 11:03:53 on Problem 1833
摘自:http://wenku.baidu.com/link?url=1xb84cvmj8woQVMuOyD2xsxMVMz36r3UYV1X7OkZ8H9TsH2qYf4GBeA4XZJeZbNp9TgZ90MtLPHZPFjFG8oxQJZHHN2hLKIQkeU8jMey38i
//解题思路
//假定给定排列中的n个数从左到右是A1,A2,A3…An。
//从An开始,往左边找,直到找到某个Aj,满足Aj-1  < Aj
//在Aj,Aj+1,…An中找到最小的比Aj-1大的数,将这个数和
//Aj-1互换位置
//将从位置j到位置n的所有数(共n-j+1个)从小到大重新排序
//排好序后,新的排列就是所要求的排列
//当然,按照题目要求,如果A1,A2,A3…An已经是降序
//那么,它的下一个排序就是An,An-1,An-2…A1 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 2000;
int a[maxn];
int cmp( const void *a , const void *b )
{
	return *(int *)a - *(int *)b;  //升序排序
	//return *(int *)b - *(int *)a; //降序排序
}

int main()
{
	//freopen("pailie.in","r",stdin);
	//freopen("pailie.out","w",stdout);
	
	int m;
	cin >> m;
	while(m--)
	{
		int n, k;
		cin >> n >> k;
			
		//排列存放在a[1]~a[n] 
		for(int i = 1; i <= n; i++)
			scanf("%d",&a[i]);
		a[0] = 10000; //确保a[0]比排列中所有的数都大
		
		while(k--)
		{
			int j;
			for(j = n; j >= 1 && a[j-1] > a[j]; j--);
						
			if(j >= 1)
			{
				int nMinLarger = a[j];
				int nMinIdx = j;
				//下面找出从a[j]及其后最小的比a[j-1]大的元素中的“最小值”
				for(int kk = j; kk <= n; kk++)
				{
					if(a[kk] < nMinLarger && a[kk] > a[j-1])
					{
						nMinLarger = a[kk];
						nMinIdx = kk;
					}
				}
				//交换位置
				a[nMinIdx] = a[j-1];
				a[j-1] = nMinLarger;
				
				//对a[j]~a[n]升序排列 
				qsort(a+j, n-j+1, sizeof(int), cmp);	
			}
			else //a里面的排列已经是降序了,那么下一个排列是1 2 3 …n 
			{
				for(int i = 1; i <= n; i++)
					a[i] = i;
			}	
		} 
		
		for(int i = 1; i <= n; i++)
			cout << a[i] << " ";
		cout << endl;
	}
	
	fclose(stdin);
	fclose(stdout);
	
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator