P5149 会议座位

P5149 会议座位

题意:

其实还是求逆序对数。

解法:

用离散化统计每个数,再用树状数组求逆序对。

CODE:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>

using namespace std;

#define LL long long
#define N 100010

struct Node {
    int pos,val;
} a[N];
map<string,int> Hash;
char ch[10];
int tree[N],n,tag[N];
LL ans;
inline bool cmp(Node a,Node b) {
    if(a.val == b.val) 
        return a.pos < b.pos;
    return a.val < b.val;
}
inline int lowbit(int x) {
    return x & (-x);
}
inline void add(int x) {
    for( ; x <= n ; x += lowbit(x))
        tree[x]++;
    return;
}
inline int query(int x) {
    int ans = 0;
    for( ; x ; x -= lowbit(x)) 
        ans += tree[x];
    return ans;
}

int main() {
    scanf("%d",&n);
    for(int i = 1 ; i <= n ; i++) {
        scanf("%s",ch);
        Hash[ch] = i;
    }
    for(int i = 1 ; i <= n ; i++) {
        scanf("%s",ch);
        a[i].pos = i;
        a[i].val = Hash[ch];
    }
    sort(a + 1,a + n + 1,cmp);
    for(int i = 1 ; i <= n ; i++) 
        tag[a[i].pos] = i;
    for(int i = n ; i >= 1 ; i--) {
        ans += query(tag[i]);
        add(tag[i]);
    }
    printf("%lld \n",ans);
    //system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Repulser/p/11469800.html