-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlightoj 1057.cpp
More file actions
144 lines (129 loc) · 2.6 KB
/
lightoj 1057.cpp
File metadata and controls
144 lines (129 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// Created by ash_98
#include<bits/stdc++.h>
using namespace std;
#define mx 25
#define ll long long
#define mod 1000000007
int ar[mx];
char ch[mx][mx];
int n,m,k,ii;
vector<pair<int,int>>v;
int dist[mx][mx][mx][mx];
int xx[]={1,1,0,0,-1,1,-1,-1};
int yy[]={-1,1,1,-1,0,0,1,-1};
int dp[(1<<15)+5][16];
int vis[(1<<15)+5][16];
int stx,sty;
int Set(int N,int pos)
{
return N=N|(1<<pos);
}
int Reset(int N,int pos)
{
return N=N & ~(1<<pos);
}
bool chk(int N,int pos)
{
return (bool)(N &(1<<pos));
}
void dijkstra(int x,int y)
{
dist[x][y][x][y]=0;
priority_queue<pair<int,pair<int,int>>>pq;
pq.push({0,{x,y}});
while(!pq.empty())
{
int cost=pq.top().first;
cost*=-1;
int a=pq.top().second.first;
int b=pq.top().second.second;
pq.pop();
if(dist[x][y][a][b]<cost)continue;
for(int i=0;i<8;i++)
{
int temx=a+xx[i];
int temy=b+yy[i];
if(temx>0 && temx<=n && temy>0 && temy<=m && dist[x][y][temx][temy]>cost+1)
{
dist[x][y][temx][temy]=cost+1;
pq.push({-dist[x][y][temx][temy],{temx,temy}});
}
}
}
}
int func(int mask,int last)
{
if(mask==(1<<k)-1)return dist[v[last].first][v[last].second][stx][sty];
if(vis[mask][last]==ii)return dp[mask][last];
vis[mask][last]=ii;
int re=1e6;
for(int i=0;i<k;i++)
{
if(!chk(mask,i))
{
int cost=0;
if(mask==0)cost=dist[stx][sty][v[i].first][v[i].second];
else cost=dist[v[last].first][v[last].second][v[i].first][v[i].second];
re=min(re,cost+func(Set(mask,i),i));
}
}
return dp[mask][last]=re;
}
void solve()
{
scanf("%d%d",&n,&m);
v.clear();
for(int i=1;i<=n;i++)scanf("%s",ch[i]+1);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(ch[i][j]=='g')v.push_back({i,j});
if(ch[i][j]=='x')stx=i,sty=j;
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
for(int l=1;l<=n;l++)
{
for(int z=1;z<=m;z++)dist[i][j][l][z]=1e6;
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
dijkstra(i,j);
}
}
// for(int i=1;i<=n;i++)
// {
// for(int j=1;j<=m;j++)
// {
// for(int l=1;l<=n;l++)
// {
// for(int z=1;z<=m;z++)
// {
// cout<<i<<" "<<j<<" "<<l<<" "<<z<<" "<<dist[i][j][l][z]<<endl;
// }
// }
// }
// }
ii++;
k=v.size();
if(v.size()==0)printf("Case %d: 0\n",ii );
else printf("Case %d: %d\n",ii,func(0,0));
}
int main()
{
int t=1;
scanf("%d",&t);
while(t--)
{
solve();
}
return 0;
}