您的位置:首页 > 产品设计 > UI/UE

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

2015-07-22 13:31 453 查看
思路:



中出现了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
, next
, ans[200005], back[200005];
bool front
;

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
= 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: