poj 1635 树的表示

今天做了一道判定树同构的题。由于其是有根树,我们可以将这棵树用最小字典序表示出进行比较即可,找最小序的过程用递归完成即可。另外用string表示的过程中,可以采用std::ios::sync_with_sdtio(false)来提高输入效率(虽然也只是十几ms级别,离大神们的0ms还是有很长路要走。。另外看他们用hash方法能够取得接近0ms的成绩,或许我还要学习一个)

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;

int n;
class subwayTree
{
public:
	subwayTree() { std::ios::sync_with_stdio(false); cin>>treeNodes; }
	bool operator == (subwayTree B) 
	{
		if (treeNodes.length() != B.length())
			return false;
		return standardString() == B.standardString();
	}
	int length() { return treeNodes.length(); }
	string standardString() { return parse(treeNodes); }
	string parse(string a)
	{
		vector<string > tempParse;
		tempParse.clear();
		int sum = 0, start = 0;
		for (int i = 0; i < a.length(); i++) {
			if (a[i] == '0')
				sum++;
			else
				sum--;
			if (sum == 0) {
				if (i - start == 1)
					tempParse.push_back("01");
				else {
					string temp = "0" + parse(a.substr(start + 1, i - start - 1)) + "1";
					tempParse.push_back(temp);
				}
				start = i + 1;
			}
		}
		sort(tempParse.begin(), tempParse.end());
		string ret;
		for (int i = 0; i < tempParse.size(); i++)
			ret += tempParse[i];
		tempParse.clear();
		return ret;
	}
private:
	string treeNodes;
};
int main()
{
	scanf("%d", &n);
	getchar();
	for (int i = 0; i < n; i++) {
		subwayTree A = subwayTree();
		subwayTree B= subwayTree();
		if (A == B)
			printf("same\n");
		else
			printf("different\n");
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值