Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P1527 [国家集训队]矩阵乘法

P1527 [国家集训队]矩阵乘法

离散化所有数,记录每个数的位置,整体二分答案,用二维树状数组维护个数。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
const int N = 510, Q = 6e4 + 10, M = 25e4 + 10;
int n, m, q, ans[Q], w[N][N], tr[N][N];
struct Query
{
int x1, y1, x2, y2, k, id;
};
vector<PII> cnt[M];
void modify(int x, int y, int k)
{
int tmpy = y;
for (; x <= n; x += x & -x)
for (y = tmpy; y <= n; y += y & -y)
tr[x][y] += k;
}
int query(int x, int y)
{
int res = 0, tmpy = y;
for (; x; x -= x & -x)
for (y = tmpy; y; y -= y & -y)
res += tr[x][y];
return res;
}
void solve(int l, int r, vector<Query> &p)
{
if (p.empty())
return;
if (l == r)
{
for (Query i : p)
ans[i.id] = l;
return;
}
int mid = l + r >> 1;
for (int i = l; i <= mid; i++)
for (PII j : cnt[i])
modify(j.first, j.second, 1);
vector<Query> L, R;
for (Query i : p)
{
int t = query(i.x2, i.y2) - query(i.x1 - 1, i.y2) - query(i.x2, i.y1 - 1) + query(i.x1 - 1, i.y1 - 1);
if (t >= i.k)
L.push_back(i);
else
{
i.k -= t;
R.push_back(i);
}
}
for (int i = l; i <= mid; i++)
for (PII j : cnt[i])
modify(j.first, j.second, -1);
solve(l, mid, L), solve(mid + 1, r, R);
}
int main()
{
read(n), read(q);
vector<int> ws;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
read(w[i][j]);
ws.push_back(w[i][j]);
}
sort(ws.begin(), ws.end());
m = ws.erase(unique(ws.begin(), ws.end()), ws.end()) - ws.begin();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
w[i][j] = lower_bound(ws.begin(), ws.end(), w[i][j]) - ws.begin() + 1;
cnt[w[i][j]].push_back(make_pair(i, j));
}
vector<Query> p;
for (int i = 1, x1, y1, x2, y2, k; i <= q; i++)
{
read(x1), read(y1), read(x2), read(y2), read(k);
p.push_back((Query){x1, y1, x2, y2, k, i});
}
solve(1, m, p);
for (int i = 1; i <= q; i++)
write(ws[ans[i] - 1]), puts("");
return 0;
}