1. 程式人生 > >H - Alyona and Spreadsheet

H - Alyona and Spreadsheet

遞增 title logs example otherwise 個數 quest 數組a sorted

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