| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
注意:两个程序的区别:程序1:
#include <iostream>
using namespace std;
int main()
{
int t,n,count,a[10001];
a[0]=0;
cin>>t;
while(t--)
{
cin>>n;
count=0;
for(int i=1;i<=n;i++)
cin>>a[i];
int temp;
for(int j=1;j<=n;j++)
{
if(a[j]!=j)
{
for(int k=1;k<=n;k++)//K每次都是从第一个数开始比较的,但是这样增加了比较次数,因为每循环一次,前面的数都是有序的了,可以不用比较了。
if(a[k]==j)
{
temp=a[j];
a[j]=a[k];
a[k]=temp;
break;
}
count++;
}
}
cout<<count<<endl;
}
return 0;
}
程序2:#include <iostream>
using namespace std;
int main()
{
int t,n,count,a[10001];
a[0]=0;
cin>>t;
while(t--)
{
cin>>n;
count=0;
for(int i=1;i<=n;i++)
cin>>a[i];
int temp;
for(int j=1;j<=n;j++)
{
if(a[j]!=j)
{
for(int k=j+1;k<=n;k++) //k=j+i使得k的值随着j的值变化而变化,进而减少了for循环的比较此数,因为k的值每一次都是从未排好序的序列的第一个数开始比的。
if(a[k]==j)
{
temp=a[j];
a[j]=a[k];
a[k]=temp;
break;
}
count++;
}
}
cout<<count<<endl;
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator