跳到正文

个人记录

搜索

jltyzy约 15 分钟
原文
文章信息与版本

文章信息

发布
2026年9月30日
收录
2026年11月4日
更新
2026年11月12日
篇幅
约 15 分钟

版本

  1. v1当前

折半搜索 MeetInTheMiddle

折半搜索也叫双向搜索,就是把搜索的指数减半,再对两侧合并,典型问题有求子集元素和小于定值的个数,另一侧二分可以做到 2n/22^{n/2}。

P3067,这道题每个元素有三种状态,在两个集合中分别呈现正负不同的贡献,在每一侧计算元素和的时候再将所选位置的二进制表示记录下来,最后直接 2n2^n 枚举判断即可。

C++
#include <bits/stdc++.h>
using namespace std;
struct node
{
	long long sum;
	int mask;
	bool operator < (const node &x)const
	{
		if(sum==x.sum)
			return mask<x.mask;
		return sum<x.sum;
	}
	bool operator == (const node &x)const
	{
		return sum==x.sum&&mask==x.mask;
	}
};
long long a[25];
void dfs(int l,int r,long long sum,int mask,vector <node> &res)
{
	if(l>r)
	{
		res.push_back({sum,mask});
		return;
	}
	dfs(l+1,r,sum,mask,res);
	dfs(l+1,r,sum+a[l],mask|(1<<(l-1)),res);
	dfs(l+1,r,sum-a[l],mask|(1<<(l-1)),res);
}
int av[2000005];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%lld",&a[i]);
	int mid=n/2;
	vector <node> lx,rx;
	dfs(1,mid,0,0,lx);
	dfs(mid+1,n,0,0,rx);
	sort(lx.begin(),lx.end());
	lx.erase(unique(lx.begin(),lx.end()),lx.end());
	sort(rx.begin(),rx.end());
	rx.erase(unique(rx.begin(),rx.end()),rx.end());
	for(node tmp:lx)
	{
		node l={-tmp.sum,-1},r={-tmp.sum,1000000000};
		auto it1=lower_bound(rx.begin(),rx.end(),l);
		auto it2=upper_bound(rx.begin(),rx.end(),r);
		for(auto it=it1;it!=it2;it++)
			if(tmp.mask|it->mask)
				av[tmp.mask|it->mask]=1;
	}
	int ans=0;
	for(int i=1;i<(1<<n);i++)
		if(av[i])
			ans++;
	printf("%d\n",ans);
	return 0;
}

A*

有一个代表式 f(n)=g(n)+h(n)f(n)=g(n)+h(n),f(n)f(n) 表示最终总代价,g(n)g(n) 表示已消耗代价,h(n)h(n) 表示估价,是 A∗A* 算法的关键。正常做 bfsbfs 会进行全方位的搜索,h(n)h(n) 则会对未来的消费进行评估,这样会选择较优的前进方向,避免不必要的状态枚举。对于每个状态采用 DijkstraDijkstra 的方法取最优。

h(n)h(n) 要满足尽量靠近真实未来值,却一定不能比真实优,最经典就是在网格图里用曼哈顿距离估价。

下面是模板:P1379。

C++
#include <bits/stdc++.h>
using namespace std;
string t="123804765";
int tx[10],ty[10],dx[]={-1,0,1,0},dy[]={0,1,0,-1};
struct node
{
	string s;
	int g,h;
	bool operator <(const node &x)const
	{
		return g+h>x.g+x.h;
	}
};
int H(string s)
{
	int res=0;
	for(int i=0;i<9;i++)
	{
		int num=s[i]-'0';
		if(num==0)
			continue;
		res+=abs(i/3-tx[num])+abs(i%3-ty[num]);
	}
	return res;
}
int Astar(string start)
{
	priority_queue <node> q;
	unordered_map <string,int> dis;
	dis[start]=0;
	q.push({start,0,H(start)});
	while(!q.empty())
	{
		node tmp=q.top();
		q.pop();
		string s=tmp.s;
		int g=tmp.g;
		if(g!=dis[s])
			continue;
		if(s==t)
			return g;
		int pos=s.find('0'),x=pos/3,y=pos%3;
		for(int i=0;i<4;i++)
		{
			int nx=x+dx[i],ny=y+dy[i];
			if(nx<0||nx>2||ny<0||ny>2)
				continue;
			int np=nx*3+ny;
			string ns=s;
			swap(ns[pos],ns[np]);
			if(!dis.count(ns)||g+1<dis[ns])
			{
				dis[ns]=g+1;
				q.push({ns,g+1,H(ns)});
			}
		}
	}
	return -1;
}
int main()
{
	string s;
	cin>>s;
	for(int i=0;i<9;i++)
	{
		int num=t[i]-'0';
		tx[num]=i/3;
		ty[num]=i%3;
	}
	printf("%d\n",Astar(s));
	return 0;
}

