题解:P4621 [COCI 2012/2013 #6] BAKTERIJE

· · 题解

简单题,没有任何细节。

直接搜出每个细菌从四种方向进入陷阱的周期。然后暴力枚举每种细菌是从哪个方向进入的。

使用 ExCRT 合并周期,算出最后的时间即可。注意我们的时间是形如 kT+d 的形式,但是可能 d>T(第一次进入时间大于周期),这个时候直接用同余方程 x\equiv d\pmod T 的话可能得到 <d 的解。我们需要对于最后得到的解,进行 \ge d 的约束检测,如果不满足这个约束就加上若干倍的周期使得其 \ge d。

#include<bits/stdc++.h>
#define pb emplace_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef __int128 i128; 
const int maxn=55;
void cmin(ll &x,i128 y){ x=x<y?x:y; }
struct node{ int x,y,t; }b[maxn]; ll ans=LLONG_MAX;
vector<pair<int,int> > vec[maxn],E;//T d
int n,m,K,a[maxn][maxn][maxn],vis[maxn][maxn][4],lst[5],sx,sy;
int dx[]={-1,0,1,0},dy[]={0,1,0,-1},ID; char S[maxn];
int to(char c){
    if(c=='U') return 0; if(c=='R') return 1;
    if(c=='D') return 2; if(c=='L') return 3;
}
bool chk(int T){
    for(auto z:E){
        if(!z.fi&&z.se!=T) return 0;
        if(z.fi&&((T%z.fi)!=(z.se%z.fi)||T<z.se)) return 0;
    }
    return 1;
}
void exgcd(ll a,ll b,ll& x,ll& y){
    if(!b){ x=1, y=0; return ; }
    exgcd(b,a%b,y,x); y-=x*(a/b);
}
i128 ExCRT(){
    for(auto z:E)
        if(!z.fi){
            if(chk(z.se)) return z.se;
            else return -1;
        }
    ll tm=E.front().fi,ta=E.front().se%tm,x,y;
    for(int i=1;i<E.size();i++){
        ll cm=E[i].fi,ca=E[i].se%cm;
        ll F=(ca-ta%cm+cm)%cm,d=__gcd(tm,cm);
        if(F%d) return -1; cm/=d; F/=d;
        exgcd(tm/d,cm,x,y); x=(x%cm+cm)%cm;
        ta+=(i128)F*x%cm*tm; tm=tm*cm; ta%=tm;
    }
    for(auto z:E){
        if(ta>=z.se) continue;
        ll k=(z.se-ta+tm-1)/tm;
        ta+=k*tm;
    }
    return ta;
}
void dfs(int x,int y,int t,int l){
    if(vis[x][y][t]>=2) return ;
    if(x==sx&&y==sy){
        if(!lst[t]) vec[ID].pb(0,l),lst[t]=l;
        else vec[ID].pb(l-lst[t],lst[t]);
    }
    vis[x][y][t]++; t=(t+a[ID][x][y])%4;
    int nx=x+dx[t],ny=y+dy[t];
    if(nx<1||nx>n||ny<1||ny>m) t=(t+2)%4;
    dfs(x+dx[t],y+dy[t],t,l+1);
}
void solve(int x){
    if(x==K+1){
        i128 res=ExCRT(); 
        if(~res) cmin(ans,res);
        return ;
    }
    for(auto z:vec[x]){ E.pb(z); solve(x+1); E.pop_back(); }
}
int main(){// U0 R1 D2 L3
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin>>n>>m>>K>>sx>>sy;
    for(int i=1;i<=K;i++){
        int x,y; char c;
        cin>>x>>y>>c; b[i]=node{x,y,to(c)};
        for(int j=1;j<=n;j++){
            cin>>(S+1);
            for(int k=1;k<=m;k++) a[i][j][k]=S[k]-'0';
        }
    }
    for(int i=1;i<=K;i++){
        memset(vis,0,sizeof(vis)); ID=i;
        memset(lst,0,sizeof(lst));
        dfs(b[i].x,b[i].y,b[i].t,0);
    }
    solve(1);
    if(ans==LLONG_MAX) cout<<-1;
    else cout<<ans+1;
    return 0;
}