Gym 100741G Yet Another Median Task

来源:互联网 发布:鲱鱼罐头 淘宝 编辑:程序博客网 时间:2024/06/05 10:38

题意:

给出一个n*n的矩阵。然后有很多操作,每次给你两个点(x1,y1)和(x2,y2),求出这两个点作为新矩阵的左上角和有下角,求出新矩阵所有值的中点。


直接暴力,用scanf输入,然后就爆过了,用cin cout会超时。

用nth_element函数。

使用方法:nth_element(start, start+n, end)

使第n大元素处于第n位置(从0开始,其位置是下标为n的元素),并且比这个元素小的元素都排在这个元素之前,比这个元素大的元素都排在这个元素之后,但不能保证他们是有序的。

代码:

#include <iostream>#include <string>#include <cmath>#include <algorithm>#include <cstring>#include <cstdio>using namespace std;int a[1000005];int g[1005][1005];int main(){    int n, 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++)            {                a[cnt++] = g[i][j];            }        }        nth_element(a, a+(cnt-1)/2, a+cnt);        printf("%d\n", a[(cnt-1)/2]);        //cout << a[(cnt-1)/2] << endl;    }    return 0;}


原创粉丝点击