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)