Codeforces Round #279 (Div. 2) B. Queue 模拟

思路:中出现了0的行,代表的是队首和队尾元素,所以只需沿着两个0前向/逆向出发,即可将队列填满。

由队尾给出的那一行一定为:ID[n - 1], 0,所以从0逆向出发能确定第n - 1个人,根据n的奇偶性进行判断:

①当n为奇数时,从0前向出发,依次可以确定队列的第2,4,……,n - 1个人,所以应该从队尾元素逆向出发,确定队列的第n,n - 2,……,1个人

②当n为偶数时,从0前向出发,依次可以确定队列的第2,4,……,n个人,从0逆向出发确定队列的第n - 1,n -3,……,1个人

代码如下:

#include <cstdio>
using namespace std;
#define N 1000005
int pre[N], next[N], ans[200005], back[200005];
bool front[N];

int main(){
	int n, x, y, tail;
	scanf("%d", &n);
	for(int i = 0; i < n; ++i){
		scanf("%d %d", &x, &y);
		next[x] = y, pre[y] = x;
		front[x] = true;
		back[i] = y;
	}
	for(int i = 0; i < n; ++i){
        if(!front[back[i]]){
            tail = back[i];
            break;
        }
	}
	int idx = 2;
	for(int i = next[0]; i != 0; i = next[i])
		ans[idx] = i, idx += 2;
    int last = pre[0];
    idx = n - 1;
	if(n % 2)
        ans[n] = tail, last = pre[tail], idx = n - 2;
	for(int i = last; i != 0; i = pre[i])
		ans[idx] = i, idx -= 2;
	for(int i = 1; i <= n; ++i)
		printf("%d ", ans[i]);
	printf("\n");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值