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

滚动数组N^2实现,但是,注意不要搞成N^3

Posted by yzhw at 2011-09-11 00:09:10 on Problem 3666
# include <cstdio>
# include <algorithm>
# include <vector>
using namespace std;
# define N 2005
long long dp[2][2][N];
int data[N];
int list[N],p=0,n;
# define abs(pos) ((pos)<0?-(pos):(pos))
# define now i&1
# define last (i-1)&1
int main()
{
	//freopen("input","r",stdin);
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",data+i);
		list[p++]=data[i];
	}
	sort(list,list+n);
	p=unique(list,list+n)-list;
	for(int i=0;i<p;i++)
		dp[0][0][i]=dp[0][1][i]=abs(data[0]-list[i]);
	for(int i=1;i<p;i++)
		dp[0][0][i]=min(dp[0][0][i],dp[0][0][i-1]);
	for(int i=p-2;i>=0;i--)
		dp[0][1][i]=min(dp[0][1][i],dp[0][1][i+1]);
	for(int i=1;i<n;i++)
	{
		for(int j=0;j<p;j++)
			dp[now][0][j]=dp[last][0][j]+abs(data[i]-list[j]),
			dp[now][1][j]=dp[last][1][j]+abs(data[i]-list[j]);
		for(int j=1;j<p;j++)
			dp[now][0][j]=min(dp[now][0][j],dp[now][0][j-1]);
		for(int j=p-2;j>=0;j--)
			dp[now][1][j]=min(dp[now][1][j+1],dp[now][1][j]);
	}
	printf("%I64d\n",dp[(n-1)&1][0][p-1]);
	return 0;
}

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