[ POJ ][ 树HASH ] 1635 Subway tree systems

首先,对于一个树,我们可以有一种压缩表示:

  0010011101001011

其中 0 表示向下走,1 表示向上走。于是:

  00100111|01|001011

对于每一段的 0 1 出现次数相同,这种hash方法叫 树的最小表示法 

1635 题目精简大意:给你n对01字符串,判断每一对儿表示的是不是同一个树,方法:

  1.定义 cnt, start, end 来记录当前0 1之和是否相等,start,end 记录相等时所得字数的范围。

  2.去首尾得到子串,递归进行1步骤直到子串只为“0 1”。

  3.所有子串排序组合到一起然后重新替代原串,此时的新str即为最小表示(sort字典序排序)。

  4.两串进行比较即可。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
int n;
void dfs(string& str) {
	if(str.length() == 2) return;
	vector<string> substrs;
	int z = 0, start = 0, end = 0;
	for(int i = 0; i < str.length(); i++) {
		if(str[i] == '0') z++;
		else if(str[i] == '1') {
			z--;
			if(z == 0) {
				end = i;
				string substr = str.substr(start + 1, end - 1 - start);
				dfs(substr);
				substrs.push_back('0' + substr + '1');
				start = i + 1;
			}
		}
	}
	sort(substrs.begin(), substrs.end());
	str = "";
	for(int i = 0; i < substrs.size(); i++) {
		str += substrs[i];
	}
}
int main() {
	cin >> n;
	while(n--) {
		string str1, str2;
		cin >> str1 >> str2;
		if(str1.length() != str2.length()) {
			cout << "different" << endl;
			continue;
		} else {
			dfs(str1), dfs(str2);
			if(str1 == str2) cout << "same" << endl;
			else cout << "different" << endl;
		}
	}
	return 0;
}

  

转载于:https://www.cnblogs.com/Kvar-ispw17/p/6576323.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值