1067. Sort with Swap(0,*) (25)

102 篇文章 0 订阅
37 篇文章 0 订阅

1067. Sort with Swap(0,*) (25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given any permutation of the numbers {0, 1, 2,..., N-1}, 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 N nonnegative integers.

Input Specification:

Each input file contains one test case, which gives a positive N (<=105) followed by a permutation sequence of {0, 1, ..., N-1}. 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
N个数  接着是当前【数】放在序号i=0~N-1;
问通过0来交换,最少多少次;
通过存放的编号和存放的数为下一个编号,最终可以弄成一个环,而利用0来交换的最小次数为。当0在这个交换的环中,那么只要环的长度-1;如果不在则长度+1
例子;
存放的器0-3-2-7
存放的数3-2-7-0此时这个环为0-3-2-7-0~  有0;通过从右边起,0-7交换,7-2交换……交换最短 环长度-1=4;
存放的器1-5-4-6-9
存放的数5-4-6-9-1此时这个环为1-5-4-6-9-1~ 有无;通过从右边起先把0-1换,接着0-9交换,0-6交换……最后再0-1交换回来,交换最短 环长度+1=5;

评测结果

时间结果得分题目语言用时(ms)内存(kB)用户
8月14日 00:03答案正确251067C++ (g++ 4.7.2)32820datrilla

测试点

测试点结果用时(ms)内存(kB)得分/满分
0答案正确118415/15
1答案正确328203/3
2答案正确155643/3
3答案正确13602/2
4答案正确13081/1
5答案正确13081/1

#include <iostream>   
#include<vector> 
using namespace std; 
 int main()
{
  int N,index,sum,min,temp,now;
  bool Flag;
  cin >> N; 
  vector<int>swapsort(N);
  for (index = 0; index < N; index++)
  {
    cin >> swapsort[index];
  }
  sum = 0;
  for (index = 0; index < N; index++)
  {     if (swapsort[index] != index)
    {  
      now = index;
      Flag = false; 
      min = 0;
      while (swapsort[now] != now)
      { 
        if (now == 0)Flag = true;
        temp = swapsort[now];
        swapsort[now] = now;
        now= temp; 
        min++;  
      }  
      if (Flag)min--;
      else min++;
        sum += min; 
    } 
  }
  cout << sum << endl;
    system("pause");
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值