Hdu 4612 Warm up (双连通分支+树的直径)

时间:2021-12-30 20:31:06

题目链接:

  Hdu 4612 Warm up

题目描述:

  给一个无向连通图,问加上一条边后,桥的数目最少会有几个?

解题思路:

  题目描述很清楚,题目也很裸,就是一眼看穿怎么做的,先求出来双连通分量,然后缩点重新建图,用bfs求树的直径,直径的长度就是减去桥的数目。

这个题目需要手动扩展,而且手动扩展的话要用C++提交,G++re哭了。

 #include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std; const int maxn = ;
struct node
{
int to, next;
}edge[*maxn], Edge[*maxn];
int vis[maxn], dist[maxn];
int head[maxn], low[maxn], dfn[maxn], id[maxn], Head[maxn];
int stack[maxn], tot, Tot, ntime, top, cnt, Max, end_p; void init ()
{
tot = ntime = top = Tot = cnt = Max = end_p = ;
memset (id, , sizeof(id));
memset (low, , sizeof(low));
memset (dfn, , sizeof(dfn));
memset (head, -, sizeof(head));
memset (stack, , sizeof(stack));
memset (Head, -, sizeof(Head));
}
void Add (int from, int to)
{
Edge[Tot].to = to;
Edge[Tot].next = Head[from];
Head[from] = Tot ++;
}
void add (int from, int to)
{
edge[tot].to = to;
edge[tot].next = head[from];
head[from] = tot ++;
}
void Tarjan (int u, int father)
{
int k = ;
low[u] = dfn[u] = ++ntime;
stack[top++] = u;
for (int i=head[u]; i!=-; i=edge[i].next)
{
int v = edge[i].to;
if (v == father && !k)
{
k ++;
continue;
}
if (!dfn[v])
{
Tarjan (v, u);
low[u] = min (low[u], low[v]);
}
else
low[u] = min (low[u], dfn[v]);
}
if (low[u] == dfn[u])
{
cnt ++;
while ()
{
int v = stack[--top];
id[v] = cnt;
if (v == u)
break;
}
}
}
void bfs (int s)
{
queue<int>Q;
int u, v;
memset (vis, ,sizeof(vis));
vis[s] = ;
dist[s] = ;
Q.push(s);
while (!Q.empty())
{
u = Q.front();
Q.pop();
for (int i=Head[u]; i!=-; i=Edge[i].next)
{
v = Edge[i].to;
if (!vis[v])
{
vis[v] = ;
dist[v] = dist[u] + ;
Q.push(v);
if (dist[v] > Max)
{
Max = dist[v];
end_p = v;
}
}
}
}
}
void solve (int n)
{
int sum = ;
Tarjan (, );
for (int i=; i<=n; i++)
for (int j=head[i]; j!=-; j=edge[j].next)
{
int u = id[i];
int v = id[edge[j].to];
if (v != u)
{
Add (u, v);
sum ++;
}
}
sum /= ;
bfs ();
bfs (end_p);
printf ("%d\n", sum - Max);
}
int main ()
{
int n, m;
while (scanf ("%d %d", &n, &m), n+m)
{
init ();
while (m --)
{
int u, v;
scanf ("%d %d", &u, &v);
add (u, v);
add (v, u);
}
solve (n);
}
return ;
}