POJ 1635 解题报告

这道题是求树的最小表示。

从0开始到1结束,如果0的个数和1的个数相等,说明遍历了一个子树回来了。我们可以递归地处理每棵树。

首先每棵树可以按照如上的方式分解成多个子树,在递归地处理完每个子树后,我们把子树排序,然后拼接起来。任何排序应该都是可以的,只要排序后同一棵树的不同的遍历的表达形式是一样的。我们这里按照string从小到大的顺序排的。

thestoryofsnow1635Accepted712K344MSC++1574B
/* 
ID: thestor1 
LANG: C++ 
TASK: poj1635 
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

void toMinimalForm(string &str)
{
	if (str.length() == 2)
	{
		return;
	}

	std::vector<string> substrs;
	int zero = 0, start = 0, end = 0;
	for (int i = 0; i < str.length(); ++i)
	{
		if (str[i] == '0') 
		{
			zero++;
		}
		else if (str[i] == '1')
		{
			zero--;
			if (zero == 0)
			{
				// new subtree (start, end)
				end = i;
				assert(str[start] == '0' && str[end] == '1');
				string substr = str.substr(start + 1, end - 1 - start);
				toMinimalForm(substr);
				substrs.push_back('0' + substr + '1');
				start = i + 1;
			}
		}
	}
	assert(zero == 0);

	sort(substrs.begin(), substrs.end());
	str = "";
	for (int i = 0; i < substrs.size(); ++i)
	{
		str += substrs[i];
	}
}

int main()
{
	int T;
	scanf("%d", &T);
	string str1, str2;
	for (int t = 0; t < T; ++t)
	{
		cin >> str1 >> str2;
		// cout << "str1: " << str1 << endl;
		// cout << "str2: " << str2 << endl;
		bool isSame = true;
		if (str1.length() != str2.length())
		{
			isSame = false;
		}
		else
		{
			toMinimalForm(str1);
			toMinimalForm(str2);	
			// cout << "[toMinimalForm]str1: " << str1 << ", str2: " << str2 << endl;
			isSame = (str1 == str2);
		}
		
		if (isSame)
		{
			printf("same\n");
		}
		else
		{
			printf("different\n");
		}
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值