http://poj.org/problem?id=2907
挺简单的一题,但是上来就给想错了。应该是按各个可用点搜索,累加各点间距离取最小,我想的是按坐标全搜,标记过程值。
code:
#include<cstdio>
#include<cstring>
using namespace std ;
const int MAX = 1e8 ;
int n, m, sx, sy, num, ans ;
struct node{
int x, y ;
bool vis ;
}bee[ 11] ;
int dis( int p, int q){
int dx = bee[p].x-bee[q].x< 0?bee[q].x-bee[p].x:bee[p].x-bee[q].x ;
int dy = bee[p].y-bee[q].y< 0?bee[q].y-bee[p].y:bee[p].y-bee[q].y ;
return dx + dy ;
}
void dfs( int sum, int p, int len){
if(len>=ans) return ;
if(sum==num){
int d = len+dis(p, 0) ;
if(d<ans) ans = d ;
return ;
}
for( int i= 1; i<=num; i++){
if(!bee[i].vis){
bee[i].vis = true ;
dfs(sum+ 1, i, len+dis(p, i)) ;
bee[i].vis = false ;
}
}
}
int main(){
int t, x, y ;
scanf( " %d ", &t) ;
while(t--){
scanf( " %d%d ", &n, &m) ;
scanf( " %d%d ", &bee[ 0].x, &bee[ 0].y) ;
scanf( " %d ", &num) ;
for( int i= 1; i<=num; i++){
scanf( " %d%d ", &bee[i].x, &bee[i].y) ;
bee[i].vis = false ;
}
ans = MAX ;
dfs( 0, 0, 0) ;
printf( " The shortest path has length %d\n ", ans) ;
}
return 0 ;
}
#include<cstring>
using namespace std ;
const int MAX = 1e8 ;
int n, m, sx, sy, num, ans ;
struct node{
int x, y ;
bool vis ;
}bee[ 11] ;
int dis( int p, int q){
int dx = bee[p].x-bee[q].x< 0?bee[q].x-bee[p].x:bee[p].x-bee[q].x ;
int dy = bee[p].y-bee[q].y< 0?bee[q].y-bee[p].y:bee[p].y-bee[q].y ;
return dx + dy ;
}
void dfs( int sum, int p, int len){
if(len>=ans) return ;
if(sum==num){
int d = len+dis(p, 0) ;
if(d<ans) ans = d ;
return ;
}
for( int i= 1; i<=num; i++){
if(!bee[i].vis){
bee[i].vis = true ;
dfs(sum+ 1, i, len+dis(p, i)) ;
bee[i].vis = false ;
}
}
}
int main(){
int t, x, y ;
scanf( " %d ", &t) ;
while(t--){
scanf( " %d%d ", &n, &m) ;
scanf( " %d%d ", &bee[ 0].x, &bee[ 0].y) ;
scanf( " %d ", &num) ;
for( int i= 1; i<=num; i++){
scanf( " %d%d ", &bee[i].x, &bee[i].y) ;
bee[i].vis = false ;
}
ans = MAX ;
dfs( 0, 0, 0) ;
printf( " The shortest path has length %d\n ", ans) ;
}
return 0 ;
}