牛客寒假算法基礎集訓營3 - F 處女座和小姐姐(二) 雙向dfs+狀壓

題目鏈接

題意:一共 nm+p1n*m+p-1 個數,連續 pp 個數的乘積 modmod PP 作爲矩陣中一個元素。現在在矩陣中找出一條長度爲 kk 的路徑,且路徑上所有元素在 modmod kk 的意義下均不同。問這樣的路徑有多少條?

思路:首先是求連續 pp 個數的乘積 modmod PP,可以把這些數按照 pp 個數爲一組劃分,對於一段連續 pp 個數的乘積即爲其所覆蓋的上一組的後綴積與所覆蓋的這一組的前綴積的乘積。此複雜度爲線性。
其次求長度爲 kk 的路徑,由於 kk 不大於20,可以通過雙向 dfsdfs ,枚舉路徑的中心點,選擇路徑上,通過狀態壓縮來處理,時間複雜度爲 nm2410n*m*2*4^{10}

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int n, m, p, k, K;
long long a[1000505], b[1000505], P;//a爲前綴積,b爲後綴積
int j, i;
int ma[25][25], temp[1048576];
int h[4] = {0, 0, 1, -1}, l[4] = {1, -1, 0, 0};
long long ans;
void dfs(int x, int y, int tot, bool flag, int pick, int cnt)
{
    if(cnt == tot)
    {
        if(flag == false)
            ++temp[pick];
        else
            ans += temp[K - 1 - pick];
        return;
    }
    int nx, ny;
    for (int z = 0; z < 4; ++z)
    {
        nx = x + h[z], ny = y + l[z];
        if (nx <= 0 || nx > n || ny <= 0 || ny > m)
            continue;
        if (ma[nx][ny] == ma[i][j] || pick & (1 << ma[nx][ny]))
            continue;
        dfs(nx, ny, tot, flag, pick | (1 << ma[nx][ny]), cnt + 1);
    }
}
int main()
{
    long long x, y, z;
    int total, cnt = 0;
    scanf("%d%d%d%lld%d", &n, &m, &p, &P, &k);
    scanf("%lld%lld%lld%lld", &a[0], &x, &y, &z);
    if (k == 1)
    {
        printf("%d\n", n * m);
        return 0;
    }
    x %= P, y %= P, z %= P;
    K = 1 << k;
    total = n * m + p - 1;
    for (i = 1; i <= total; ++i)
        a[i] = (a[i - 1] * a[i - 1] % P * x % P + y * a[i - 1] % P + z) % P;
    ans = 1;
    j = 0;
    for (i = p; i <= total; ++i)//把total個數分成K組,每組p個數:[1,p],[p+1,2p],...,[Kp,total]
    {
        (ans *= a[i]) %= P;//第h+1組的當前前綴積
        if (i - p + 1 > j)//第h組的所有後綴積(hp = i)
        {
            j = i;
            ans = 1;
            b[i] = a[i];
            for (int z = i - 1; z >= i - p + 1; --z)
                b[z] = b[z + 1] * a[z] % P;
        }
        temp[++cnt] = (long long)ans * b[i - p + 1] % P;
    }
    cnt = 0;
    for (i = 1; i <= n; ++i)
        for (j = 1; j <= m; ++j)
            ma[i][j] = temp[++cnt] % k;
    ans = 0;
    for (i = 1; i <= n; ++i)
        for (j = 1; j <= m; ++j)
        {
            memset(temp, 0, sizeof(int) * K);
            dfs(i, j, k >> 1, false, 1 << ma[i][j], 1);
            dfs(i, j, (k >> 1) + k % 2 + 1, true, 0, 1);
        }
    printf("%lld\n", ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章