建立二分图,跑一边最大流即可,最后再根据流量路径输出
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 41000;
const int MAXM = 10000010;
const int INF = 0x3f3f3f3f;
//const ll MOD = 998244353;
inline int read(){int ra,fh;char rx;rx=getchar(),ra=0,fh=1;
while((rx<'0'||rx>'9')&&rx!='-')rx=getchar();if(rx=='-')
fh=-1,rx=getchar();while(rx>='0'&&rx<='9')ra*=10,ra+=rx-48,
rx=getchar();return ra*fh;}
struct Edge
{
int from, to, cap, flow, next;
};
Edge edge[MAXM];
int head[MAXN], cur[MAXN], edgenum;
int dist[MAXN];
bool vis[MAXN];
int N, M,ss,tt;
void init()
{
edgenum = 0;
memset(head, -1, sizeof(head));
}
void addEdge(int u, int v, int w)
{
Edge E1 = {u, v, w, 0, head[u]};
edge[edgenum] = E1;
head[u] = edgenum++;
Edge E2 = {v, u, 0, 0, head[v]};
edge[edgenum] = E2;
head[v] = edgenum++;
}
bool BFS(int s, int t)
{
queue<int> Q;
memset(dist, -1, sizeof(dist));
memset(vis, false, sizeof(vis));
dist[s] = 0;
vis[s] = true;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i = head[u]; i != -1; i = edge[i].next)
{
Edge E = edge[i];
if(!vis[E.to] && E.cap > E.flow)
{
dist[E.to] = dist[u] + 1;
if(E.to == t) return true;
vis[E.to] = true;
Q.push(E.to);
}
}
}
return false;
}
int DFS(int x, int a, int t)
{
if(x == t || a == 0) return a;
int flow = 0, f;
for(int &i = cur[x]; i != -1; i = edge[i].next)
{
Edge &E = edge[i];
if(dist[E.to] == dist[x] + 1 && (f = DFS(E.to, min(a, E.cap - E.flow), t)) > 0)
{
edge[i].flow += f;
edge[i^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
}
return flow;
}
int Maxflow(int s, int t)
{
int flow = 0;
while(BFS(s, t))
{
memcpy(cur, head, sizeof(head));
flow += DFS(s, INF, t);
}
return flow;
}
int m,n;
int main()
{
// freopen("data.txt","r",stdin);
ios_base::sync_with_stdio(false);
cin >> m>>n;
init();
int s = 0;
int t = n+1;
for(int i=1;i<=m;i++)
{
addEdge(s,i,1);
}
for(int i=m+1;i<=n;i++)
{
addEdge(i,t,1);
}
int u,v;
while(cin >> u >>v)
{
if(u==-1 && v==-1)
break;
addEdge(u,v,1);
}
int ans =Maxflow(s,t);
if(ans==0)
{
cout <<"No Solution!"<<endl;
continue;
}
cout<< ans<<endl;
for(int k=1;k<=m;k++)
{
for(int i = head[k]; i != -1; i = edge[i].next)
{
if(edge[i].flow==1)
{
cout << k <<" "<<edge[i].to<<endl;
// break;
}
}
}
return 0;
}