算法竞赛入门经典 第四章


  • [√ ] UVA201 正方形 Squares

    遍历所有点(最右边和最下边的点就没必要了)作为正方形的左上角

    正方形判定通过分别判断四条边实现,如果四条边都能延长至长度len,则形成一个正方形

    注意四条边的判定函数要注意越界的判定

    $\color{green}{UVa12096}$
    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<map>
    #include<iterator>
    #include<set>
    #include<queue>
    using namespace std;
    int H[15][15];
    int V[15][15];
    int n;
    
    int Above(int x,int y,int len) {
        if (y == n) return 0;
        while (len--) {
            if (!H[x][y]) return 0;
            y++;
        }
        return 1;
    }
    
    int Below(int x, int y, int len) {
        if (x > n) return 0;
        if (y == n) return 0;
        while (len--) {
            if (!H[x][y]) return 0;
            y++;
        }
        return 1;
    }
    
    int Left(int x, int y, int len) {
        if (x == n) return 0;
        while (len--) {
            if (!V[x][y]) return 0;
            x++;
        }
        return 1;
    }
    
    int Right(int x, int y, int len) {
        if (x == n) return 0;
        if (y > n) return 0;
        while (len--) {
            if (!V[x][y]) return 0;
            x++;
        }
        return 1;
    }
    
    int squarejudge(int x,int y,int len) {//以(x,y)为左上角,边长为len的正方形
        if (!Above(x,y,len)) return 0;//上边(从左往右
        if (!Below(x+len,y,len)) return 0;//下边(从左往右
        if (!Left(x,y,len)) return 0;//左边(从上往下
        if (!Right(x,y+len,len)) return 0;//右边(从上往下
        return 1;
    }
    int main()
    {
        //FILE* stream1;
        //freopen_s(&stream1,"input.txt", "r", stdin);
        //freopen_s(&stream1,"output.txt", "w", stdout);
        int kase = 0;
        while (cin >> n) {
            memset(H, 0, sizeof(H));
            memset(V, 0, sizeof(V));
            if (kase) cout << endl << "**********************************" << endl << endl;
            cout << "Problem #" << ++kase << endl << endl;
            int found = 0,com_cnt,x,y;
            char com;
            cin >> com_cnt;
            while (com_cnt--) {
                cin >> com >> x >> y;
                if (com == 'H') {
                    H[x][y] = 1;
                }
                else V[y][x] = 1;
            }
            for (int k = 1;k <= n - 1;k++) {
                int ans = 0;
                for (int i = 1;i <= n - 1;i++) {
                    for (int j = 1;j <= n - 1;j++) {
                        if (squarejudge(i, j, k)) {
                            ans++;found = 1;
                        }
                    }
                }
                if(ans) cout << ans << " square (s) of size " << k << endl;
            }
            if (!found) cout << "No completed squares can be found." << endl;
        }
        return 0;
    }
    

posted @ 2020-03-25 18:34  StreamAzure  阅读(243)  评论(0编辑  收藏  举报