直接BFS
class Solution {
public:
int conveyorBelt(vector<string>& matrix, vector<int>& start, vector<int>& end) {
vector ach(matrix.size(),vector<int>(matrix[0].size(),(1<<30)));
auto i = [&](){
queue<pair<int,int>>q;
int f[] = {0,1,0,-1,1,0,-1,0};
string c = {">};
q.push({start[0],start[1]});
ach[start[0]][start[1]] = 0;
while(!q.empty())
{
auto [x,y] = q.front();
q.pop();
for(int i=0;i<4;++i)
{
int nx = x+f[i<<1];
int ny = y+f[i<<1|1];
if(nx>=0 && nx<matrix.size() && ny>=0 && ny<matrix[0].size())
{
if(ach[nx][ny]>ach[x][y]+(matrix[x][y]==c[i]?0:1))
{
ach[nx][ny] = ach[x][y]+(matrix[x][y]==c[i]?0:1);
q.push({nx,ny});
}
}
}
}
return ach[end[0]][end[1]];
};
return i();
}
};
a + 1 b = a ∗ b + 1 b a+\frac{1}{b}=\frac{a*b+1}{b} a+b1=ba∗b+1
class Solution {
public:
vector<int> fraction(vector<int>& cont) {
int c = 1,d = 0;
for(int i=cont.size()-1;i>=0;--i)
{
swap(c,d);
c += cont[i]*d;
}
return {c/gcd(c,d),d/gcd(c,d)};
}
};
状压dp,因为数据量较小,所以暴力处理每一行broken就行
class Solution {
public:
int domino(int n, int m, vector<vector<int>>& broken) {
vector<int>cl(n);
vector<int>nums(n);
vector br(n,vector<int>(m,0));
for(auto i:broken)
{
br[i[0]][i[1]] = 1;
cl[i[0]] |= (1<<i[1]);
}
vector dp(n,vector<int>((1<<m),0));
for(int j=0;j<(1<<m);++j)
{
if(j&cl[0])
continue;
if(n>1 && (j&cl[1]))
continue;
for(int i=0;i<m-1;++i)
{
if(br[0][i]==0 && br[0][i+1]==0 && ((1<<i)&j)==0 && ((1<<(i+1))&j)==0)
{
dp[0][j]++;
++i;
}
}
for(int i=0;i<m;++i)
{
if((1<<i)&j && n>1)
dp[0][j]++;
}
}
for(int i=1;i<n;++i)
{
for(int j=0;j<(1<<m);++j)
{
if(j&cl[i])continue;
if(i<n-1 && (j&cl[i+1]))
continue;
for(int k=0;k<(1<<m);++k)
if(!(j&k))
{
int k1 = dp[i-1][k];
for(int z=0;z<m-1;++z)
{
if(br[i][z]==0 && br[i][z+1]==0 && ((1<<z)&j)==0 && ((1<<(z+1))&j)==0 && ((1<<z)&k)==0 && ((1<<(z+1))&k)==0)
{
k1++;
++z;
}
}
if(i!=n-1)
for(int z=0;z<m;++z)
if((1<<z)&j)
k1++;
dp[i][j] = max(k1,dp[i][j]);
}
}
}
int ans = 0;
for(int i=0;i<(1<<m);++i)
ans = max(dp[n-1][i],ans);
return ans;
}
};
计算循环一次的路径和终点(dx,dy),对于路径每一个点(x1,y1)而言,如果有
x % d x = x 1 y % d y = y 1 x / d x = y / d y x\%dx = x1 \\ y\%dy = y1 \\ x/dx = y/dy x%dx=x1y%dy=y1x/dx=y/dy
显然x/dx=y/dy恒成立,因为xdy=0,ydx=0
说明该路径会到达终点,同理障碍也是。
class Solution {
public:
bool robot(string command, vector<vector<int>>& obstacles, int x, int y) {
int dx=0,dy=0;
for(auto i:command)
if(i=='U')dy++;
else dx++;
int d1 = x/dx,d2 = y/dy;
d1 = min(d1,d2);
bool ok = 0;
int nx=0,ny=0;
if(d1*dx==x && d1*dy==y)
ok = 1;
for(auto i:command)
{
if(i=='U')ny++;
else nx++;
if(x-dx*d1==nx && y-dy*d1==ny)
ok = 1;
for(auto j:obstacles)
{
if(j[0]-min(j[0]/dx,j[1]/dy)*dx==nx && j[1]-min(j[0]/dx,j[1]/dy)*dy==ny && min(j[0]/dx,j[1]/dy)<=d1 && j[0] <=x &&j[1]<=y)
return 0;
if(j[0]%dx==0 && j[1]%dy==0 && j[0]/dx==j[1]/dy && j[0] <=x &&j[1]<=y)
return 0;
}
}
return ok;
}
};