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

来源:互联网 发布:菊水 清酒 知乎 编辑:程序博客网 时间:2024/06/05 05:53

思路:中出现了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 1000005int 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
原创粉丝点击