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
| #include<stdio.h>
#include<algorithm>
#include<math.h>
#include<string.h>
using namespace std;
const int MAXN = 1005;
int L[MAXN*MAXN], R[MAXN*MAXN], U[MAXN*MAXN], D[MAXN*MAXN];
int S[MAXN];
int Col[MAXN*MAXN], Row[MAXN*MAXN],ans,limit,up;
void Remove(int c) {
L[R[c]] = L[c];
R[L[c]] = R[c];
for (int i = D[c]; i != c; i = D[i])
for (int j = R[i]; j != i; j = R[j]) {
U[D[j]] = U[j];
D[U[j]] = D[j];
-- S[Col[j]];
}
}
void Resume(int c) {
for (int i = U[c]; i != c; i = U[i])
for (int j = L[i]; j != i; j = L[j]) {
U[D[j]] = j;
D[U[j]] = j;
++ S[Col[j]];
}
L[R[c]] = c;
R[L[c]] = c;
}
bool dfs(int depth) {
if (depth >= ans) return true;
if(R[0] == 0) { if(depth < ans)ans = depth; return true; }
int i, j, c, minnum = 2000000000, flag = 0;
for (i = R[0]; i != 0; i = R[i]) {
if (S[i] < minnum) {
minnum = S[i];
c = i;
}
}
Remove(c);
for (i = U[c]; i != c; i = U[i]) {
//如果需要的话,在这里记录一组解(Ans[depth] = Row[i])
for (j = R[i]; j != i; j = R[j]) Remove(Col[j]);
if (dfs(depth + 1)) flag = 1; //return true;
for (j = L[i]; j != i; j = L[j]) Resume(Col[j]);
}
Resume(c);
return flag;//false;
}
int solve(int n, int m, int DL[][MAXN]) {
for (int i = 0; i <= m; i ++) {
L[i] = i - 1;
R[i] = i + 1;
U[i] = D[i] = i;
}
L[0] = m;
R[m] = 0;
int cnt = m + 1;
memset(S, 0, sizeof (S));
for (int i = 1; i <= n; i ++) {
int head = cnt, tail = cnt;
for (int c = 1; c <= m; c ++) if (DL[i][c]) {
S[c] ++;
Row[cnt] = i;
Col[cnt] = c;
U[D[c]] = cnt;
D[cnt] = D[c];
U[cnt] = c;
D[c] = cnt;
L[cnt] = tail;
R[tail] = cnt;
R[cnt] = head;
L[head] = cnt;
tail = cnt;
cnt ++;
}
}
if (dfs(0)) return true;
return false;
}
int mark[MAXN][MAXN];
int main()
{
int i,j,k,l,n,m,T,row,col,x1,x2,y1,y2,id[33][33],low;
scanf("%d",&T);
while(T--)
{
scanf("%d %d %d",&n,&m,&row);
col = 0;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
col++; id[i][j] = col;
}
for(i=1;i<=row;i++)
for(j=1;j<=col;j++)mark[i][j] = 0;
for(i=1;i<=row;i++)
{
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
x1++; y1++;
for(k=x1;k<=x2;k++)
for(l=y1;l<=y2;l++)
mark[i][id[k][l]] = 1;
}
ans = 1000000000;
if(!solve(row, col, mark))ans = -1;
printf("%d\n",ans);
}
return 0;
}
|