777C Alyona and Spreadsheet

来源:互联网 发布:凤凰于飞 知乎 编辑:程序博客网 时间:2024/04/29 16:43

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 thei-th row and the j-th column. We say that the table is sorted in non-decreasing order in the columnj if ai, j ≤ ai + 1, j for alli from 1 to n - 1.

Teacher gave Alyona k tasks. For each of the tasks two integersl and r are given and Alyona has to answer the following question: if one keeps the rows froml 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 suchj that ai, j ≤ ai + 1, j for alli from l tor - 1 inclusive.

Alyona is too small to deal with this task and asks you to help!

Input

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 thei 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 andri (1 ≤ li ≤ ri ≤ n).

Output

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");}}





0 0
原创粉丝点击