• hdu6489 2018 黑龙江省大学生程序设计竞赛j题


    Problem Description
    Kayaking is playing a puzzle game containing n different blocks. He marks the blocks with integers from 1 to n, which show the blocks’ original positions. Each time he can exchange two blocks and he wants to know how many times he needs at least to restore the puzzle.
     
    Input
    The input starts with one line contains exactly one positive integer which is the number of test cases.
    Each test case contains two lines.
    The first line contains an integer, which indicates the number of puzzle pieces.
    The second line contains n different integers, the i-th number means the mark of the block in the i-th position.
     
    Output
    For each test case, output one line with one number represents the minimum operations.
     
    Sample Input
    2 4 2 3 4 1 4 2 1 4 3
     
    Sample Output
    3 2
    Hint
    1<=T<=20,1<=n<=100000
     
     
    题意:有顺序不定的从1到n的n个数,排序,每次操作更换两个数的位置,求最少操作次数,使得排序为从变成从 1 到 n。
    思路:标记每个数应该所在的位置,然后将该位置上的数寻找其应有的位置并进行标记,并标记好每个数位置是否已经找好。具体看代码注释
     
    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<cstring>
    #include<cmath> 
    using namespace std;
    const int N = 1e6+10;
    int a[N],vis[N];  //vis数组记录每个数是否找过他应该在的位置 
    int main()
    {
    	int t;
    	scanf("%d",&t);
    	while(t--){
    		memset(vis,0,sizeof(vis)); 
    		int ans = 0;
    		int n,i;
    		scanf("%d",&n);
    		for(i = 1; i <= n; i++){
    			scanf("%d",&a[i]);
    		}
    		for(i = 1; i <= n; i++){
    			int temp = a[i],x = 0;
    			while(!vis[temp]){  //temp 还没找过其应在的位置 
    				vis[temp] = 1;  //标记temo已经找过 
    				temp = a[temp];  //用temp应在的位置上的数覆盖temp,如果其在应在的位置那么继续while循环直接跳出然后不用做交换 
    				x++;
    			}
    			if(x > 0){
    				ans += x-1;  //遍历每一组情况下应该对x减一才能得到正确的交换次数 
    			}
    		}
    		printf("%d
    ",ans);
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    灵魂拷问!浏览器输入「xxxxhub」的背后.....
    趣谈 DHCP 协议,有点意思。
    规约模式,颤抖吧产品经理!再也不怕你乱改需求了
    订阅者模式,公众号、B站、快手用了都说好!
    设计模式,你相信吗,只用两个函数实现事务!
    Linux系统中安装Jenkins
    Linux系统在线安装和查看git版本
    VIM中的保存和退出命令
    @JsonProperty爆红
    手动运行jar包
  • 原文地址:https://www.cnblogs.com/clb123/p/10731929.html
Copyright © 2020-2023  润新知