首页 > 代码库 > H - Alyona and Spreadsheet

H - Alyona and Spreadsheet

H - Alyona and Spreadsheet

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 mcolumns. 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 ifai,?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 rinclusive 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 alli from l to r?-?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 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).

Output

Print "Yes" to the i-th line of the output if the table consisting of rows from lito ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".

Example

Input
5 4
1 2 3 5
3 1 3 2
4 5 2 3
5 5 3 2
4 4 3 4
6
1 1
2 5
4 5
3 5
1 3
1 5
Output
Yes
No
Yes
Yes
Yes
No
题意:第一行输入两个整数n,m(1?≤?n·m?≤?100?000),第二行输入一个n×m的矩阵,然后再输入一个整数k,接下来k行,每行两个整数r,l,
询问从r到l行,如果存在一列数是非递减的,就输出Yes,否则就输出No。
题解:1.从上到下非递减,则上面的数比下面的数大就满足不了。
   2.用二维数组用的不好就会超时,所以用一维数组a【】来存储每一行的数
   3. 从后往前推,用一维数组b【】来存储每一列能到达的最上行,在用c【】来存储每一行能到达的最上行
  4.最后只需要比较c【r】与l的大小即可。详情请看代码。
代码:
#include<iostream>
using namespace std;
int a[100005],b[100005],c[100005];
int main()
{
    int n,m,x,i,j,r,l,k;
    cin>>n>>m;
    for(i=1;i<=m;i++)//没个数能到的最上一行是第一行。
        b[i]=1;
    for(i=1;i<=n;i++){
        c[i]=i;    //每个数都能到达所在的行。
        for(j=1;j<=m;j++){
            cin>>x;
            if(x<a[j])//如果x上面的数比x大,则不是非递增的,所以x不能到达桑拿一行。
                b[j]=i;
            a[j]=x;  //存储每一行的数。
            if(b[j]<c[i]) //找每一列能到达的最上行。
              c[i]=b[j];
        }
    }
    cin>>k;
    while(k--){
        cin>>r>>l;
        if(c[l]<=r)
            cout<<"Yes"<<endl;
        else
            cout<<"No"<<endl;
    }
    return 0;
}

 

H - Alyona and Spreadsheet