算法训练 (DFS/回溯)

算法训练 (DFS/回溯)

八皇后问题:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
int a[10000] = { 0 };
int cnt = 0;
bool place(int row, int cow)
{
//确定当前行数后,从左到右检查是否满足条件
	for (int i = 0; i < row; i++)
	{
	//a[i]记录第i行皇后的所在列
		if (cow == a[i] || abs(a[i] - cow) == abs(i - row))
			return false;
	}
	return true;
}
//暂时确定第k行皇后的位置(根据后续情况回溯更改位置)
void queen(int k, int n)
{
	for (int i = 0; i < n; i++)
	{
		if (place(k, i))
		{
		//a[k]记录第k行皇后的所在列
			a[k] = i;
			if (k == n - 1)
			{
				for (i = 0; i < n; i++)
				cout << a[i]+1 << " ";    //输出一个可行解
				cout << endl;
			}
			else
				queen(k + 1, n);//下一层
		}
	}
}
int main()
{
	int n;
	cin >> n;
	queen(0, n);
	cout << cnt;
}

原题:https://www.luogu.com.cn/problem/P1019

比较直白的DFS,根据首字母找到第一个单词后依次向下搜索,返回长度最大值,需要注意起始条件的判断。

#include<cstdio>
#include<algorithm>
#include<string.h>
#include<iostream>
using namespace std;

int length = 1, n;
int used[1000] = { 0 };//统计出现次数
string str[1000];

int getLength(string A, string B)
{
	for (unsigned i = 1; i < min(A.length(), B.length()); i++)
	{
		int flag = 1;
		for (unsigned j = 0; j < i; j++)
		{
			if (A[A.length() - i + j] != B[j])//首尾比较;若在该长度内出现一个不相等则不为重叠部分;反之,易得最大重叠部分长度为i
				flag = 0;
		}
		if (flag)
			return i;
	}
}

void DFS(int length_current, string current)
{
	length = max(length, length_current);
	for (int i = 0; i < n; i++)
	{
		if (used[i] >= 2)
			continue;
		int same = getLength(current, str[i]);
		if (same)
		{
			used[i]++;//进入下一层
			DFS(length_current + int(str[i].length()) - same, str[i]);
			used[i]--;//回退到上一结点
		}
	}
}
int main()
{
	cin >> n;
	for (int i = 0; i <= n; i++)
		cin >> str[i];
	DFS(1, ' '+str[n]);//防止getLength的第一个循环无法开始
	cout << length;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值