A. Rooms and Passages【區間問題】

題目鏈接:https://codeforces.com/gym/102215/problem/A

題目:
There are (n+1) rooms in the dungeon, consequently connected by n passages. The rooms are numbered from 0 to n, and the passages — from 1 to n. The i-th passage connects rooms (i−1) and i.

Every passage is equipped with a security device of one of two types. Security device of the first type checks if a person who walks through the passage has the pass of the certain color, and forbids movement if such pass is invalid. Security device of the second type never forbids movement, but the pass of the certain color becomes invalid after the person walks through.

In the beginning you are located in the room s and have all the passes. For every s from 0 to (n−1) find how many rooms you can walk through in the direction of the room n.

Input
The first line contains an integer n (1≤n≤500000) — the number of passages.

The second line contains n integers ai (1≤|ai|≤n). The number |ai| is a color of the pass which the i-th passage works with. If ai>0, the i-th passage is the first type passage, and if ai<0 — the second type.

Output
Output n integers: answers for every s from 0 to (n−1).

Examples
inputCopy
6
1 -1 -1 1 -1 1
outputCopy
3 2 1 2 1 1
inputCopy
7
2 -1 -2 -3 1 3 2
outputCopy
4 3 3 2 3 2 1

題目大意:

	面前有n+1個房間,n個門,門有兩種:正數門需要你擁有對應數字的鑰匙才能通過,負數門隨便通過,但是會奪走對應數字的鑰匙。問分別在0到n-1作爲起點,各自走的最遠距離。

這是一個區間問題,我的原始想法非常暴力,用used存鑰匙的情況,然後從開始遍歷,遇到正數,ans[time]=ans[time-1],遇到負數就往後查。

這種無腦往後面推進的做法直接導致了我的代碼的長度,複雜度都上升了,雖然做法得證是正確的,但是因爲過於複雜難以糾錯,在17th個test就卡住了。

然後看了一下別人的代碼發現別人是從反向遍歷的,而且沒有用到used數組,而是使用了一一對應的位置數組:

遇到正數就更新first[a[time]]=time;
遇到負數就查if(first[-a[time]]!=0)right=min(right,first[-a[time]]);

用right表示最遠可達的位置,每次遇到負數,而且他的first數組的數字是一個非零數,就更新right的數值。

最後因爲right是最遠可達位置,我們每次反向遍歷中就可以讓ans[time]=right-time;

重點在於保證了right切切實實是最遠可達的位置。

const int MAXN=5e5+10;
int a[MAXN],first[MAXN],ans[MAXN];
int main()
{
	int n;
	cin>>n;
	int right=n;
	for(int time=0;time<n;time++)cin>>a[time];
	for(int time=n-1;time>=0;time--)
	{
		if(a[time]>0)first[a[time]]=time;
		else
		{
			if(first[-a[time]]!=0)right=min(right,first[-a[time]]);
		}
		ans[time]=right-time;
	}
	for(int time=0;time<n;time++)cout<<ans[time]<<' ';
	cout<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章