IDA*

IDA∗IDA* 与 A∗A* 最大的不同在于它使用了 dfsdfs,我们需要枚举期望的步数。dfsdfs 中若 g+h>limg+h>lim 就停止,而 h=0h=0 认作找到答案,所以计算 hh 是一定注意不要将非答案的情况认作 00,其他基本相同。

P2324

C++
#include <bits/stdc++.h>
using namespace std;
char mp[5][5];
char tg[5][5]={{'1','1','1','1','1'},{'0','1','1','1','1'},{'0','0','*','1','1'},{'0','0','0','0','1'},{'0','0','0','0','0'}};
int dx[]={2,-2,2,-2,1,-1,1,-1},dy[]={1,-1,-1,1,2,-2,-2,2};
int H()
{
	int res=0;
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
			if(mp[i][j]!='*'&&mp[i][j]!=tg[i][j])
				res++;
	return res;
}
bool dfs(int x,int y,int dep,int lmt,int las)
{
	int val=H();
	if(dep+val>lmt)
		return false;
	if(val==0)
		return true;
	for(int i=0;i<8;i++)
	{
		if(i==(las^1))
			continue;
		int nx=x+dx[i],ny=y+dy[i];
		if(nx<0||nx>4||ny<0||ny>4)
			continue;
		swap(mp[x][y],mp[nx][ny]);
		if(dfs(nx,ny,dep+1,lmt,i))
			return true;
		swap(mp[x][y],mp[nx][ny]);
	}
	return false;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int sx,sy;
		for(int i=0;i<5;i++)
		{
			string s;
			cin>>s;
			for(int j=0;j<5;j++)
			{
				mp[i][j]=s[j];
				if(mp[i][j]=='*')
					sx=i,sy=j;
			}
		}
		int ans=-1;
		for(int i=0;i<=15;i++)
			if(dfs(sx,sy,0,i,1e9))
			{
				ans=i;
				break; 
			}
		printf("%d\n",ans);
	}
	return 0;
}

DLX

解决精确覆盖问题,即有 nn 个集合 mm 个元素,要选出一些集合,使每个元素在所选集合中恰好出现一次,求方案。模板:P4929。每一行代表一个集合,列代表元素,行中为一的位置代表有这个元素,要求每列在选中行中恰好出现一个一。

先介绍 Algorithm XAlgorithm\ X,这是一种搜索方法,每次选中还没被覆盖的一列,再枚举可以覆盖它的行。选中一个行后需要把它删掉,因为它同时覆盖了另外一些列,这些列不能再被选择,所以要把在这些列有一的行全部删掉。每次搜索后需要回溯。

因为暴力回溯复杂度很高,所以要加入 DancingLinksDancing Links。我们考虑一个链表,将一个点删掉后,它的左侧和右侧信息是保留的,可以快速恢复。用这个就可以快速搜索。

