分数规划(Bzoj1486: [HNOI2009]最小圈)

题面

传送门

分数规划

分数规划有什么用?
可以把带分数的最优性求解式化成不带除发的运算
假设求max{\(\frac{a}{b},b>0\)}
二分一个权值\(k\)
\(\frac{a}{b}\le k\)那么\(a-k*b\le 0\)
如果得出来\(a-k*b\)的最大值大于\(0\),那么\(k\)可以变大
否则缩小\(k\)

Sol

分数规划,然后求解负环即可

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;

IL int Input(){
	RG int x = 0, z = 1; RG char c = getchar();
	for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
	for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
	return x * z;
}

const int maxn(3005);
const int maxm(1e4 + 5);
const double eps(1e-9);

int n, m, first[maxn], cnt, vis[maxn];
double dis[maxn], l = 1e7, r = -1e7;

struct Edge{
	int to, next;
	double w;
} edge[maxm];

IL void Add(RG int u, RG int v, RG double w){
	edge[cnt] = (Edge){v, first[u], w}, first[u] = cnt++;
}

IL int Dfs(RG int u, RG double w){
	vis[u] = 1;
	for(RG int e = first[u]; e != -1; e = edge[e].next){
		RG int v = edge[e].to;
		RG double d = dis[u] + edge[e].w - w;
		if(dis[v] - d >= eps){
			dis[v] = d;
			if(vis[v] || Dfs(v, w)) return 1;
		}
	}
	vis[u] = 0;
	return 0;
}

IL int Check(RG double v){
	for(RG int i = 1; i <= n; ++i) dis[i] = 0, vis[i] = 0;
	for(RG int i = 1; i <= n; ++i) if(Dfs(i, v)) return 1;
	return 0;
}

int main(){
	n = Input(), m = Input();
	for(RG int i = 1; i <= n; ++i) first[i] = -1;
	for(RG int i = 1; i <= m; ++i){
		RG int u = Input(), v = Input(), w = Input();
		Add(u, v, w), l = min(l, -1.0 * abs(w)), r = max(r, 1.0 * abs(w));
	}
	while(r - l >= eps){
		RG double mid = (l + r) / 2.0;
		if(Check(mid)) r = mid;
		else l = mid;
	}
	printf("%.8lf\n", r);
	return 0;
}
posted @ 2018-05-30 22:05  Cyhlnj  阅读(152)  评论(0编辑  收藏  举报