在奇怪的表格上打印特定的数字

Ola*_*oja 2 c++ algorithm

我有一个由非负整数组成的表,这些整数以这种方式排列:表中的每个元素都是不在其左侧或上方出现的最小值.这是一个6x6网格的示例:

0 1 2 3 4 5
1 0 3 2 5 4
2 3 0 1 6 7
3 2 1 0 7 6
4 5 6 7 0 1
5 4 7 6 1 0 
Run Code Online (Sandbox Code Playgroud)

第一行和第一行以0 1 2 3 4 5开始...在坐标(x,x)中始终为0,如您所见.在此之后的每个图块上,您必须放置在同一行或列上尚不存在的最小正数.就像在数独拼图中一样:在同一行和列上不能有两次数字.

现在我必须在给定的坐标(y,x)中打印数字.例如[2,5] = 5

我提出了一个有效的解决方案,但它占用了太多的内存和时间,我只知道还有另一种方法.我的时间限制是1秒,我必须找到的坐标数最多可以达到(1000000,1000000).

这是我目前的代码:

#include <iostream>
#include <vector>

int main()
{
    int y, x, grid_size;
    std::vector< std::vector<int> > grid;

    std::cin >> y >> x; // input the coordinates we're looking for

    grid.resize(y, std::vector<int>(x, 0)); // resize the vector and initialize every tile to 0

    for(int i = 0; i < y; i++)
        for(int j = 0; j < x; j++)
        {
            int num = 1;

            if(i != j) { // to keep the zero-diagonal

                for(int h = 0; h < y; h++)
                    for(int k = 0; k < x; k++) { // scan the current row and column
                        if(grid[h][j] == num || grid[i][k] == num) { // if we encounter the current num
                            num++;                                   // on the same row or column, increment num
                            h = -1; // scan the same row and column again
                            break;
                        }
                    }

                grid[i][j] = num; // assign the smallest number possible to the current tile

            }
        }

    /*for(int i = 0; i < y; i++) {            // print the grid
        for(int j = 0; j < x; j++)            // for debugging
            std::cout << grid[i][j] << " ";   // reasons

        std::cout << std::endl;
    }*/

    std::cout << grid[y-1][x-1] << std::endl; // print the tile number at the requested coordinates
    //system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以我该怎么做?这比我想象的要容易吗?

int*_*jay 5

总结一下你的问题:你有一个表,其中每个元素是最小的非负整数,它不会出现在其左侧或上方.您需要在位置(x,y)找到元素.

结果非常简单:如果xy是0,那么(x,y)处的元素是x XOR y.这与您发布的表格相匹配.我已经通过实验验证了200x200的表格.

证据:

很容易看出相同的数字在同一行或列上不会出现两次,因为如果x 1 ^ y = x 2 ^ y那么必然x 1 = x 2.

要看到这x^y是最小的:让a一个小于的数字x^y.让i是其中最左边的位的索引(从右侧)a不同于x^y.第ith位a必须为0且第ith位x^y必须为1.

因此,该位中的任何一个xy必须具有0 i.假设WLOG是x0,代表xy:

x = A0B
y = C1D
Run Code Online (Sandbox Code Playgroud)

其中A,B,C,D是比特序列,B和D是比i特长.由于最左边的位与a以下位中的相同x^y:

a^x = C0E
Run Code Online (Sandbox Code Playgroud)

其中E是i比特序列.所以我们可以看到a^x < y.(a^x)在同一列的第th行中出现的值是:(a^x)^x = a.因此,该值a必须已经出现在同一行(或列,如果它y在第in位中为0 ).对于小于的任何值都是如此x^y,因此x^y确实是最小可能值.