| Sorting by Swapping |
| Time Limit: 1000ms, Special Time Limit:2500ms, Memory Limit:32768KB |
| Total submit users: 110, Accepted users: 104 |
| Problem 10067 : No special judgement |
| Problem description |
| Given a permutation of numbers from 1 to n, we can always get the sequence 1, 2, 3, ..., n by swapping pairs of numbers. For example, if the initial sequence is 2, 3, 5, 4, 1, we can sort them in the following way: 2 3 5 4 1 1 3 5 4 2 1 3 2 4 5 1 2 3 4 5 Here three swaps have been used. The problem is, given a specific permutation, how many swaps we needs to take at least. |
| Input |
| The first line contains a single integer t (1 <= t <= 20) that indicates the number of test cases. Then follow the t cases. Each case contains two lines. The first line contains the integer n (1 <= n <= 10000), and the second line gives the initial permutation. |
| Output |
| For each test case, the output will be only one integer, which is the least number of swaps needed to get the sequence 1, 2, 3, ..., n from the initial permutation. |
| Sample Input |
2 3 1 2 3 5 2 3 5 4 1 |
| Sample Output |
0 3 |
| Problem Source |
| Beijing 2005 Warmup |
#include <stdio.h>
#define MAX 10000
#define RIGHT 1
#define WRONG 0
main()
{
int total=0,n=0,num[MAX],min=0;
int i=0,j=0,k=0,p=0,count=0;
int flag,start;
scanf("%d",&total);
for( k = 0 ; k < total ; k++ ){
count = 0 ;
scanf("%d",&n);
for( p = 0 ; p < n ; p++)scanf("%d",&num[p]);
//for( p = 0 ; p < n ; p++)printf("num%d ",num[p]);
for( i = 0 ; i < n ; i++){
if( num[i] != i+1 ){
start = i;
flag = WRONG;
while( flag != RIGHT ){
for( j = 0 ; j < n ; j++ ){
if( num[j] == start + 1 ){
num[j] = num[start];
num[start] = start +1;
count++;
start = j;
break;
}
}
if( num[start] == start+1 )flag = RIGHT;
else flag = WRONG;
}//while
}
}
printf("%d ",count);
}
return 0;
}
#define MAX 10000
#define RIGHT 1
#define WRONG 0
main()
{
int total=0,n=0,num[MAX],min=0;
int i=0,j=0,k=0,p=0,count=0;
int flag,start;
scanf("%d",&total);
for( k = 0 ; k < total ; k++ ){
count = 0 ;
scanf("%d",&n);
for( p = 0 ; p < n ; p++)scanf("%d",&num[p]);
//for( p = 0 ; p < n ; p++)printf("num%d ",num[p]);
for( i = 0 ; i < n ; i++){
if( num[i] != i+1 ){
start = i;
flag = WRONG;
while( flag != RIGHT ){
for( j = 0 ; j < n ; j++ ){
if( num[j] == start + 1 ){
num[j] = num[start];
num[start] = start +1;
count++;
start = j;
break;
}
}
if( num[start] == start+1 )flag = RIGHT;
else flag = WRONG;
}//while
}
}
printf("%d ",count);
}
return 0;
}
本文详细探讨了ACM湖南大学(HNU)竞赛中的Problem 10067,该问题涉及通过交换操作对整数序列进行排序。文章深入分析了如何有效地实现这一排序策略,同时讲解了输入输出格式和处理整数数组的技巧。
384

被折叠的 条评论
为什么被折叠?



