题目大意:
有两列火柴,给出他们的根数和他们对应的长度ai,bi,并且规定距离为,一列相邻的火柴可以交换,要使距离最小,最少要交换多少次?
解题思路:
怎么使距离最小?哈哈哈哈,是在两个队列里面的火柴相对应(A集合火柴中第i小对应B集合中第i小),将两个集合排序(为了让AB相对应),因为排好序A,B是最小的,所以A下标与B下标就要对应;
然后按照A去处理B,开一个数组C,C[A[i].point] = B[i].point;数组C中的下标为A[i]的下标,对应的值是B[i]的下标;
举一个例子:
A:4 5 6 1 3 7 ->A':1 3 4 5 6 7
B:5 3 2 1 7 6 ->B':1 2 3 5 6 7
C: 2 1 6 4 3 5
很明显要求C数组的逆序对数啊!逆序对数用什么?树状数组!
代码如下:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define lowbit(i) i&-i
#define MAXN 100005
using namespace std;
int c[MAXN],action[MAXN];
int n,ans;
struct node
{
int val,point;
bool operator < (const node &a)const{return a.val<val;}
}matchone[MAXN],matchtwo[MAXN];
void updata(int x)
{
for(int i = x;i <= n;i += lowbit(i))c[i]++;
}
int sum(int x)
{
int ans = 0;
for(int i = x;i > 0;i -= lowbit(i))ans += c[i];
return ans;
}
int main()
{
freopen("match.in","r",stdin);
freopen("match.out","w",stdout);
cin>>n;
for(int i = 1;i <= n;i++)
{
scanf("%d",&matchone[i]);
matchone[i].point = i;
}
for(int i = 1;i <= n;i++)
{
scanf("%d",&matchtwo[i].val);
matchtwo[i].point = i;
}
sort(matchone+1,matchone+n+1);
sort(matchtwo+1,matchtwo+1+n);
for(int i = 1;i <= n;i++)
action[matchone[i].point] = matchtwo[i].point;
for(int i = 1;i <= n;i++)
{
updata(action[i]);
ans += (i-sum(action[i]));
ans %= 99999997;
}
cout<<ans;
return 0;
}
这个都是套路,套路就像LCS转LIS一样对应;