POJ2231 Moo Volume [Simple DP]

Source: Internet
Author: User
Tags sort

Test instructions

A given n number.

Ask what the sum of the difference between any two numbers is.


Ideas:

Order from small to large first.

Then the DP transfer equation:

Dp[i]=dp[i-1] + (i-1) * (A[i]-a[i-1]);

The final result is ans=dp[n]*2; (because the noise calculation is bidirectional)

In fact, rather than DP, it is better to find the law.

Such time complexity is the time complexity O (NLOGN) of the sort.

#include <iostream>
#include <vector>
#include <string>
#include <queue>
# include<cmath>
#include <algorithm>
#define Llong Long
#define Min (A, B) (A<B?A:B)
#define MAX (A, B) (A>B?A:B)
#define ABS (a) ((a) >0? ( A):-(a)
#define MOD (a) ((a) -1+ (b))% (b) +1)
using namespace std;
int n,m,t;
const int n=10005;
const int m=105;
const int inf= (1<<30);
int a[n];
Llong Dp[n];
int main ()
{
	scanf ("%d", &n);
	for (int i=1;i<=n;i++)
		scanf ("%d", a+i);
	Sort (a+1,a+1+n);
	for (int i=2;i<=n;i++)
		dp[i]=dp[i-1]+ (i-1) *llong (a[i]-a[i-1]);
	Llong ans=0;
	for (int i=1;i<=n;i++)
		ans+=dp[i];
	printf ("%lld\n", ans*2);
	return 0;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.