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 132 133 134 135
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<climits> #include<vector> #include<cstdio> #include<cmath> #include<queue> using namespace std;
inline const int Get_Int() { int num=0,bj=1; char x=getchar(); while(x<'0'||x>'9') { if(x=='-')bj=-1; x=getchar(); } while(x>='0'&&x<='9') { num=num*10+x-'0'; x=getchar(); } return num*bj; }
const int maxn=605;
int n1,n2,N,m,father[maxn],vst[maxn],match[maxn],pre[maxn],Type[maxn]; vector<int>edges[maxn]; queue<int>Q;
void AddEdge(int x,int y) { edges[x].push_back(y); edges[y].push_back(x); }
int LCA(int x,int y) { static int times=0; times++; x=father[x],y=father[y]; while(vst[x]!=times) { if(x) { vst[x]=times; x=father[pre[match[x]]]; } swap(x,y); } return x; }
void blossom(int x,int y,int lca) { while(father[x]!=lca) { pre[x]=y; y=match[x]; if(Type[y]==1) { Type[y]=0; Q.push(y); } father[x]=father[y]=father[lca]; x=pre[y]; } }
int Augument(int s) { for(int i=1; i<=N; i++)father[i]=i; memset(Type,-1,sizeof(Type)); Q=queue<int>(); Type[s]=0; Q.push(s); while(!Q.empty()) { int Now=Q.front(); Q.pop(); for(int Next:edges[Now]) { if(Type[Next]==-1) { pre[Next]=Now; Type[Next]=1; if(!match[Next]) { for(int to=Next,from=Now; to; from=pre[to]) { match[to]=from; swap(match[from],to); } return true; } Type[match[Next]]=0; Q.push(match[Next]); } else if(Type[Next]==0&&father[Now]!=father[Next]) { int lca=LCA(Now,Next); blossom(Now,Next,lca); blossom(Next,Now,lca); } } } return false; }
int t,ans=0;
int id(int x,int y) { return (y-1)*n2+x; }
void Clear() { for(int i=1; i<=N; i++)edges[i].clear(); memset(match,0,sizeof(match)); ans=0; }
int main() { t=Get_Int(); while(t--) { Clear(); n1=Get_Int(); n2=Get_Int(); m=Get_Int(); for(int i=1; i<=m; i++) { int x=Get_Int()+3*n2,y=Get_Int(); AddEdge(x,id(y,1)); AddEdge(x,id(y,2)); AddEdge(x,id(y,3)); } for(int i=1; i<=n2; i++) { AddEdge(id(i,1),id(i,2)); AddEdge(id(i,2),id(i,3)); AddEdge(id(i,1),id(i,3)); } N=n1+3*n2; for(int i=N; i>=1; i--) if(!match[i])ans+=Augument(i); printf("%d\n",ans-n1); for(int i=3*n2+1; i<=N; i++)printf("%d ",match[i]%n2==0?n2:match[i]%n2); putchar('\n'); } return 0; }
|