Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

用DFS的同学注意了!!

Posted by dahai1990 at 2012-11-23 16:40:01 on Problem 2192
我写了一个从第一个字符开始的深搜结果超时了,然后加一个剪枝:判断C的最后一个字符是否等于A或B的最后一个字符。这样就可以AC了。网上有说还有一个剪枝是判断C的长度是否等于A+B的长度,个人认为这个是多余的,题目中有说:The length of the third string is always the sum of the lengths of the first two strings。所以不存在长度不符合的情况。
同样的道理,我决定从最后一个字符开始深搜试试,不加任何剪枝就AC了。
所以应该是这题的数据的问题了。


代码:
//从头开始深搜
#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <string.h>
using namespace std;
const int maxn=205;
char a[maxn],b[maxn],c[maxn*2];
int n,m,L;
int dfs(int x,int y,int z)
{
	if(z==0) return 1;
	if(c[z]!=a[x] && c[z]!=b[y]) return 0;
	if(c[z]==a[x] && dfs(x-1,y,z-1)) return 1;
	if(c[z]==b[y] && dfs(x,y-1,z-1)) return 1;
	return 0;
}
int main()
{
	int T,ncase=0;
	cin>>T;
	while(T--)
	{
		scanf("%s%s%s",a+1,b+1,c+1);
		n=strlen(a+1);
		m=strlen(b+1);
		L=strlen(c+1);
		int ans=dfs(n,m,n+m);
		printf("Data set %d: %s\n",++ncase,ans?"yes":"no");
	}
	return 0;
}
//从尾开始深搜

#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <string.h>
using namespace std;
const int maxn=205;
char a[maxn],b[maxn],c[maxn*2];
int n,m,L;
int dfs(int x,int y,int z)
{
	if(z>L) return 1;
	if(c[z]!=a[x] && c[z]!=b[y]) return 0;
	if(c[z]==a[x] && dfs(x+1,y,z+1)) return 1;
	if(c[z]==b[y] && dfs(x,y+1,z+1)) return 1;
	return 0;
}
int main()
{
	int T,ncase=0;
	cin>>T;
	while(T--)
	{
		int ans=0;
		scanf("%s%s%s",a+1,b+1,c+1);
		n=strlen(a+1);
		m=strlen(b+1);
		L=strlen(c+1);
		if(c[L]==a[n] || c[L]==b[m]) ans=dfs(1,1,1);
		printf("Data set %d: %s\n",++ncase,ans?"yes":"no");
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator