题意:
给出起点与终点,以及k种水管的长度及其数量,求消耗的最少水管从起点修到终点
思路:
首先在假设水管无限多的情况下分别求出横纵坐标到终点的最少步数,然后迭代加深搜索+剪枝即可
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <algorithm>
#define For(i,j,k) for(int i = j;i <= k;i ++)
const int N = 1010;
using namespace std;
int hx[N], hy[N], k, l[5], c[5];
int sx, sy, tx, ty, tot;
void calh(int h[], int ed){
For(i,0,1000)h[i] = -1;
queue<int> q;
q.push(ed);
h[ed] = 0;
while(!q.empty()){
int s = q.front();q.pop();
For(i,1,k){
if(s + l[i] <= 1000 && h[s + l[i]] < 0)
h[s + l[i]] = h[s] + 1, q.push(s + l[i]);
if(s - l[i] >= 0 && h[s - l[i]] < 0)
h[s - l[i]] = h[s] + 1, q.push(s - l[i]);
}
}
}
bool DFS(int dep, int x, int y){
if(hx[x] == -1 || hy[y] == -1 || hx[x] + hy[y] > dep)
return 0;
if(x != tx){
For(i,1,k){
if(!c[i])continue;
--c[i];
if(x + l[i] <= 1000)
if(DFS(dep - 1, x + l[i], y))
return 1;
if(x - l[i] >= 0)
if(DFS(dep - 1, x - l[i], y))
return 1;
++c[i];
}
}
else if(y != ty){
For(i,1,k){
if(!c[i])continue;
--c[i];
if(y + l[i] <= 1000)
if(DFS(dep - 1, x, y + l[i]))
return 1;
if(y - l[i] >= 0)
if(DFS(dep - 1, x, y - l[i]))
return 1;
++c[i];
}
}
else return 1;
return 0;
}
int main(){
scanf("%d%d%d%d%d", &sx, &sy, &tx, &ty, &k);
For(i,1,k)
scanf("%d", &l[i]);
For(i,1,k)
scanf("%d", &c[i]), tot += c[i];
calh(hx, tx);
calh(hy, ty);
if(sx == tx && sy == ty)
puts("0");
else{
For(i,1,tot)
if(DFS(i, sx, sy)){
printf("%d\n", i);
break;
}
else if(i == tot)
puts("-1");
}
return 0;
}

本文介绍了一种解决给定起点和终点、多种长度水管及数量限制下寻找从起点到终点最短路径的问题。通过先计算无限水管情况下的最优解,再使用迭代加深搜索加剪枝的方法找到实际条件下所需的最少水管数量。
686

被折叠的 条评论
为什么被折叠?



