POJ 2445 Squares (未优化)

A children’s board game consists of a square array of dots that contains lines connecting some dots. One part of the game requires that the players count the number of squares that are formed by these lines. For example, in the figure shown below, there are 3 squares, 2 of size 1 and 1 of size 2 , so the total number of squares is 3. (The “size” of a square is the number of lines segments required to form a side.)
在这里插入图片描述

Your task is to write a program to count the number of all the possible squares.

Input
The input represents a series of game boards. Each board consists of a description of a square array of n ^ 2 dots (where 2 <= n <= 1500) and some interconnecting horizontal and vertical lines. A record of a single board with n ^ 2 dots and m (m <= 300000 )interconnecting lines is formatted as follows:

Line 1: “n” the number of dots in a single row or column.
Line 2: “m” the number of interconnecting lines.
Each of the next m lines are one of following two types:

“H i j k” (1 <= i, j <= n, k >0, j + k <= n) indicates a horizontal line of length k from the dot in row i, column j to the dot in row i, column j + k.

or

“V i j k” (1 <= i, j <= n, k >0, i + k <= n) indicates a vertical line of length k from the dot in row i, column j to the dot in row i + k, column j.

The end of input is indicated by end-of-file.

Output
For each record print only one integer, which is the number of squares.

Sample Input
4
9
H 1 1 1
H 1 3 1
H 2 1 3
H 3 2 1
H 4 2 2
V 1 1 1
V 1 2 3
V 2 3 1
V 1 4 3
4
9
H 1 1 1
H 1 3 1
H 2 1 3
H 3 2 1
H 4 2 2
V 1 1 1
V 1 2 3
V 2 3 1
V 1 4 3

Sample Output
3
3

代码如下(这种方法数组需要开得非常大,超时,暂未优化):

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;
 
int n,m;
int h[105][105];
int v[105][105];
int main()
{
    int cont=0;
    while(~scanf("%d %d",&n,&m))
    {
        char op;
        int a,b,c;
        memset(h,0,sizeof(h));
        memset(v,0,sizeof(v));
        while(m--)
        {
            cin>>op>>a>>b>>c;
            if(op=='H')
            	for(int i=b;i<b+c;i++)
                	h[a][i]=1;
            else
            	for(int j=a;j<a+c;j++)
                	v[j][b]=1;
        }
        int sum=0;
        for(int s=1;s<=n;s++)// 边从1-n
        {
            int ans=0,flag;// ans 统计 个数
            for(int i=1;i<=n-s;i++)// 暴力枚举
                for(int j=1;j<=n-s;j++)//  控制在n的范围内
                {
                    flag=1;
                    for(int k=j;k<j+s&&flag;k++)// 控制长度
                        if(!h[i][k]||!h[i+s][k]) flag=0;
                    for(int l=i;l<i+s&&flag;l++)
                        if(!v[l][j]||!v[l][j+s]) flag=0;
                    if(flag)
                        ans++;
                }
            sum+=ans;

        }

    	cout<<sum<<endl;
    }
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_19656301/article/details/82824068