您的位置:首页 > 其它

Light OJ 1429 - Assassin`s Creed (II)

2015-12-26 17:05 302 查看
POJ 2594 类似,只不过这里给的是一个有环的图!还有每个人可以走重复的点,任意访问多次都行,只要可达即可。

解法也类似,只不过这里先要缩点,因为同一个强连通分量内的点都相互可达嘛,所以直接缩点就好了!

代码:

#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const int maxn = 1010;

int vis[maxn];
int y[maxn];
vector <int> G[maxn], G2[maxn], G3[maxn];
int n, m;
int a[maxn][maxn];

int pre[maxn];
int low[maxn];
int sccno[maxn];
int dfs_clock;
int scc_cnt;
stack <int> S;

void dfs(int u)
{
pre[u] = low[u] = ++dfs_clock;
S.push(u);
for(int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if(!pre[v])
{
dfs(v);
low[u] = min(low[u], low[v]);
}
else if(!sccno[v])
low[u] = min(low[u], pre[v]);
}
if(pre[u] == low[u])
{
scc_cnt++;
while(1)
{
int x = S.top();
S.pop();
sccno[x] = scc_cnt;
if(x == u)
break;
}
}
}
void find_scc()
{
dfs_clock = scc_cnt = 0;
memset(sccno, 0, sizeof(sccno));
memset(pre, 0, sizeof(pre));
for(int i = 1; i <= n; i++)
if(!pre[i])
dfs(i);
}
void DFS(int now,int u)
{
vis[u] = 1;
for(int i = 0;i < G2[u].size();i ++){
int v = G2[u][i];
if(!vis[v]) {
G[now].push_back(v);
DFS(now, v);
}
}
}
bool dfs2(int u)
{
for(int i = 0; i < G3[u].size(); i++)
{
int v = G3[u][i];
if(vis[v])
continue;
vis[v] = true;
if(y[v] == -1 || dfs2(y[v]))
{
y[v] = u;
return true;
}
}
return false;
}
int hungary()
{
int ans = 0;
memset(y, -1, sizeof(y));
for(int i = 1; i <= scc_cnt; i++)
{
memset(vis, 0, sizeof(vis));
if(dfs2(i)) ans++;
}
return ans;
}

int main()
{
int T, ca = 0;
scanf("%d", &T);
while(T--)
{
scanf("%d %d", &n, &m);
for(int i = 0; i <= n; i++)
G[i].clear(), G2[i].clear(), G3[i].clear();
while(m--)
{
int u, v;
scanf("%d %d", &u, &v);
G2[u].push_back(v);
}
for(int i = 1; i <= n; i++){
memset(vis, 0, sizeof(vis));
DFS(i,i);
}

find_scc();
for(int u = 1; u <= n; u++)
{
for(int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if(sccno[u] != sccno[v])
G3[sccno[u]].push_back(sccno[v]);
}
}
printf("Case %d: %d\n", ++ca, scc_cnt - hungary());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 图论