题意: 给一个已经排好序的序列,然后给你两个区间,问这两个区间的中位数是多少。
思路:直接模拟一定超时,所以得考虑不同的情况,:)贼容易错!中间变量会超long long
不同的情况就是区间不相交和区间相交,区间相交的那一段每个元素有两个。
代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <set>
using namespace std;
#define ll long long
const int maxn = 1e5 + 10;
ll D[maxn];
int n,m;
int Find(int a,int b,int c,int d,int id)
{
int l = c, r = min(b,d), last = max(b,d);
int cnum = (r-l+1)*2;
int pnum = l - a, lnum = last - r, vnum = pnum + cnum + lnum;
if(id <= pnum)
return a + id - 1;
else if(id <= pnum + cnum)
return c + (id - pnum - 1)/2;
else return r + (id - pnum - cnum) ;
}
int Finda(int a,int b,int c,int d,int id)
{
int fnum = b - a +1;
if(id > fnum)
return c + id - fnum - 1;
else return a + id - 1;
}
void solve(int a,int b,int c,int d)
{
if(a > c) swap(a,c),swap(b,d);
int fnum = b-a+1, snum = d-c+1;
if(b < c)
{
int vnum = fnum + snum;
if(vnum % 2)
{
int id = vnum / 2 + 1;
int thi = Finda(a,b,c,d,id);
printf("%.1lf\n",(double)D[thi]);
}
else
{
int id1 = vnum / 2, id2 = id1 + 1;
int thi = Finda(a,b,c,d,id1), thj = Finda(a,b,c,d,id2);
printf("%.1f\n",(double)(D[thi] + D[thj])/2.0);
}
}
else
{
int vnum = c-a + (b-c+1)*2 + d-b;
if(vnum % 2)
{
int id = Find(a,b,c,d,vnum/2 + 1);
printf("%.1f\n",(double)D[id]);
}
else
{
int id1 = Find(a,b,c,d,vnum/2);
int id2 = Find(a,b,c,d,vnum/2 + 1);
printf("%.1f\n",(double)(D[id1]+D[id2])/2.0);
}
}
}
int main()
{
int t,a,b,c,d;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++) cin >> D[i];
for(int i = 0; i < m; i++)
{
scanf("%d%d",&a,&b);
scanf("%d%d",&c,&d);
solve(a,b,c,d);
}
}
return 0;
}