Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

折腾好久,终于AC了,说一下自己踩的坑 附代码

Posted by ajianhouyuan at 2015-04-23 10:59:03 on Problem 2201
1.如果是runtime error,需要注意一下题目中给出的条件是k,a的绝对值小于30000,说明k和a有可能是负数。检查一下代码里有没有使用k做数组索引。
2.qsort排序返回值要用减法,不能用比较符号,用比较符号样例数据过了以为没问题,结果一直栽在这里。

代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>

using namespace std;

#define MAXN	50010

typedef struct _NODE
{
	//节点编号,节点值
	int k, a;
	//父节节点index
	int parent;
	//左右儿子节点index
	int left, right;
}NODE;

NODE node[MAXN];
int stack[MAXN];
int index2node[MAXN];

void build_tree(int n)
{
	int stack_pos = -1;
	int top = -1;
	for (int i = 1; i <= n; i++)
	{
		while (stack_pos >= 0 && node[stack[stack_pos]].a > node[index2node[i]].a)
		{
			stack_pos--;
		}

		if (stack_pos != -1)
		{
			node[stack[stack_pos]].right = index2node[i];
			node[index2node[i]].parent = stack[stack_pos];
		}

		if (stack_pos < top)
		{
			node[index2node[i]].left = stack[stack_pos + 1];
			node[stack[stack_pos + 1]].parent = index2node[i];
		}

		stack[++stack_pos] = index2node[i];
		top = stack_pos;
	}
}

int sort_by_key(const void *a, const void *b)
{
	return node[*(int*)a].k - node[*(int*)b].k;
}

int cmp(int a, int b)
{
	return node[a].k < node[b].k;
}

int main()
{
	int n;
	scanf("%d", &n);

	memset(node, 0, sizeof(NODE)*(n + 1));
	memset(stack, 0, sizeof(int)*(n + 1));

	//k有可能是负数!!!!!
	for (int i = 1; i <= n; i++)
	{
		scanf("%d %d", &node[i].k, &node[i].a);
		index2node[i] = i;
	}

	qsort(index2node + 1, n, sizeof(int), sort_by_key);
	//sort(index2node + 1, index2node + 1 + n, cmp);
	build_tree(n);

	printf("YES\n");
	for (int i = 1; i <= n; i++)
	{
		printf("%d %d %d\n", node[i].parent, node[i].left, node[i].right);
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator