参照别人的思路,利用移位操作来记录状态,首先计算出所有可能符合要求的延迟的值,注意最多的延迟是n。然后开始进行dfs操作,每次操作要记录当前所操作的任务的id,如果操作到了最后一个任务要判断能否对最终的结果进行更新,如果是中间任务,要加入剪枝操作,如果在当前的延迟条件下,剩余的任务都最小延迟还是会使最终的时间超过当前记录的最优的值,那么就不需要进行后续操作了,在未被剪枝的条件下,继续递归操作,直到最后,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
int n,ans;
int unit[5];
vector<int> feaStep;
bool judge(int *cur,int offset){
for (int i = 0; i < 5; i++){
if (unit[i] & (cur[i] >> offset)) return false;
}
return true;
}
void dfs(int taskId,int curTime,int *state){
if (taskId == 9){
if (curTime + n < ans) ans = curTime + n;
return;
}
int temp[5];
for (int i = 0; i < feaStep.size(); i++){
if (curTime +feaStep[i]+ (9 - taskId - 1)*feaStep[0] + n > ans) return;
memcpy(temp, state, sizeof(temp));
if (!judge(temp, feaStep[i])) continue;
for (int j = 0; j < 5; j++) temp[j] =(temp[j]>>feaStep[i])|unit[j];
dfs(taskId + 1, curTime + feaStep[i], temp);
}
}
int main(){
while (cin >> n){
if (n == 0) break;
ans = 1 << 20;
feaStep.clear();
memset(unit, 0, sizeof(unit));
for (int i = 0; i < 5; i++){
string s;
cin >> s;
for (int j = 0; j < n; j++){
if (s[j] == 'X') unit[i] |= (1 << j);
}
}
int temp[5];
for (int i = 0; i <= n; i++){
if (judge(unit, i)) feaStep.push_back(i);
}
memcpy(temp, unit, sizeof(temp));
dfs(0, 0, temp);
cout << ans << endl;
}
return 0;
}