線性規劃與網路流24——最小路徑覆蓋問題
阿新 • • 發佈:2019-01-30
有個結論,最小路徑覆蓋數=點數-最大匹配,
然後需要輸出路徑,,就是通過 matchxy,和matchyx輪流輸出解決
#include<iostream> #include<cstdio> #include<math.h> #include<algorithm> #include<map> #include<set> #include<bitset> #include<stack> #include<queue> #include<string.h> #include<cstring> #include<vector> #include<time.h> #include<stdlib.h> using namespace std; #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3f #define FIN freopen("input.txt","r",stdin) #define mem(x,y) memset(x,y,sizeof(x)) typedef unsigned long long ULL; typedef long long LL; #define MX 2222 #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 typedef pair<pair<int,int>,int> PIII; typedef pair<int,int> PII; int n,m,nx,ny; int head[MX],rear; struct Edge { int to,nxt; } edge[111*MX]; void edge_init() { mem(head,-1); rear=0; } void edge_add(int a,int b) { edge[rear].nxt=head[a]; edge[rear].to=b; head[a]=rear++; } bool vis[MX]; int matchxy[MX],matchyx[MX]; bool hungarian_dfs(int u) { for(int i=head[u]; ~i; i=edge[i].nxt) { int v=edge[i].to; if(vis[v]) continue; vis[v]=1; if(matchyx[v]==-1||hungarian_dfs(matchyx[v])) { matchyx[v]=u; matchxy[u]=v; return 1; } } return 0; } int hungarian() { mem(matchxy,-1); mem(matchyx,-1); int ret=0; for(int i=1; i<=nx; i++) { mem(vis,0); ret+=hungarian_dfs(i); } return ret; } int main() { while(~scanf("%d%d",&n,&m)) { nx=ny=n; edge_init(); for(int i=1; i<=m; i++) { int a,b; scanf("%d%d",&a,&b); edge_add(a,b+n); } int as=n-hungarian(); for(int i=1; i<=n; i++) if(matchxy[i]==-1) { vector<int> ans; ans.push_back(i); int u=i; int v; while((v=matchyx[u+n])!=-1) { ans.push_back(v); u=v; } for(int j=0; j<ans.size(); j++) printf("%d%c",ans[j],j==ans.size()-1?'\n':' '); } printf("%d\n",as); } return 0; }