標籤:acm 演算法 編程 哈理工 hust
G - Reverse NumberTime Limit:1000MS Memory Limit:131072KB 64bit IO Format:%lld & %lluSubmitStatusPracticeHUST 1347
Description
Given a non-negative integer sequence A with length N, you can exchange two adjacent numbers each time. After K exchanging operations, what’s the minimum reverse number the sequence can achieve? The reverse number of a sequence is the number of pairs (i, j) such that i < j and Ai > Aj
Input
There are multiple cases. For each case, first line contains two numbers: N, K 2<=N<=100000, 0 <= K < 2^60 Second line contains N non-negative numbers, each of which not greater than 2^30
Output
Minimum reverse number you can get after K exchanging operations.
Sample Input
3 13 2 15 25 1 4 3 2
Sample Output
Case #1: 2Case #2: 5 先用樹狀數組求出逆序數。因為每一次交換可以增加或著減少一對逆序數,假設有m對逆序數,我們交換n對,那麼這n對我們讓他每次都減少一對逆序數,交換n次後 還有m - n對逆序。注意題目中k的取值,如果求出的逆序數大於k,那麼可以直接得出結果 res - k ,如果小於k,此時就要注意數字串中是否有重複的,如果沒有那麼當交換res - k次後此時逆序數恰好為0, 剩餘交換次數為k - res,如果k - res為偶數,那麼我們可以重複交換同一對此時逆序數還為0,如果為奇數,此時只能結果為1。 如果字串中有重複的那麼可以交換那兩個重複的數,此時無論是奇數還是偶數,結果並不影響最小逆序對總數。/*=============================================================================## Author: liangshu - cbam ## QQ : 756029571 ## School : 哈爾濱理工大學 ## Last modified: 2015-08-30 22:32## Filename: A.cpp## Description: # The people who are crazy enough to think they can change the world, are the ones who do ! =============================================================================*/##include<iostream>#include<sstream>#include<algorithm>#include<cstdio>#include<string.h>#include<cctype>#include<string>#include<cmath>#include<vector>#include<stack>#include<queue>#include<map>#include<set>using namespace std;#define maxn 100010struct node{ int v,id;} s[maxn];int c[maxn],n;typedef long long ll;ll res;bool cmp(node x,node y){ return ((x.v>y.v) || ((x.v==y.v)&&(x.id>y.id)));}int Lowbit(int x){ return x&(x^(x-1));}ll Getsum(int pos){ ll ret = 0LL; while(pos>0) { ret+=c[pos]; pos -= Lowbit(pos); } return ret;}ll update(int pos){ while(pos<=n) { c[pos]++; pos+=Lowbit(pos); }}int main(){ int k,x; int cs = 1; while(scanf("%d%d",&n,&k)!=EOF) { set<int>cnt; memset(c,0,sizeof(c)); res = 0; for(int i=1; i<=n; i++) { scanf("%d",&s[i].v); cnt.insert(s[i].v); s[i].id = i; } sort(s+1,s+n+1,cmp); for(int i=1; i<=n; i++) { res += Getsum(s[i].id); update(s[i].id); } if((res-k)>=0) printf("Case #%d: %lld\n",cs ++,res-k); else { if(cnt.size() < n) { printf("Case #%d: 0\n",cs ++); } else { if(abs(res-k)%2) printf("Case #%d: 1\n",cs ++); else printf("Case #%d: 0\n",cs ++); } } } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
HUST 1343 Reverse Number(哈理工 亞洲區選拔賽前練習賽)