【bzoj1486】 HNOI2009—最小圈

http://www.lydsy.com/JudgeOnline/problem.php?id=1486 (题目链接)

题意

  给出一张有向图,规定一个数值u表示图中一个环的权值/环中节点个数。求最小的u。

Solution

  尼玛今天考试题,不知道是考二分的话这真的做不出。。 

  二分一个答案${ans}$,这个答案可行当且仅当${ans>=\sum\frac{w}{cnt}}$,${cnt}$表示环中节点个数。移项,${ans*cnt-\sum{w}>=0}$,而${w}$的个数又正好等于${cnt}$,所以最后的式子变成了: $${\sum_{i=1}^{cnt} (ans-w)>=0}$$

  这个式子看着很和谐对吧。没错,只要将边的权值全部减去ans后,dfs版spfa判断图中是否存在负权环即可。

细节

  dfs版SPFA判负环时,枚举起点,并且将dis初值赋为0。

代码

// bzoj1486
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<ctime>
#define LL long long
#define inf 2147483640
#define eps 1e-10
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;
 
const int maxn=3010,maxm=10010;
struct edge {int to,next;double w;}e[maxm<<1];
double dis[maxn];
int vis[maxn],head[maxn],cnt,n,m,flag;

void link(int u,int v,double w) {
	e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].w=w;
}
void SPFA(int x) {
	vis[x]=1;
	if (!flag) return;
	for (int i=head[x];i;i=e[i].next)
		if (dis[e[i].to]>dis[x]+e[i].w) {
			if (vis[e[i].to]) {flag=0;return;}
			dis[e[i].to]=dis[x]+e[i].w;
			SPFA(e[i].to);
		}
	vis[x]=0;
	return;
}
bool check(double mid) {
	flag=1;
	for (int i=1;i<=n;i++) dis[i]=vis[i]=0;
	for (int i=1;i<=cnt;i++) e[i].w-=mid;
	for (int i=1;i<=n;i++) {
		SPFA(i);
		if (!flag) break;
	}
	for (int i=1;i<=cnt;i++) e[i].w+=mid;
	return flag;
}
int main() {
	scanf("%d%d",&n,&m);
	double L=inf,R=0,ans;
	for (int u,v,i=1;i<=m;i++) {
		double w;
		scanf("%d%d%lf",&u,&v,&w);
		link(u,v,w);
		R=max(R,w);L=min(L,w);
	}
	while (L+eps<R) {
		double mid=(L+R)/2;
		if (!check(mid)) R=mid-eps,ans=mid;
		else L=mid+eps;
	}
	printf("%.8lf",ans);
    return 0;
}

  

  

posted @ 2016-09-27 19:58  MashiroSky  阅读(500)  评论(0编辑  收藏  举报