Caocao's Bridges
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3992 Accepted Submission(s): 1250
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 <= N 2 )
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.
题目链接:HDU 4738
题目不难但有三个坑点:1、两点之间可能有重边;2、初始状态的图已经不是连通的了;3、某个桥就算没人守也至少派要一个人去炸桥
这题的重边可以有两种处理方式,很容易想到简单方法就是多用一个邻接矩阵来记录两点之间守卫人数,在加边的时候就把重边判断掉使其权值变成INF,这样就算有桥也是拿INF这个权值去更新答案
第二种就是给每一条边一个id,然后判断是否往回走就不是用v==pre而是id==E[i].id,这样一来若有重边则肯定存在另外至少一个不同id的边可以进行dfs把pre(指向u的后向边)的low更新掉,导致low[v]不会大于dfn[u],就构不成桥的条件了,解决了重边的问题。
例如这样的数据
2 2
1 2 2
1 2 2
首先是dfs从1->2,把1的dfn更新,发现2没访问过,开始从2递归即2->1,遍历发现2->1这条边和1->2这走过来的边id一样,continue,又发现一条2->1的但id不一样的,但是此时的dfn[1]已经有值且1在stack中,则$low[2]=min(low[2],dfn[1])=1$,此时$low[2]$便不会大于$dfn[1]$
感觉第二种方法比较好用且适用性好,学习一个
代码:
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define CLR(x,y) memset(x,y,sizeof(x))
#define LC(x) (x<<1)
#define RC(x) ((x<<1)+1)
#define MID(x,y) ((x+y)>>1)
typedef pair<int,int> pii;
typedef long long LL;
const double PI=acos(-1.0);
const int N=1007;
struct edge
{
int to;
int pre;
int id;
int w;
};
edge E[N*N];
int head[N],tot;
//int soldier[N][N];//第一种方法所需的的邻接矩阵
int low[N],dfn[N],ts,top,st[N],ins[N];
int least;
void init()
{
CLR(head,-1);
tot=0;
//CLR(soldier,INF);
CLR(low,0);
CLR(dfn,0);
ts=top=0;
CLR(ins,0);
least=INF;
}
inline void add(int s,int t,int w,int id)
{
E[tot].to=t;
E[tot].id=id;
E[tot].w=w;
E[tot].pre=head[s];
head[s]=tot++;
}
void Tarjan(int u,int id)
{
low[u]=dfn[u]=++ts;
ins[u]=1;
st[top++]=u;
int v;
for (int i=head[u]; ~i; i=E[i].pre)
{
v=E[i].to;
if(id==E[i].id)
continue;
if(!dfn[v])
{
Tarjan(v,E[i].id);
low[u]=min<int>(low[v],low[u]);
if(low[v]>dfn[u])
{
int need=E[i].w;
if(need<least)
least=need;
}
}
else if(ins[v])
low[u]=min<int>(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
do
{
v=st[--top];
ins[v]=0;
}while (u!=v);
}
}
int main(void)
{
int n,m,a,b,w,i;
while (~scanf("%d%d",&n,&m)&&(n||m))
{
init();
for (i=0; i<m; ++i)
{
scanf("%d%d%d",&a,&b,&w);
add(a,b,w,i);
add(b,a,w,i);
}
int k=0;
for (i=1; i<=n; ++i)
{
if(!dfn[i])
{
Tarjan(i,-1);
++k;
}
}
if(k>1)//连通图数量
least=0;
else if(least==0)//至少派一个人去
least=1;
else if(least==INF)//
least=-1;
printf("%d\n",least);
}
return 0;
}