算法训练 (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;
}