POJ 1674
来源:互联网 发布:pkpm钢结构计算软件 编辑:程序博客网 时间:2024/06/05 18:34
题意:给一串顺序打乱的数字,要求输出:将这串数字变为从小到大顺序的最少交换次数。
思路:输入完一串数字后,如果该位置上的数字与该位置号不相同,交换该位置上的数字与该位置上的数字的位置号上的数字(重复操作,直到该位置上的数字与该位置号相同为止)。即:
while(a[i]!=i){swap(a[i],a[a[i]]);count++;}
代码:
#include<iostream>
usingnamespace std;
intmain()
{
int *a,count,i,n,n0;
cin>>n;
while(n--)
{
count=0;
cin>>n0;
a=new int[n0+1];
for(i=1;i<n0+1;i++)
cin>>a[i];
for(i=1;i<n0+1;i++)
{
while(a[i]!=i)
{
swap(a[i],a[a[i]]);
count++;
}
}
cout<<count<<endl;
delete []a;
}
return 0;
}
using
int
{
}
- POJ 1674
- poj 2488
- POJ 3299
- poj 1905
- POJ 1674 Sorting by Swapping(需…
- POJ 2485 Highways
- POj 1017 Packets
- poj 1020 搜索
- poj 3278 宽搜
- poj 1426 宽搜
- poj 1925 Spiderman
- poj 3259 Wormholes
- POJ 2160 BOX
- POJ 2190 ISBN
- poj 3299 humidex
- poj 2253 Frogger
- poj 2485 Highways
- poj 3041 Asteroids
- POJ 1504
- POJ 1552
- C++学习书籍推荐
- POJ 1607
- POJ 1657
- POJ 1674
- POJ 1799
- POJ 1862
- POJ 1906
- POJ 1922
- POJ 1929
- POJ 1969
- POJ 2000
- POJ 2005