-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdmpg16g2.cpp
129 lines (104 loc) · 2.94 KB
/
dmpg16g2.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Ivan Carvalho
// Solution to https://dmoj.ca/problem/dmpg16g2
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
const int MAXN = 1e3 + 2;
const int MAXK = 32;
ll inter[MAXK], uniao[MAXK];
char entrada[MAXN];
ii vetor[MAXN];
int grid[MAXN][MAXN], ini[MAXN], fim[MAXN], N;
ll soma(ll x) { return (x * (x + 1)) / 2; }
ll histogram() {
vetor[0] = ii(-1, 0);
stack<int> pilha;
pilha.push(0);
for (int i = 1; i <= N; i++) {
while (!pilha.empty() && vetor[pilha.top()] > vetor[i]) {
fim[pilha.top()] = i;
pilha.pop();
}
ini[i] = pilha.top();
pilha.push(i);
}
while (!pilha.empty()) {
fim[pilha.top()] = N + 1;
pilha.pop();
}
ll ans = 0;
for (int i = 1; i <= N; i++) {
ini[i]++;
fim[i]--;
int a = i - ini[i] + 1;
int b = fim[i] - i + 1;
ans += 1LL * a * b * vetor[i].first;
}
return ans;
}
ll histogram_debug() {
ll ans = 0;
for (int i = 1; i <= N; i++) {
int minimo = vetor[i].first;
ans += minimo;
for (int j = i + 1; j <= N; j++) {
minimo = min(vetor[j].first, minimo);
ans += minimo;
}
}
// printf("ANS %lld\n",ans);
return ans;
}
ll solve_uniao(int bitmask) {
if (uniao[bitmask] != -1) return uniao[bitmask];
for (int j = 1; j <= N; j++) vetor[j].second = j;
memset(vetor, 0, sizeof(vetor));
ll ans = soma(N) * soma(N);
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (bitmask & grid[i][j])
vetor[j].first = 0;
else
vetor[j].first++;
}
ans -= histogram();
}
// printf("Uniao %d com %lld\n",bitmask,ans);
return uniao[bitmask] = ans;
}
ll solve_inter(int bitmask) {
if (inter[bitmask] != -1) return inter[bitmask];
int cont = __builtin_popcount(bitmask);
if (cont == 1) return inter[bitmask] = solve_uniao(bitmask);
int cof = (cont % 2 == 0) ? (1) : (-1);
ll ans = 0;
for (int nbitmask = 1; nbitmask < 32; nbitmask++) {
if ((nbitmask & bitmask) != nbitmask) continue;
int ncont = __builtin_popcount(nbitmask);
int ncof = (ncont % 2 == 1) ? (1) : (-1);
if (bitmask == nbitmask) {
ans -= solve_uniao(nbitmask);
} else {
ans += ncof * solve_inter(nbitmask);
}
}
// printf("Inter %d com %lld\n",bitmask,cof*ans);
return inter[bitmask] = cof * ans;
}
int main() {
scanf("%d", &N);
for (int i = 1; i <= N; i++) {
scanf("%s", entrada);
for (int j = 1; j <= N; j++) {
char c = entrada[j - 1];
if (c == '.') continue;
int d = c - 'A';
grid[i][j] = (1 << d);
}
}
memset(inter, -1, sizeof(inter));
memset(uniao, -1, sizeof(inter));
printf("%lld\n", solve_inter(31));
return 0;
}