Description Karel is a robot who lives in a rectangular coordinate system where each place is designated by a set of integer coordinates (x and y). Your job is to design a program that will help Karel pick up a number of beepers that are placed in Karel can only move along the x and y axis, never diagonally. Moving from one position (i, j) to an adjacent position (i, j + 1), (i, j ? 1), (i ? 1, j), or (i + 1, j) You can assume that Karel’s world is never larger than 20 × 20 squares and that there will never be more than 10 beepers to pick up. Each coordinate will be given as a pair (x, y) where each value will be in the range 1 through the size Input First there will be a line containing the number of scenarios you are asked to help Karel in. For each scenario there will first be a line containing the size of the world. This will be given as two integers (x-size and y-size). Next there Output The output will be one line per scenario, giving the minimum distance that Karel has to move to get from her starting position to each of the beepers and back again to the starting position. Sample Input 1 10 10 1 1 4 2 3 5 5 9 4 6 5 Sample Output The shortest path has length 24 Source |
简单的DFS暴搜,操,但是做的时候不知道怎么想的。直接暴力枚举所有情况取最小值
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> using namespace std; int tt,n,m,s,t,x; int cnt,ans,sum;//cnt记录了多少点,ans记录答案,sum记录中间的可行答案 int visit[550]; struct node{ int x,y;; }e[550]; void dfs(int xx,int yy) { if(sum>ans)//剪枝 return ; // cout<<"cnt "<<cnt<<endl; // cout<<"sum "<<sum<<endl; if(cnt==x) { // cout<<"fuck "<<sum<<endl; int temp=sum+abs(xx-s)+abs(yy-t); if(temp<ans) ans=temp; return ; } for(int i=0;i<x;i++) { if(!visit[i]) { int temp=abs(e[i].x-xx)+abs(e[i].y-yy); visit[i]=1; cnt++; sum+=temp; dfs(e[i].x,e[i].y); cnt--; sum-=temp; visit[i]=0; } } } int main() { cin>>tt; while(tt--) { cin>>n>>m>>s>>t>>x; for(int i=0;i<x;i++) cin>>e[i].x>>e[i].y; // cout<<s<<" "<<t<<endl; // cout<<"s "<<x<<endl; ans=INT_MAX; cnt=0; sum=0; dfs(s,t); printf("The shortest path has length %d\n",ans); } }
POJ 2907 Collecting Beepers (DFS+回溯)