标签:
///1085422276 #include<bits/stdc++.h> using namespace std ; typedef long long ll; #define mem(a) memset(a,0,sizeof(a)) #define meminf(a) memset(a,127,sizeof(a)); #define inf 100000007 inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){ if(ch==‘-‘)f=-1;ch=getchar(); } while(ch>=‘0‘&&ch<=‘9‘){ x=x*10+ch-‘0‘;ch=getchar(); }return x*f; } //**************************************** #define maxn 105 int dis[maxn][maxn],vis[maxn][maxn],v[maxn],n,m,q,st,ed; int mp[maxn][maxn],mps[maxn][maxn],a[maxn],b[maxn],ans; int ss[4][2]={-1,0,0,-1,1,0,0,1}; bool check(int x,int y){ if(x<=0||y<=0||x>n||y>m)return 1;return 0; } void bfs(int x,int y){ mem(vis);memset(dis,127/2,sizeof(dis)); queue<pair<int ,int > >q; q.push(make_pair(x,y)); vis[x][y]=1;dis[x][y]=0; while(!q.empty()){ pair<int ,int >k; k=q.front();q.pop(); for(int i=0;i<4;i++){ int xx=k.first+ss[i][0]; int yy=k.second+ss[i][1]; if(check(xx,yy)||mp[xx][yy]==‘#‘||vis[xx][yy])continue; dis[xx][yy]=dis[k.first][k.second]+1; vis[xx][yy]=1;q.push(make_pair(xx,yy)); } } } void floyd(int x,int sum) { v[x]=1; bool flag=1; for(int i=1;i<=q;i++){ if(!v[i])flag=0; } if(flag)ans=min(ans,sum); int tmp=inf*2; for(int i=1;i<=q;i++) { if(!v[i]&&mp[x][i]!=0){ floyd(i,sum+mps[x][i]); } } v[x]=0; } void test(){ for(int i=1;i<=q;i++){ for(int j=1;j<=q;j++){ cout<<mps[i][j]<<" "; } cout<<endl; } } int main() { while(scanf("%d%d",&n,&m)&&n&&m){ for(int i=1;i<=n;i++){ getchar(); for(int j=1;j<=m;j++){ scanf("%c",&mp[i][j]); if(mp[i][j]==‘@‘){st=i;ed=j;} } } q=read(); for(int i=1;i<=q;i++){ scanf("%d%d",&a[i],&b[i]); }q++;a[q]=st;b[q]=ed;mem(mps); for(int i=1;i<=q;i++){ bfs(a[i],b[i]);//test();//return 0; for(int j=1;j<=q;j++){ if(j!=i){ mps[i][j]=dis[a[j]][b[j]]; } } }mem(v);//test();//cout<<q<<endl; ans=inf;floyd(q,0);if(ans>=inf)ans=-1; printf("%d\n",ans); } return 0; }
HDU 4771 Stealing Harry Potter's Precious dfs+bfs
标签:
原文地址:http://www.cnblogs.com/zxhl/p/4910101.html