During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.
Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai, j ≤ ai + 1, j for all i from 1 to n - 1.
Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai, j ≤ ai + 1, j for all i from l to r - 1 inclusive.
Alyona is too small to deal with this task and asks you to help!
The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 100 000) — the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table.
Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai, j (1 ≤ ai, j ≤ 109).
The next line of the input contains an integer k (1 ≤ k ≤ 100 000) — the number of task that teacher gave to Alyona.
The i-th of the next k lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n).
Print "Yes" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".
输入一个矩阵A,取矩阵的第l行至第r行,问其中是否有一列是非递减排列的。
动态规划。首先想到设dp[i][j]为第j列中,满足从第k行至第i行为非递减的最小的k。dp[i][j] = A[i][j] >= A[i - 1][j] ? A[i - 1][j] : i;当且仅当k<=l时这一列满足条件。所以搜索每一列,只要找到这样满足条件的一列就输出Yes。k个查询,复杂度为O(mn + nk)。
上面的做法会超时。每次给出一组l和r的时候,矩阵中所有的列都会被取出,所以不用每次都遍历所有列,先在dp[i][j]中找出每一行最小的,只要最小的比l小那么这些列中一定有一列满足条件,复杂度为O(mn)。查询的时候只要O(k)。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int m, n; cin >> m >> n;
vector<vector<int>> sheet(m, vector<int>(n));
vector<vector<int>> dp(m, vector<int>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> sheet[i][j];
}
}
for (int i = 0; i < n; i++) {
dp[0][i] = 0;
}
for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
if (sheet[i][j] >= sheet[i - 1][j]) {
dp[i][j] = dp[i - 1][j];
}
else {
dp[i][j] = i;
}
}
}
vector<int> dp2(m, 0);
for (int i = 0; i < m; i++) {
dp2[i] = dp[i][0];
for (int j = 1; j < n; j++) {
if (dp[i][j] < dp2[i]) {
dp2[i] = dp[i][j];
}
}
}
int k; cin >> k;
for (int i = 0; i < k; i++) {
int l, r; cin >> l >> r;
bool f = dp2[r - 1] <= l - 1;
if (f) printf("Yes\n");
else printf("No\n");
}
}