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 130 131
| import java.io.*; import java.util.*; public class Main {
public static void main(String[] args) { FastScanner sc=new FastScanner(); PrintWriter pw=new PrintWriter(System.out); DancingLinks dl=new DancingLinks(); while(sc.hasNext()){ int n=sc.nextInt(); int m=sc.nextInt(); dl.init(n, m); for(int i=1;i<=n;i++){ int k=sc.nextInt(); for(int o=1;o<=k;o++){ int j=sc.nextInt(); dl.link(i, j); } } boolean judge=dl.dance(0); if(!judge){ pw.println("NO"); }else{ pw.print(dl.ansd); for(int i=0;i<dl.ansd;i++){ pw.print(" "+dl.ans[i]); } pw.println(); } pw.flush(); }
}
} class DancingLinks{ int n,m,size; int maxn=100100; int[]U,D,R,L,Row,Col; int[]H; int[]S; int ansd; int[]ans; DancingLinks(){ U=new int[maxn]; D=new int[maxn]; R=new int[maxn]; L=new int[maxn]; Row=new int[maxn]; Col=new int[maxn]; H=new int[maxn]; S=new int[maxn]; ans=new int[maxn]; } void init(int n,int m){ this.n=n; this.m=m; for(int i=0;i<=m;i++){ 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){ ++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){ 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]) ++S[Col[U[D[j]]=D[U[j]]=j]]; L[R[c]]=R[L[c]]=c; } boolean dance(int d){ if(R[0]==0){ ansd=d; return true; } int c=R[0]; for(int i=R[0];i!=0;i=R[i]) if(S[i]<S[c]) c=i; remove(c); for(int i=D[c];i!=c;i=D[i]){ ans[d]=Row[i]; for(int j=R[i];j!=i;j=R[j]) remove(Col[j]); if(dance(d+1)) return true; for(int j=L[i];j!=i;j=L[j]) resume(Col[j]); } resume(c); return false; } }
|