世界真的很大
这道题还算是比较裸的题了,但是坑点很多
但是主体代码不难写,好在有高人提前指出了坑点,才没有调多久
tarjan敲的越来越熟练了233
看题先:
description:
给一个无向图,求找出一条边,使得删除这条边以后整个图就不连通了,找出满足的边里权值最小的那个,找不到输出-1
input:
There are no more than 12 test cases.
In each test case:
The first line contains two integers, N and M, meaning that there are N islands and M bridges. All the islands are numbered from 1 to N. ( 2 <= N <= 1000, 0 < M <= N2 )
Next M lines describes M bridges. Each line contains three integers U,V and W, meaning that there is a bridge connecting island U and island V, and there are W guards on that bridge. ( U ≠ V and 0 <= W <= 10,000 )
The input ends with N = 0 and M = 0.
output:
For each test case, print the minimum soldier number Zhou Yu had to send to complete the mission. If Zhou Yu couldn’t succeed any way, print -1 instead.
题目还是比较显然了。
求出所有的桥,选择其中边权最小的炸掉
特判如果图本来就不连通,输出0
如果找不到桥,即整个图是一个双连通分量,输出-1
如果找到桥的最小值是0,但是还是需要派一个人去炸桥,输出1
此外再输出答案
完整代码:
#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
const int INF=0x3f3f3f3f;
struct edge
{
int u,v,w,last;
}ed[8000010];
int n,m,num=1,ans=INF,idx=0,flag=0;
int head[200010],dfn[200010],low[200010],fa[200010];
void add(int u,int v,int w)
{
num++;
ed[num].v=v;
ed[num].w=w;
ed[num].last=head[u];
head[u]=num;
}
void tarjan(int u)
{
dfn[u]=low[u]=++idx;
for(int i=head[u];i;i=ed[i].last)
{
int v=ed[i].v;
if(i==(fa[u]^1)) continue ;
if(!dfn[v])
{
fa[v]=i;
tarjan(v);
low[u]=min(low[u],low[v]);
}
else low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u]&&u!=1)
ans=min(ans,ed[fa[u]].w);
}
void init()
{
memset(head,0,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(fa,0,sizeof(fa));
flag=idx=0,num=1,ans=INF;
}
int main()
{
while(1)
{
init();
scanf("%d%d",&n,&m);
if(!n && !m) break ;
for(int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w),add(v,u,w);
}
tarjan(1);
for(int i=1;i<=n;i++)
if(!dfn[i]) flag=1;
if(flag)
{
printf("0\n");
continue ;
}
if(ans==INF) ans=-1;
if(ans==0) ans++;
printf("%d\n",ans);
}
return 0;
}
/*
Whoso pulleth out this sword from this stone and anvil is duly born King of all England
*/
嗯,就是这样