数组模拟双向链表

http://codeforces.com/contest/1154/problem/E

#include
using namespace std;
const int N = 3e5+5;
int n, k;
int l[N], r[N], vis[N], a[N], id[N]; //数组模拟双向链表 
int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	memset(vis, 0, sizeof(vis));
	cin >> n >> k;
	for(int i = 1; i <= n; i++){
		cin >> a[i];
		id[a[i]] = i;
		l[i] = i - 1;
		r[i] = i + 1;
	}
	int cur = n, turn = 1;
	while(cur){
		int m = id[cur];
		if(!vis[m]){
			vis[m] = turn;
			int i1, i2, j;
			for(i1 = l[m], j = 0; i1 >= 1 && j < k; i1 = l[i1], j++){
				if(!vis[i1]) vis[i1] = turn;
			}
			for(i2 = r[m], j = 0; i2 <= n && j < k; i2 = r[i2], j++){
				if(!vis[i2]) vis[i2] = turn;
			}
			//if(i1 == 0) i1 = 1;
			//if(i2 == n + 1) i2 = n;
			r[i1] = i2; l[i2] = i1;
			turn = turn % 2 + 1;
		}
		cur--;
	}
	for(int i = 1; i<= n; i++)cout << vis[i];
	cout << endl; 
	return 0;
}

 

你可能感兴趣的:(算法)