CH2601 电路维修(算竞进阶习题)

时间:2020-12-08 15:37:37

01边bfs

这题很容易想到的就是根据符号的情况建图,把每个点方格的对角线看成图的节点,有线相连就是边权就是0,没有就是1

然后跑最短路,但是最短路用的优先队列维护是有logn的代价的

这题还有一个更快的方法,就是双端队列。。0边放队头,1边放队尾,然后虽然每个点会入队多次,但是我们只要取第一次出队(最短的情况)就行了

时间复杂度为O(r*c)

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
char g[510][510];
int r, c, cnt, head[510*510], d[510*510], ed;
bool vis[510*510];
struct Edge{
int v, next, dis;
}edge[500000<<1]; void addEdge(int a, int b, int w){
edge[cnt].v = b, edge[cnt].dis = w, edge[cnt].next = head[a];
head[a] = cnt ++;
} int bfs(){
memset(d, -1, sizeof d);
memset(vis, 0, sizeof vis);
deque<pair<int, int>> q;
d[1] = 0;
q.push_front(make_pair(1, 0));
while(!q.empty()){
int s = q.front().first, d = q.front().second; q.pop_front();
if(s == ed) return d;
if(vis[s]) continue;
vis[s] = true;
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(!vis[u]){
if(edge[i].dis == 1) q.push_back(make_pair(u, d + 1));
else q.push_front(make_pair(u, d));
}
}
}
return -1;
} int main(){ int _; scanf("%d", &_);
for(; _; _ --){
memset(head, -1, sizeof head);
cnt = 0;
scanf("%d%d", &r, &c);
for(int i = 1; i <= r; i ++) scanf("%s", g[i] + 1);
for(int i = 1; i <= r; i ++){
for(int j = 1; j <= c; j ++){
int a = (i - 1) * (c + 1) + j, b = a + 1;
int d = a + c + 2, c = d - 1;
if(g[i][j] == '\\'){
addEdge(a, d, 0), addEdge(d, a, 0);
addEdge(b, c, 1), addEdge(c, b, 1);
}
else{
addEdge(a, d, 1), addEdge(d, a, 1);
addEdge(b, c, 0), addEdge(c, b, 0);
}
}
}
//for(int i = 0; i < cnt; i ++) cout << edge[i].v << " " << edge[i].dis << endl;
ed = (r + 1) * (c + 1);
int ans = bfs();
printf(ans == -1 ? "NO SOLUTION\n" : "%d\n", ans);
}
return 0;
}