/*******
Author Smile
以后遇到这种拼凑问题
千万要考虑重复情况
dfs的使用范围更新下
他的时间复杂度看情况而定
1e5 这些也有可能的
这题对我的提高真的挺大的
我要重温细节这题很多细节
败在这题我不哭
1. 下面拼凑的纸条可能有些是都吻合的
2. 但是因为顺序的不同最终肯定是不能够拼接完整的
这里就要加上dfs结束条件,这点真的是非常重要
3. 经验 + 1;
再来分析下时间复杂度
dfs是O(n * m + e) 本题
*******/
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int M = 1e2 + 10;
int n, m;
int a[N], h[M][N], k[M];
int path[M];
bool vis[M];
bool check(int a[], int b[], int k, int loc)
{
for (int i = 1; i <= k; ++i)
{
if (a[i] != b[loc + i - 1])
return false;
}
return true;
}
bool dfs(int u, int loc)
{
if (u == m)
{
if (loc != n)
return false;
for (int i = 0; i < m - 1; ++i)
cout << path[i] << ' ';
cout << path[m - 1] << endl;
return true;
}
for (int i = 1; i <= m; ++i)
{
if (!vis[i] && check(h[i], a, k[i], loc))
{
vis[i] = true;
path[u] = i;
if (dfs(u + 1, loc + k[i] - 1))
return true;
vis[i] = false;
}
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> a[i];
cin >> m;
for (int i = 1; i <= m; ++i)
{
cin >> k[i];
for (int j = 1; j <= k[i]; ++j)
{
cin >> h[i][j];
}
}
dfs(0, 1);
return 0;
}
还原文件(dfs)
最新推荐文章于 2024-07-25 13:54:27 发布