題目大意:
就是N*M的01矩陣, 初始有C(C <= 100)個1, 問從中選出一些橫行是否能使所有列都恰好有一個1
大致思路:
跳舞鏈解決的矩陣精確覆蓋問題, 模板題
模板來自kuangbin大爺Orz
代碼如下:
Result : Accepted Memory : 1916 KB Time : 164 ms
/*
* Author: Gatevin
* Created Time: 2015/10/1 22:09:50
* File Name: Sakura_Chiyo.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;
/*
* Dacing Links
* 舞蹈連算法, 通過四向鏈表加快搜索速度
*/
#define maxnode 100010
#define maxm 1010
#define maxn 1010
/*
* 這個模板解決n*m的01矩陣中選擇一定的row使得每列都只包含一個1
* 初始n*m中1的個數只有C個(C <= 100)
*/
struct DLX
{
int n, m, size;
int U[maxnode], D[maxnode], R[maxnode], L[maxnode], Row[maxnode], Col[maxnode];
//Row[i], Col[i]表示第i個點所在的行和列
int H[maxn], S[maxm];
int ansd, ans[maxn];//ansd表示選擇的row的數量,存儲在ans數組中
void init(int _n, int _m)
{
n = _n;
m = _m;
for(int i = 0; i <= m; i++)//初始化第0橫行(head, C1, C2,..Cm)
{
S[i] = 0;
U[i] = D[i] = i;
L[i] = i - 1;
R[i] = i + 1;
}
R[m] = 0; L[0] = m;
size = m;
for(int i = 1; i <= n; i++) H[i] = -1;
}
void Link(int r, int c)//增加結點(r, c)
{
++S[Col[++size] = c];
Row[size] = r;
D[size] = D[c];
U[D[c]] = size;
U[size] = c;
D[c] = size;
if(H[r] < 0) H[r] = L[size] = R[size] = size;
else
{
R[size] = R[H[r]];
L[R[H[r]]] = size;
L[size] = H[r];
R[H[r]] = size;
}
}
void remove(int c)//(選擇)移除列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)//(取消選擇)恢復列c
{
for(int i = U[c]; i != c; i = U[i])
for(int j = L[i]; j != i; j = L[j])
++S[Col[U[D[j]] = D[U[j]] = j]];
L[R[c]] = R[L[c]] = c;
}
bool Dance(int dep)//dep爲遞歸深度
{
if(R[0] == 0)//每一列都有1了
{
ansd = dep;
return true;
}
int c = R[0];
for(int i = R[0]; i != 0; i = R[i])//現在考慮從還需要1的那些列中選擇對應的行刪除
if(S[i] < S[c])
c = i;//從列中1最少的列處理起
remove(c);//移除列c
for(int i = D[c]; i != c; i = D[i])//以這1列中的第i行做貢獻
{
ans[dep] = Row[i];
for(int j = R[i]; j != i; j = R[j]) remove(Col[j]);
if(Dance(dep + 1)) return true;
for(int j = L[i]; j != i; j = L[j]) resume(Col[j]);
}
resume(c);//還原c
return false;
}
};
DLX dlx;
int main()
{
int n, m;
while(scanf("%d %d", &n, &m) != EOF)
{
dlx.init(n, m);
for(int i = 1; i <= n; i++)
{
int num, j;
scanf("%d", &num);
while(num--)
{
scanf("%d", &j);
dlx.Link(i, j);
}
}
if(!dlx.Dance(0)) printf("NO\n");//沒有解
else
{
printf("%d", dlx.ansd);
for(int i = 0; i < dlx.ansd; i++)
printf(" %d", dlx.ans[i]);
printf("\n");
}
}
return 0;
}