ASP.NET 請求處理 一
阿新 • • 發佈:2020-11-30
歸併排序求逆序對
題目大意
t組資料
昨天比賽的時候居然忘記了逆序對怎麼求...罪過罪過...
當歸並過程中,如果右集合的元素進入到新集合中,說明左集合中剩下的元素都比該元素大,那麼ans+=左邊集合剩下的元素
Code
#include<string> #include<set> #include<map> #include<queue> #include<stack> #include<cmath> #include<vector> #include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; #define LL long long #define MOD 100000007 #define PI 3.1415926535898 #define INF 0x3f3f3f3f #define MAXN 1000050 const double EPS = 1e-8; LL read() { LL x = 0, w = 1; char ch = 0; while (ch < '0' || ch>'9') { if (ch == '-') { w = -1; } ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return w * x; } LL n, a[1000050],ans[1000050],sum; void msort(int l, int r) { if (l == r) return; int mid = (l + r) >> 1; msort(l, mid - 1); msort(mid, r); int nl = l; int nr = mid; int now = l; while (nl < mid && nr <= r) { if (a[nl] > a[nr]) { sum += mid - nl; sum %= MOD; ans[now++] = a[nr]; nr++; } else { ans[now++] = a[nl]; nl++; } } while (nl < mid) { ans[now++] = a[nl]; nl++; } while (nr <= r) { ans[now++] = a[nr]; nr++; } for (register int i = l; i <now; i++) { a[i] = ans[i]; } } int main() { n = read(); for (register int i = 1; i <= n; i++) { a[i] = read(); } msort(1, n); cout << sum << endl; return 0; }