建立一個鏡子 sturct 內處理四方向的下個鏡子,接著利用遞迴或迴圈依序找就好了。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Mirror{
Mirror *d[4] = {};
int x, y, type;
Mirror(int x, int y, int type): x(x), y(y), type(type){}
int answer(int in_dir) {
int nxt_d = (6 - in_dir + (type ? 1:3)) % 4;
Mirror *nxt = d[nxt_d];
return 1 + (nxt ? nxt->answer(nxt_d) : 0);
}
};
vector<Mirror *> X[60001], Y[60001];
int main() {
int n, x, y, type;
scanf("%d", &n);
for (int i=0; i<n; i++) {
scanf("%d%d%d", &x, &y, &type);
y += 30000;
Mirror *mirror = new Mirror(x, y, type);
X[x].push_back(mirror);
Y[y].push_back(mirror);
}
// Build Graph
for (int i=0; i<=60000; i++) {
sort(X[i].begin(), X[i].end(), [](Mirror *L, Mirror *R){return L->y < R->y;});
for (int j=1; j<X[i].size(); j++) {
X[i][j-1]->d[1] = X[i][j], X[i][j]->d[3] = X[i][j-1];
}
sort(Y[i].begin(), Y[i].end(), [](Mirror *L, Mirror *R){return L->x < R->x;});
for (int j=1; j<Y[i].size(); j++)
Y[i][j-1]->d[0] = Y[i][j], Y[i][j]->d[2] = Y[i][j-1];
}
printf("%d\n", Y[30000].size() ? Y[30000][0]->answer(0): 0);
}