Yet Another Median Task Gym - 100741G (nth_element找中位数)

题目链接:https://vjudge.net/contest/181019#problem/G

题意:给定一个n*n的矩阵,有q次查询,每次查询给定四个数x1 y1 x2 y2,求矩形区域 x1 <= x <= x1, y1 <= y <= y2的中位数。

思路:若每次对小矩形区域内的所有数进行排序找出中位数,则肯定会超时。STL中有一个函数ntn_element(a, x, a + n),用于使数组a中n个数中第x大的数位于第x个位置,x左边的数都大于a[x],x右边的数都小于a[x]但两边的数都可能是无序的。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<cstdlib>
#include<sstream>
#include<deque>
#include<stack>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-6;
const int  maxn = 1000 + 20;
const int  maxt = 300 + 10;
const int mod = 10;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, -1, 1};
const int Dis[] = {-1, 1, -5, 5};
const int inf = 0x3f3f3f3f;
const int MOD = 1000;
int n, m, k;
int g[maxn][maxn], num[maxn * maxn];
int main(){
    int q;
    scanf("%d%d", &n, &q);
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= n; ++j){
            scanf("%d", &g[i][j]);
        }
    }
    int x1, y1, x2, y2;
    while(q--){
        scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
        int cnt = 0;
        for(int i = x1; i <= x2; ++i){
            for(int j = y1; j <= y2; ++j){
                num[cnt++] = g[i][j];
            }
        }
//        cout << "cnt == " << cnt << " (cnt - 1) / 2 == " << (cnt - 1) / 2 << endl;
        nth_element(num, num + (cnt - 1) / 2 ,num + cnt);
        printf("%d\n", num[(cnt - 1) / 2]);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值