Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<cstdio>
- #include<iostream>
- #include<vector>
- #include<set>
- #include<map>
- #include<string>
- #include<stack>
- #include<queue>
- #include<cstdlib>
- #include<cmath>
- #include<utility>
- #include<algorithm>
- using namespace std;
- #define lli long long int
- #define endl "\n"
- int mv[]={0,0,1,-1};
- int mh[]={1,-1,0,0};
- int graph[21][21];
- int ds[11][11];
- int caminhos[10];
- void bfs(int suj1, map<int,int> &sujeira, int n, int m, int inicio)
- {
- vector<bool> usados(n*m,false);
- int mv[]={0,0,1,-1};
- int mh[]={1,-1,0,0};
- queue<int> filona;
- filona.push(suj1);
- vector<int> distancia(n*m,0);
- while(!filona.empty())
- {
- int at=filona.front();
- usados[at]=true;
- filona.pop();
- int x=at%n;
- int y=at/n;
- for(int i=0;i<4;i++)
- {
- int atx=x+mh[i];
- int aty=y+mv[i];
- if(atx >= 0 and atx < n and aty >= 0 and aty < m)
- {
- int f= atx + aty*n;
- if(graph[aty][atx]==1) continue;
- if(!usados[f] and graph[aty][atx]==0)
- {
- filona.push(f);
- distancia[f]=distancia[at]+1;
- if(sujeira.count(f)!=0)
- {
- ds[sujeira[suj1]][sujeira[f]]=distancia[f];
- ds[sujeira[f]][sujeira[suj1]]=distancia[f];
- }
- if(f==inicio)
- {
- ds[sujeira[suj1]][0]=ds[0][sujeira[suj1]]=distancia[f];
- }
- }
- }
- }
- }
- }
- int fb(int n)
- {
- int menor=10000;
- do {
- int ini=0;
- int aux=0;
- int prox=0;
- for(int i=0;i<n;i++)
- {
- prox=ds[ini][caminhos[i]];
- aux+=prox;
- ini=caminhos[i];
- }
- menor=min(menor,aux);
- }while(next_permutation(caminhos,caminhos+n));
- return menor;
- }
- int main()
- {
- ios::sync_with_stdio(false);
- cin.tie(0); cout.tie(0);
- int n,m;
- while(1)
- {
- cin>>n>>m;
- if(n==0 and m==0) break;
- int inicio=0;
- map<int,int> sujeira;
- int k=1;
- for(int i=0;i<m;i++)
- {
- for(int j=0;j<n;j++)
- {
- char p;
- cin>>p;
- if(p=='o')
- {
- graph[i][j]=0;
- inicio= i*n+j;
- }
- if(p=='*')
- {
- int a=0;
- graph[i][j]=0;
- a= i*n + j;
- sujeira.insert(make_pair(a,k));
- k++;
- }
- if(p=='x')
- {
- graph[i][j]=1;
- }
- if(p=='.')
- graph[i][j]=0;
- }
- }
- bool taerrado=false;
- if(sujeira.size()==0)
- {
- cout<<"0"<<endl;
- continue;
- }
- map<int,int>::iterator it;
- for(int i=0;i<=sujeira.size();i++)
- for(int j=0;j<=sujeira.size();j++) ds[i][j]=0;
- for(it= sujeira.begin() ; it!= sujeira.end() ; ++it)
- {
- bfs(it->first, sujeira, n,m,inicio);
- }
- /* for(int i=0;i<=sujeira.size();i++)
- {
- for(int j=0;j<=sujeira.size();j++)
- {
- cout<<ds[i][j]<<" ";
- }
- cout<<endl;
- }*/
- int v=0;
- for(int i=0;i<=sujeira.size();i++)
- {
- v=0;
- for(int j=0;j<=sujeira.size();j++)
- {
- if(ds[i][j]==0)
- v++;
- }
- if(v>1)
- {
- taerrado=true;
- break;
- }
- }
- if(!taerrado)
- {
- for(int i=0;i<sujeira.size();i++) caminhos[i]=i+1;
- cout<<fb(sujeira.size())<<endl;
- }
- else cout<<"-1"<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement