您的位置:首页 > 其它

POJ 3740 Easy Finding

2015-04-23 22:42 411 查看
题目链接:http://poj.org/problem?id=3740

dancing links 入门题

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <iomanip>
using namespace std;
int M, N;
#define maxn 16*300+5
int R[maxn], L[maxn], U[maxn], D[maxn];
int H[maxn], C[maxn], ans[20], colsum[300+5];
int mp[18][310];
int cnt, head;
void addnode(int row, int col, int sum, int pre, int rowhead){
cnt++;
H[cnt] = row;
C[cnt] = col;

if(pre == -1){
R[cnt] = cnt; L[cnt] = cnt;
}
else if(sum == 2){
R[pre] = cnt; R[cnt] = pre;
L[pre] = cnt; L[cnt] = pre;
}
else{
R[cnt] = rowhead; R[pre] = cnt;
L[cnt] = pre; L[rowhead] = cnt;
}

D[U[col]] = cnt;
U[cnt] = U[col];
D[cnt] = col;
U[col] = cnt;

colsum[col]++;
}
void init(){
cnt = 0; head = 0;
memset(colsum, 0, sizeof(colsum));
L[head] = N; R[head] = 1; D[head] = head; U[head] = head;
for(int i = 1; i <= N; i++){
cnt++;
H[cnt] = 0; C[cnt] = i;
U[cnt] = cnt; D[cnt] = cnt;
if(i == N){
R[cnt-1] = cnt;
L[cnt] = cnt-1;
R[cnt] = head;
}
else{
R[cnt-1] = cnt;
L[cnt] = cnt-1;
}
}
int temp;
for(int i = 1; i <= M; i++){
int sum = 0, pre = -1, rowhead;
for(int j = 1; j <= N; j++){
scanf("%d", &temp);
if(temp == 1){
sum++;
addnode(i, j, sum, pre, rowhead);
if(sum == 1) rowhead = cnt;
pre = cnt;
}
}
}
}
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]){
U[D[j]] = U[j];
D[U[j]] = D[j];
colsum[C[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]){
U[D[j]] = j;
D[U[j]] = j;
colsum[C[j]]++;
}
}
}
bool dance(int k){
int c = R[head];
if(c == head){
return true;
}
int min = 999999;
for(int i = R[head]; i != head; i = R[i]){
if(colsum[i] <= min){
min = colsum[i];
c = i;
}
}
remove(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(dance(k+1)) return true;
for(int j = L[i]; j != i; j = L[j]) resume(C[j]);
}
resume(c);
return false;
}

int main(){
while(~scanf("%d%d", &M, &N)){
init();
if(dance(0)) printf("Yes, I found it\n");
else printf("It is impossible\n");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: