1017 - Exact cover
时间限制:15秒 内存限制:128兆
自定评测 6110 次提交 3226 次通过
- 题目描述
- There is an N*M matrix with only 0s and 1s, (1 <= N,M <= 1000). An exact cover is a selection of rows such that every column has a 1 in exactly one of the selected rows. Try to find out the selected rows.
- 输入
- There are multiply test cases. First line: two integers N, M; The following N lines: Every line first comes an integer C(1 <= C <= 100), represents the number of 1s in this row, then comes C integers: the index of the columns whose value is 1 in this row.
- 输出
- First output the number of rows in the selection, then output the index of the selected rows. If there are multiply selections, you should just output any of them. If there are no selection, just output "NO".
- 样例输入
-
6 7
3 1 4 7
2 1 4
3 4 5 7
3 3 5 6
4 2 3 6 7
2 2 7 - 样例输出
-
3 2 4 6
- 提示
- 来源
- dupeng
本人智商奇低,看了三天才学会,模板验证题。
顺便一提这是正式转入C++后第一A。
#include<iostream>
#include<cstdio>
using namespace std; const int HEAD = ;
const int N = ;
int MAP[N][N];
int U[N * N],D[N * N],L[N * N],R[N * N],H[N * N],C[N * N],ANS[N * N]; void ini(int col);
bool dancing(int k);
void output(void);
void remove(int c);
void resume(int c);
int main(void)
{
int n,m,num,col;
int count,front,first; while(cin >> n >> m)
{
ini(m); count = m + ;
for(int i = ;i <= n;i ++)
{
cin >> num;
front = first = count;
while(num --)
{
cin >> col; U[count] = U[col];
D[count] = col;
L[count] = front;
R[count] = first; D[U[col]] = count;
U[col] = count;
R[front] = count; H[count] = i;
C[count] = col;
front = count;
count ++;
}
L[first] = count - ;
}
if(!dancing())
cout << "NO" << endl;
} return ;
} void ini(int col)
{
U[HEAD] = D[HEAD] = H[HEAD] = C[HEAD] = HEAD;
R[HEAD] = ;
L[HEAD] = col; int front = HEAD;
for(int i = ;i <= col;i ++)
{
U[i] = D[i] = i;
L[i] = front;
R[i] = HEAD;
R[front] = i;
front = i; C[i] = i;
H[i] = ;
}
} bool dancing(int k)
{
int c = R[HEAD];
if(c == HEAD)
{
output();
return true;
} remove(C[c]);
for(int i = D[c];i != c;i = D[i])
{
ANS[k] = H[i];
for(int j = R[i];j != i;j = R[j])
remove(C[j]);
if(dancing(k + ))
return true;
for(int j = L[i];j != i;j = L[j])
resume(C[j]);
}
resume(C[c]); return false;
} void output(void)
{
int i,j;
for(i = ;ANS[i];i ++);
cout << i - << " ";
for(j = ;j < i - ;j ++)
cout << ANS[j] << " ";
cout << ANS[j] << endl;
} void remove(int c)
{
R[L[c]] = R[c];
L[R[c]] = L[c]; for(int i = D[c];i != c;i = D[i])
for(int j = R[i];j != i;j = R[j])
{
D[U[j]] = D[j];
U[D[j]] = U[j];
}
} void resume(int c)
{
R[L[c]] = c;
L[R[c]] = c; for(int i = U[c];i != c;i = U[i])
for(int j = R[i];j != i;j = R[j])
{
D[U[j]] = j;
U[D[j]] = j;
}
}