题意:有N 个点,M条边,加一条边,求割边最少。(有重边)

链接:点我

先求双连通分量,缩点形成一个生成树,然后求这个的直径,割边-直径即是答案

 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
using namespace std; const int MAXN = ;//点数
const int MAXM = ;//边数,因为是无向图,所以这个值要*2 struct Edge
{
int to,next;
bool cut;//是否是桥标记
bool cong;
}edge[MAXM];
int head[MAXN],tot;
int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];//Belong数组的值是1~block
int Index,top;
int block;//边双连通块数
bool Instack[MAXN];
int bridge;//桥的数目 void addedge(int u,int v,bool pp)
{
edge[tot].to = v;edge[tot].next = head[u];edge[tot].cut=false;
edge[tot].cong = pp;
head[u] = tot++;
} void Tarjan(int u,int pre,bool ff)
{
int v;
Low[u] = DFN[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for(int i = head[u];i != -;i = edge[i].next)
{
v = edge[i].to;
if(v == pre && (!ff))continue; //有重边
if( !DFN[v] )
{
Tarjan(v,u,edge[i].cong);
if( Low[u] > Low[v] )Low[u] = Low[v];
if(Low[v] > DFN[u])
{
bridge++;
edge[i].cut = true;
edge[i^].cut = true;
}
}
else if( Instack[v] && Low[u] > DFN[v] )
Low[u] = DFN[v];
}
if(Low[u] == DFN[u])
{
block++;
do
{
v = Stack[--top];
Instack[v] = false;
Belong[v] = block;
}
while( v!=u );
}
}
void init()
{
tot = ;
memset(head,-,sizeof(head));
} int du[MAXN];//缩点后形成树,每个点的度数
vector<int>vec[MAXN];
int dep[MAXN];
void dfs(int u)
{
for(int i = ;i < vec[u].size();i++)
{
int v = vec[u][i];
if(dep[v]!=-)continue;
dep[v]=dep[u]+;
dfs(v);
}
}
void solve(int n)
{
memset(DFN,,sizeof(DFN));
memset(Instack,false,sizeof(Instack));
Index = top = block = ;
Tarjan(,,false);
for(int i = ;i <= block;i++)
vec[i].clear();
for(int i = ;i <= n;i++)
for(int j = head[i];j != -;j = edge[j].next)
if(edge[j].cut)
{
vec[Belong[i]].push_back(Belong[edge[j].to]);
}
memset(dep,-,sizeof(dep));
dep[]=;
dfs();
int k = ;
for(int i = ;i <= block;i++)
if(dep[i]>dep[k])
k = i;
memset(dep,-,sizeof(dep));
dep[k]=;
dfs(k);
int ans = ;
for(int i = ;i <= block;i++)
ans = max(ans,dep[i]);
printf("%d\n",block--ans);
}
struct NN
{
int u,v;
}node[MAXM];
bool cmp(NN a,NN b)
{
if(a.u != b.u)return a.u<b.u;
else return a.v<b.v;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n,m;
int u,v;
while(scanf("%d%d",&n,&m)==)
{
if(n== && m==)break;
init();
for(int i = ;i < m;i++)
{
scanf("%d%d",&u,&v);
if(u==v)continue;
if(u>v)swap(u,v);
node[i].u = u;
node[i].v = v;
}
sort(node,node+m,cmp);
for(int i = ;i < m;i++)
{
if(i == || (node[i].u!=node[i-].u || node[i].v != node[i-].v))
{
if(i < m- && (node[i].u==node[i+].u && node[i].v == node[i+].v)) //标记了是否出现重边
{
addedge(node[i].u,node[i].v,true);
addedge(node[i].v,node[i].u,true);
}
else
{
addedge(node[i].u,node[i].v,false);
addedge(node[i].v,node[i].u,false);
}
}
}
solve(n);
}
return ;
}

2015/7/3

05-11 22:00