HDU多校6 - 6831 Fragrant numbers(dfs爆搜+打表)

题目链接:点击查看

题目大意:给出一个以 " 1145141919 " 无限循环的字符串,现在可以在合适的位置添加 ' + ' , ' * ' 和 ' ( ' , ' ) ' 将其转换为表达式,现在给出一个 n ,问表达出 n 所需要的最短长度是多少

题目分析:比赛时想到了可以状压 3 进制来枚举每个位置的符号:空格,+,*,然后利用递归分治暴力求解,写完之后因为复杂度不太好把控,循序渐进跑,发现当字符串长度为 10 的时候就有 4968 个数了,再想跑 n = 11 的时候就发现本地跑不出来了,硬着头皮打了个表交上去竟然 AC 了。。赛后看了一下数据,发现询问数据中最大的答案恰好就是 10 ,纯运气选手飘过

当然正解也是可以选择打表的,只不过打表程序更加优秀,其实可以直接使用递归分治再加个记忆化,对比我的程序少了个状压的过程,具体体现在了分治的过程中

然后因为有很多数会重复,所以可以用 set 去重,非常方便,dp[ l ][ r ] 为 set<int> 元素,维护了区间 [ l , r ] 内数字可以组成的答案

时间复杂度不太会算,题解说的是 11^2 * n^2 ,在本地的话反正是秒出就对了

最后对于每个答案的话,其实只有 3 和 7 是需要输出 -1 的,其余的数字都是有对应的答案的

代码:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_map>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=5e3+100;

int ans[N];

set<int>dp[20][20];

string s=" 11451419191145141919";

void dfs(int l,int r)
{
	if(dp[l][r].size())
		return;
	if(r-l+1<=4)
	{
		int num=stoi(s.substr(l,r-l+1));
		if(num<=5000)
			dp[l][r].insert(num);
	}
	for(int i=l;i<r;i++)
	{
		dfs(l,i);
		dfs(i+1,r);
		for(int x:dp[l][i])
			for(int y:dp[i+1][r])
			{
				if(x+y<=5000)
					dp[l][r].insert(x+y);
				if(x*y<=5000)
					dp[l][r].insert(x*y);
			}
	}
}

void init()
{
	memset(ans,-1,sizeof(ans));
	for(int i=1;i<=11;i++)
	{
		dfs(1,i);
		for(int x:dp[1][i])
			if(ans[x]==-1)
				ans[x]=i;
	}
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	init();
	int w;
	cin>>w;
	while(w--)
	{
		int n;
		scanf("%d",&n);
		printf("%d\n",ans[n]);
	}



















    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/107853589