# DAG的最小不相交路径覆盖

//
//  main.cpp
//  POJ1422最小不想交路径覆盖
//
//  Created by beMaster on 16/4/8.
//

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
const int N = 200 + 10;
vector<int> g[N];
int cy[N];
bool vis[N];
bool dfs(int u){
for(int i=0; i<g[u].size(); ++i){
int v = g[u][i];
if(vis[v]) continue;
vis[v] = true;
if(cy[v]==-1 || dfs(cy[v])){
cy[v] = u;
return true;
}
}
return false;
}
int solve(int n){
int ret = 0;
memset(cy, -1, sizeof(cy));
for(int i=1;i<=n;++i){
memset(vis, 0, sizeof(vis));
ret += dfs(i);
}
return n - ret;
}
int main(int argc, const char * argv[]) {
int t,n,m;
int u,v;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
g[i].clear();
for(int i=0;i<m;++i){
scanf("%d%d",&u,&v);
g[u].push_back(v);
}

int ans = solve(n);
printf("%d\n",ans);
}
return 0;
}

# DAG的最小可相交路径覆盖

//
//  main.cpp
//  POJ2594最小可相交路径覆盖
//
//  Created by beMaster on 16/4/8.
//

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
const int N = 500 + 10;
bool dis[N][N];
bool vis[N];
int cy[N];
void floyd(int n){
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
for(int k=1;k<=n;++k)
if(dis[i][k] && dis[k][j])//传递可达性
dis[i][j] = true;
}
bool dfs(int u, int n){
for(int i=1;i<=n;++i){
if(!vis[i] && dis[u][i]){
vis[i] = true;
if(cy[i]==-1 || dfs(cy[i], n)){
cy[i] = u;
return true;
}
}
}
return false;
}
int solve(int n){
int cnt = 0;
memset(cy,-1,sizeof(cy));
for(int i=1;i<=n;++i){
memset(vis,0,sizeof(vis));
cnt += dfs(i, n);
}
return n - cnt;
}
int main(int argc, const char * argv[]) {
int n,m;
int a,b;
while(scanf("%d%d",&n,&m),n+m){
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
dis[i][j] = false;
for(int i=1;i<=m;++i){
scanf("%d%d",&a,&b);
dis[a][b] = true;
}
floyd(n);
int ans = solve(n);
printf("%d\n",ans);
}
return 0;
}


posted @ 2016-04-08 20:50  justPassBy  阅读(12334)  评论(2编辑  收藏  举报