zoukankan      html  css  js  c++  java
  • PTA 10-排序6 Sort with Swap(0, i) (25分)

    题目地址

    https://pta.patest.cn/pta/test/16/exam/4/question/678

    5-16 Sort with Swap(0, i)   (25分)

    Given any permutation of the numbers {0, 1, 2,..., N-1N1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:

    Swap(0, 1) => {4, 1, 2, 0, 3}
    Swap(0, 3) => {4, 1, 2, 3, 0}
    Swap(0, 4) => {0, 1, 2, 3, 4}
    

    Now you are asked to find the minimum number of swaps need to sort the given permutation of the first NN nonnegative integers.

    Input Specification:

    Each input file contains one test case, which gives a positive NN (le 10^5105​​) followed by a permutation sequence of {0, 1, ..., N-1N1}. All the numbers in a line are separated by a space.

    Output Specification:

    For each case, simply print in a line the minimum number of swaps need to sort the given permutation.

    Sample Input:

    10
    3 5 7 2 6 4 9 0 8 1
    

    Sample Output:

    9



    /*
    评测结果
    时间	结果	得分	题目	编译器	用时(ms)	内存(MB)	用户
    2017-07-07 11:35	答案正确	25	5-16	g++	24	2	
    测试点结果
    测试点	结果	得分/满分	用时(ms)	内存(MB)
    测试点1	答案正确	15/15	2	1
    测试点2	答案正确	3/3	24	2
    测试点3	答案正确	3/3	12	1
    测试点4	答案正确	2/2	2	1
    测试点5	答案正确	1/1	2	1
    测试点6	答案正确	1/1	2	1
    
    有点技巧性的题目,mooc上讲了,主要是找排序的环。有0环的交换次数为n-1,无零环为n+1
    建了三个数组,A是存数,B是存i号元素放在了哪个位置,Checked是放这个元素有没有被访问过。
    
    坑:必须加一个全局变量做搜索函数起点的备忘录用,否则搜索函数反复调用会导致超时
    */
    #include<stdio.h>
    #define MAXN 100000
    int A[MAXN],B[MAXN],Checked[MAXN];
    int gFindBeginPosition=0;
    int FindUnchecked(int N)
    {
    	int i;
    	for(i=gFindBeginPosition;i<N;i++)
    	{
    		if(!Checked[i])
    			return gFindBeginPosition=i;
    	}
    	return -1;
    }
    
    
    int main()
    {
    	int i,N,p,sum;
    	int ringCount=0;
    	int nCount=0;
    	int zeroInPosition=0;
    	scanf("%d",&N);
    	for(i=0;i<N;i++)
    	{
    		scanf("%d",&A[i]);
    		B[A[i]]=i;
    	}
    	if(A[0]==0)
    		zeroInPosition=0;
    	else
    		zeroInPosition=-2;
    	
    	while((p=FindUnchecked(N))+1)
    	{
    		Checked[p]=1;
    		if(A[p]!=p)
    			nCount++;
    		else continue;
    		while(!Checked[B[p]])
            {
    			p=B[p];
    			Checked[p]=1;
    			nCount++;
    
    		}
    		ringCount++;
    	}
    	
    	sum=nCount+ringCount+zeroInPosition;
    	printf("%d",sum);
    }
    

      

  • 相关阅读:
    https://github.com/CocoaPods/CocoaPods/search?q=No+such+file+or+directory报错解决方式
    安卓端OCR文字识别之番外篇
    国外15种手机游戏引擎和开发工具介绍
    风雨扬州路
    iOS 使用NSUserdefault 保存自定义的 对象
    iOS sort array 数组排序里面的对象
    iOS extern 和 #define 使用
    UITableViewCell 添加 checkbox 多选
    iOS 使用 AVCaptureVideoDataOutputSampleBufferDelegate获取实时拍照的视频流
    UIImagePickerController 视频录制操作,视频大小,时间长度
  • 原文地址:https://www.cnblogs.com/gk2017/p/7141156.html
Copyright © 2011-2022 走看看