Hdu2838cow Sorting (tree array + reverse order number)

Source: Internet
Author: User

Topic Link: Click to open the link

Test Instructions Description: Given an array of length 100000, each element in the range of 1~100000, and not the same, the exchange of any two of them will cost the sum of two numbers. Q How does swapping make arrays orderly and cost the least?

Problem Solving Ideas:

1, obviously we know, to make an array ordered at least the number of exchanges (that is, the number of times must be exchanged) in the number of reverse order in the group

2, because the length of the array is relatively large, so we can use a tree-like array to statistical results

Two tree-like arrays are required here

First: Record the number of elements that are less than or equal to a value

Second: Record the sum of elements that are less than or equal to a value


Code:

#include <cstdio> #include <cstring> #define MAXN 100010using namespace Std;int c[maxn];int lowbit (int x) {RE Turn x& (-X);}    int sum (int pos) {int ret=0;        while (pos>0) {Ret+=c[pos];    Pos-=lowbit (POS); } return ret;}        void Add (int pos,int v) {while (pos<=100000) {c[pos]+=v;    Pos+=lowbit (POS);    }}long Long Ct[maxn];long long sumt (int pos) {long long ret=0;        while (pos>0) {Ret+=ct[pos];    Pos-=lowbit (POS); } return ret;}        void Addt (int pos,int v) {while (pos<=100000) {ct[pos]+=v;    Pos+=lowbit (POS);    }}int Main () {int n;        while (scanf ("%d", &n)!=eof) {memset (c,0,sizeof (C));        memset (ct,0,sizeof (Ct));        Long Long ans=0;        int x;            for (int i=0; i<n; ++i) {scanf ("%d", &x);            Add (x,1);            ADDT (X,X); ans+= ((SUM (100000)-sum (x)) * (Long Long) x+sumt (100000)-sumt (x));///Pay attention to overflow problem} PRintf ("%i64d\n", ans); } return 0;}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Hdu2838cow Sorting (tree array + reverse order number)

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.