C++
#include <bits/stdc++.h>
using namespace std;
int n,m,tot,anscnt;
int L[6005],R[6005],U[6005],D[6005],sz[505],ans[505],row[6005],col[6005];
void init()
{
	tot=m;
	for(int i=0;i<=m;i++)
	{
		L[i]=i-1;
		R[i]=i+1;
		U[i]=D[i]=i;
		sz[i]=0;
	}
	L[0]=m;
	R[m]=0;
}
void addnode(int r,int c,int &head)
{
	int x=++tot;
	row[x]=r;
	col[x]=c;
	U[x]=U[c];
	D[x]=c;
	D[U[c]]=x;
	U[c]=x;
	sz[c]++;
	if(!head)
	{
		head=x;
		L[x]=R[x]=x;
	}
	else
	{
		L[x]=L[head];
		R[x]=head;
		R[L[head]]=x;
		L[head]=x;
	}
}
void remove(int c)
{
	L[R[c]]=L[c];
	R[L[c]]=R[c];
	for(int i=D[c];i!=c;i=D[i])
		for(int j=R[i];j!=i;j=R[j])
		{
			U[D[j]]=U[j];
			D[U[j]]=D[j];
			sz[col[j]]--;
		}
}
void resume(int c)
{
	for(int i=U[c];i!=c;i=U[i])
		for(int j=L[i];j!=i;j=L[j])
		{
			U[D[j]]=j;
			D[U[j]]=j;
			sz[col[j]]++;
		}
	L[R[c]]=c;
	R[L[c]]=c;
}
bool dance(int dep)
{
	if(R[0]==0)
	{
		anscnt=dep;
		return true;
	}
	int c=R[0];
	for(int i=R[0];i;i=R[i])
		if(sz[i]<sz[c])
			c=i;
	if(!sz[c])
		return false;
	remove(c);
	for(int i=D[c];i!=c;i=D[i])
	{
		ans[dep]=row[i];
		for(int j=R[i];j!=i;j=R[j])
			remove(col[j]);
		if(dance(dep+1))
			return true;
		for(int j=L[i];j!=i;j=L[j])
			resume(col[j]);
	}
	resume(c);
	return false;
}
int main()
{
	scanf("%d%d",&n,&m);
	init();
	for(int i=1;i<=n;i++)
	{
		int head=0;
		for(int j=1;j<=m;j++)
		{
			int x;
			scanf("%d",&x);
			if(x)
				addnode(i,j,head);
		}
	}
	if(!dance(0))
		puts("No Solution!");
	else
	{
		for(int i=0;i<anscnt;i++)
			printf("%d ",ans[i]);
		puts("");
	}
	return 0;
}

下面一道例题:P4205。

这种精确覆盖问题可以体现成有一些方案,每个可以满足一些条件,要求每个条件恰好满足一次,可以解决数独问题。

在这道题中,每一块的合法摆放方案是行,要求每一格被覆盖、每一块用一次使列,可以直接做 DLXDLX。

这是一个实现封装:

C++
struct DLX
{
	int L[10005],R[10005],U[10005],D[10005],sz[105],ans[10005],row[10005],col[10005],tot,anscnt;
	DLX()
	{
		tot=67;
		for(int i=0;i<=tot;i++)
		{
			L[i]=i-1,R[i]=i+1;
			U[i]=D[i]=i;
			sz[i]=0;
		}
		L[0]=tot;
		R[tot]=0;
	}
	void add(int r,const vector <int>& cs)
	{
		int head=0;
		for(int c:cs)
		{
			int x=++tot;
			row[x]=r,col[x]=c;
			U[x]=U[c],D[x]=c;
			D[U[c]]=x,U[c]=x;
			sz[c]++;
			if(!head)
			{
				head=x;
				L[x]=R[x]=x;
			}
			else
			{
				L[x]=L[head],R[x]=head;
				R[L[head]]=x,L[head]=x;
			}
		}
	}
	void remove(int c)
	{
		L[R[c]]=L[c];
		R[L[c]]=R[c];
		for(int i=D[c];i!=c;i=D[i])
			for(int j=R[i];j!=i;j=R[j])
			{
				U[D[j]]=U[j];
				D[U[j]]=D[j];
				sz[col[j]]--;
			}
	}
	void resume(int c)
	{
		for(int i=U[c];i!=c;i=U[i])
			for(int j=L[i];j!=i;j=L[j])
			{
				U[D[j]]=j;
				D[U[j]]=j;
				sz[col[j]]++;
			}
		L[R[c]]=c;
		R[L[c]]=c;
	}
	bool dance(int dep)
	{
		if(!R[0])
		{
			anscnt=dep;
			return true;
		}
		int c=R[0];
		for(int i=R[0];i;i=R[i])
			if(sz[i]<sz[c])
				c=i;
		if(!sz[c])
			return false;
		remove(c);
		for(int i=D[c];i!=c;i=D[i])
		{
			ans[dep]=row[i];
			for(int j=R[i];j!=i;j=R[j])
				remove(col[j]);
			if(dance(dep+1))
				return true;
			for(int j=L[i];j!=i;j=L[j])
				resume(col[j]);
		}
		resume(c);
		return false;
	}
}dlx;

完结!!!

原文