Alyona and Spreadsheet 預處理保存以免TLE

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!

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 li to 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的矩陣,問 l 到 r 行是否有某一列是非遞減的(假設第 j 列滿足,則任意i>.=l&&i<=r s[i][j]>=s[i-1 ][j]總成立) 問k次;

思路:
開一個dp數組 dp[i[j]保存mp[i][j]向上幾位滿足條件,然後開一個一維數組保存第i行可以向上幾行滿足條件(一定要預處理,不然會TLE!!!) 然後O(1)次詢問即可.預處理真香!!!

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int n,m,x,s[100000];
	vector<int> mp[100000],dp[100000];
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
		{
			scanf("%d",&x);
			mp[i].push_back(x);
		}
	for(int j=0;j<m;j++)//第一行預處理爲一
		dp[0].push_back(1);
	for(int j=0;j<m;j++)
	{
		for(int i=1;i<n;i++)
		{
			if(mp[i][j]>=mp[i-1][j])
				dp[i].push_back(dp[i-1][j]+1);
			else
				dp[i].push_back(1);
		}
	}
	memset(s,0,sizeof s);
	for(int i=0;i<n;i++)//預處理
		for(int j=0;j<m;j++)
			s[i]=max(s[i],dp[i][j]);//保存最大的那個
	int k;
	scanf("%d",&k);
	while(k--)
	{
		int l,r;
		bool flag=0;
		scanf("%d%d",&l,&r);
		if(s[r-1]>=(r-l+1))
			printf("Yes\n");
		else
			printf("No\n");
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章