Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

同一解法

Posted by zhangfeifei at 2010-08-23 21:02:40 on Problem 1674
In Reply To:说下一种解法 329ms Posted by:785815369 at 2010-07-30 11:51:59
首先,感谢楼上给予这种思路。在这个思路的基础上,使用一个数组记录各个数据的下标,就不必查找。于是就将复杂度降为O(n)。
int num[10001];
int index[10001];

void init(int n)
{
	int i;
	for(i=1;i<=n;i++)
	{
		scanf("%d",&num[i]);
		index[num[i]] = i;
	}
}

inline void Swap(int &a,int &b)
{
	int t = a;
	a = b;
	b = t;
}

int getRes(int n)
{
	int i,t,sum=0;
	for(i=1;i<=n;i++)
	{
		if(num[i] != i)
		{
			sum ++;
			t = num[i];
			Swap(num[i],num[index[i]]);
			Swap(index[i],index[t]);
		}
	}
	return sum;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator