Code Monkey home page Code Monkey logo

Comments (4)

littlesevenmo avatar littlesevenmo commented on July 16, 2024

我在您的代码上简单修改了一下。
添加了key作为索引。前中后序中均保存索引值。然后用value存储具体的值。
最后ac代码如下:

#include <cstdio>
#include <vector>
#include <stack>
#include <cstring>
using namespace std;
vector<int> pre, in, post,value;
void postorder(int root, int start, int end) {
	if (start > end) return;
	int i = start;
	while (i < end && in[i] != pre[root]) i++;
	postorder(root + 1, start, i - 1);
	postorder(root + 1 + i - start, i + 1, end);
	post.push_back(pre[root]);
}
int main() {
	int n;
	scanf("%d", &n);
	char str[5];
	stack<int> s;
	int key=0;
	while (~scanf("%s", str)) {
		if (strlen(str) == 4) {
			int num;
			scanf("%d", &num);
			value.push_back(num);
			pre.push_back(key);
			s.push(key++);
		}
		else {
			in.push_back(s.top());
			s.pop();
		}
	}
	postorder(0, 0, n - 1);
	printf("%d", value[post[0]]);
	for (int i = 1; i < n; i++)
		printf(" %d",value[post[i]]);
	return 0;
}

from pat.

littlesevenmo avatar littlesevenmo commented on July 16, 2024

另外,其实也可以最后不保存postorder的,在post.push_back(pre[root]);的时候,直接输出即可。
设置一个flag,用于标记是否是第一个数。
也就是说,可以写成

//之前设置bool flag=false;

	if (flag)
		cout << ' ';
	cout << value[pre[root]];
	flag = true;

from pat.

liuchuo avatar liuchuo commented on July 16, 2024

已修改为您的代码并署名,感谢~

from pat.

littlesevenmo avatar littlesevenmo commented on July 16, 2024

我又被翻牌了,开熏。

from pat.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.