1. 程式人生 > >【打CF,學演算法——三星級】CodeForces 701B Cells Not Under Attack (分析)

【打CF,學演算法——三星級】CodeForces 701B Cells Not Under Attack (分析)

題面:

B. Cells Not Under Attack time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.

The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.

You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack

after Vasya puts it on the board.

Input

The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ min(100 000, n2)) — the size of the board and the number of rooks.

Each of the next m lines contains integers xi and yi (1 ≤ xi, yi ≤ n) — the number of the row and the number of the column where Vasya will put the i

-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.

Output

Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.

Examples Input
3 3
1 1
3 1
2 2
Output
4 2 0 
Input
5 2
1 5
5 1
Output
16 9 
Input
100000 1
300 400
Output
9999800001 
Note

On the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.

題意:

    一個n*n的棋盤,每次放入一顆棋子(每次棋子位置不同),則該棋子所在行和列都會受影響,共m次詢問,問每次放入新的棋子後,未被影響的方格數量。

解題:

     初拿到這道題沒什麼想法,因為m為10^5,且時限為2s,估算應該是O(1)/O(nlogn)的解法比較合適。仔細分析,我們需要知道的是,插入新的棋子,有幾個空位置被影響。為此,我們需呀知道原來棋盤的狀態,看似好像很複雜,但實際上,我們只需要知道新插入位置所在行和所在列對棋盤的影響即可。分類討論:如果,新行原來就是被影響的,那麼這一行都不會有變化,同理,列也是如此,所以我們需要2個數組分別標記行和列的受影響情況,以及兩個計數值記錄受影響行數和列數。原來未受影響的列,產生的新影響數為(n-已受影響行數),行也是同理,注意下交叉點的判斷即可。

程式碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#define LL long long
using namespace std;
bool row[100005],col[100005];
int main()
{
    int m,rowc=0,colc=0,x,y;
	LL n,ans;
	scanf("%lld%d",&n,&m);
	ans=n*n;
	for(int i=0;i<m;i++)
	{
		scanf("%d%d",&x,&y);
		if(row[x]&&col[y]);
        else if(!row[x]&&!col[y])
		{
			ans--;
			ans=ans-(n-colc)+1;
			colc++;
			ans=ans-(n-rowc)+1;
			rowc++;
		}
		else if(row[x])
		{
			ans=ans-(n-rowc);
			colc++;
		}
		else
		{
			ans=ans-(n-colc);
			rowc++;
		}
		row[x]=col[y]=1;
		printf("%lld\n",ans);
	}
	return 0;
}