SRM332 D2H Squares

TopCoder Statistics - Problem Statement

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2010, TopCoder, Inc. All rights reserved.

$4$点が同じアルファベットである正方形は何個存在するか.正方形は,一辺が軸に平行でなければいけない訳ではないので,$2$点を選び,その$2$点を正方形の点として見て,アルファベットが一致しているかをみた.この方法では重複が発生するので,その分最後でちゃんと割ることを忘れない.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <map>
#include <set>
#include <queue>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define INF 1<<30
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<int, int> P;

class Squares {
  public:
  int countSquares(vector <string> field) {
      int h = field.size(), w = field[0].size();

      int ans = 0;
      rep(i, h) {
          rep(j, w) {
              char c = field[i][j];

              rep(y, h) {
                  rep(x, w) {
                      if(i == y && j == x) continue;
                      if(c != field[y][x]) continue;

                      int l1 = y - i;
                      int l2 = x - j;

                      if(0 <= i + l2 && i + l2 < h && 0 <= j - l1 && j - l1 < w) {
                          if(0 <= i + l1 + l2 && i + l1 + l2 < h && 0 <= j + l2 - l1 && j + l2 - l1 < w) {
                              if(c == field[i+l2][j-l1] && c == field[i+l1+l2][j+l2-l1]) {
                                  ans++;
                              }
                          }
                      }
                  }
              }
          }
      }

      return ans / 4;
  }
};
Dec 4th, 2016