题目大意:曹操建了一个作战系统,有N个岛,M座桥,如果任意两个岛能通过若干座桥相连,则作战优势很大,每座桥上有K个士兵把守,周瑜有一个炸药包,必须派不少于K个士兵去攻击,问他至少要派多少个士兵。
题解:就是求无向图的最小桥,但要注意当K=0的时候周瑜还是要派一个人去运炸药。还有就是当图本来就不连通,那么就不用派兵过去了(这里可以用并查集)。还有就是重边不会影响算法,因为只要找最小的那一条~~
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>
#define oo 2147483640
using namespace std;
struct node
{
int x,y,next,w,id;
}edge[2000010];
int h[2000010],p,n,m,tag[1000010];
int father[1010],Nodeid,low[1010],dfn[1010];
void Init(int x,int y,int w,int id)
{
edge[p].x=x;
edge[p].y=y;
edge[p].w=w;
edge[p].id=id;
edge[p].next=h[x];
h[x]=p++;
}
int search(int x)
{
if (father[x]==x) return x;
int tx=search(father[x]);
father[x]=tx;
return tx;
}
void connect(int x,int y)
{
int tx,ty;
tx=search(x);
ty=search(y);
if (tx<ty)
father[ty]=tx;
else father[tx]=ty;
}
void tarjan(int x,int id)
{
int y,i;
dfn[x]=low[x]=++Nodeid;
for (i=h[x];i;i=edge[i].next)
{
if (id==edge[i].id) continue;
y=edge[i].y;
if (!dfn[y])
{
tarjan(y,edge[i].id);
low[x]=low[x]<low[y]?low[x]:low[y];
if (dfn[x]<low[y]) tag[i]=1;
}
else low[x]=low[x]<dfn[y]?low[x]:dfn[y];
}
return ;
}
int main()
{
int i,j,k,ans,w;
while (scanf("%d%d",&n,&m)&&n&&m)
{
memset(tag,0,sizeof(tag));
memset(h,0,sizeof(h));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
p=1;
for (i=1;i<=n;i++) father[i]=i;
for (i=1;i<=m;i++)
{
scanf("%d%d%d",&j,&k,&w);
Init(j,k,w,i);
Init(k,j,w,i);
connect(j,k);
}
for (i=2;i<=n;i++)
if (search(i)!=search(1)) break;
if (i<=n)
{
printf("0\n");
continue;
}
Nodeid=0;
tarjan(1,0);
ans=oo;
for (i=1;i<=p;i++)
if (tag[i])
ans=ans>edge[i].w?edge[i].w:ans;
if (ans==oo) printf("-1\n");
else printf("%d\n",ans==0?1:ans);
}
return 0;
}
/*
6 7
1 2 1
1 3 2
2 3 3
2 4 4
4 5 5
4 6 6
5 6 7
*/