google codejam 2008 round2

本文介绍了一种通过记录深度优先搜索结果来优化模拟题解决方案的方法。该方法应用于一个特定的问题——Boolean树,通过对DFS过程的结果进行缓存,有效减少了重复计算,提高了求解效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem A. Cheating a Boolean Tree

模拟题,可将dfs的结果保存到数组进行优化


 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <string>
#include <string.h>
#include <sstream>
#include <cctype>
#include <climits>
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <vector>
#include <iterator>
#include <algorithm>
#include <stack>
#define _clr(x,y) memset(x,y,sizeof(x))
#define _inf(x) memset(x,0x3f,sizeof(x))
#define pb push_back
#define mp make_pair
using namespace std;
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
typedef long long LL;
struct node
{
	int g,c,val;
}tree[10000+5];
int m;
int dfs(int x,int v)
{
	int res=INF,res2=INF;
	if(x>(m-1)/2) if(v==tree[x].val) return 0;else return INF;
	int l1,l0,r1,r0;
	l1=dfs(x*2,1);l0=dfs(x*2,0);r1=dfs(x*2+1,1);r0=dfs(x*2+1,0);
	if(tree[x].g==1)
	{
		if(v==1)
		{
			res=l1+r1;
		}
		else
		{
			res=min(l1+r0,r1+l0);
			res=min(res,r0+l0);
		}
	}
	else
	{
		if(v==0)
		{
			res=l0+r0;
		}
		else
		{
			res=min(l1+r0,r1+l0);
			res=min(res,r1+l1);
		}
	}
	if(tree[x].c==1)
	{
		if(tree[x].g==0)
		{
			if(v==1)
			{
				res2=l1+r1;
			}
			else
			{
				res2=min(l1+r0,r1+l0);
				res2=min(res2,r0+l0);
			}
		}
		else
		{
			if(v==0)
			{
				res2=l0+r0;
			}
			else
			{
				res2=min(l1+r0,r1+l0);
				res2=min(res2,r1+l1);
			}
		}
	}
	res=min(res,res2+1);
	if(res>=INF) res=INF;
	//cout<<x<<" "<<v<<" "<<res<<endl;
	return res;
}
int main()
{
	//ios_base::sync_with_stdio(false);cin.tie(0);
	#ifndef ONLINE_JUDGE
		//freopen("A-small-practice.in","r",stdin);
		//freopen("out.txt","w",stdout);
	#endif

	int T;
	cin>>T;
	for(int cas=1;cas<=T;cas++)
	{
		_clr(tree,0);
        int v;
        cin>>m>>v;
        for(int i=1;i<=(m-1)/2;i++)
        {
        	cin>>tree[i].g>>tree[i].c;
		}
		for(int i=(m-1)/2+1;i<=m;i++)
        {
        	cin>>tree[i].val;
		}
		int ans=dfs(1,v);
		cout<<"Case #"<<cas<<": ";
		if(ans==INF) cout<<"IMPOSSIBLE"<<endl;
		else cout<<ans<<endl;
	}

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值