【bzoj1486】 HNOI2009—最小圈

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

題意:給出一張有向圖,規定一個數值u表示圖中一個環的權值/環中節點個數。求最小的u。

Solution
  尼瑪今天考試題,不知道是考二分的話這真的做不出。。
  二分一個答案ans,這個答案可行當且僅當ans>=∑w/cnt,cnt表示環中節點個數。移項,ans*cnt-∑w>=0,而w的個數又正好等於cnt,所以最後的式子變成了:
  

i=0n(answ)>=0

  這個式子看着很和諧對吧。沒錯,只要將邊的權值全部減去ans後,spfa判斷圖中是否存在負權環即可。

代碼:

// bzoj1486
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#define LL long long
#define inf 2147483640
#define eps 0.000000001
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;
inline LL getint() {
    int f,x=0;char ch=getchar();
    while (ch<='0' || ch>'9') {if (ch=='-') f=-1;else f=1;ch=getchar();}
    while (ch>='0' && ch<='9') {x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

const int maxn=3010,maxm=10010;
struct edge {int to,next;double w;}e[maxm<<1];
double dis[maxn];
int vis[maxn],head[maxn],cnts[maxn],cnt,n,m;

void link(int u,int v,double w) {
    e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].w=w;
}
bool SPFA() {
    queue<int> q;
    for (int i=1;i<=n;i++) {
        dis[i]=0;
        q.push(i);
        vis[i]=1;
        cnts[i]=0;
    }
    dis[1]=0;
    while (q.size()) {
        int x=q.front();
        vis[x]=0;q.pop();
        for (int i=head[x];i;i=e[i].next)
            if (dis[e[i].to]>dis[x]+e[i].w) {
                dis[e[i].to]=dis[x]+e[i].w;
                if (!vis[e[i].to]) {
                    if (++cnts[e[i].to]>30) return 0;
                    q.push(e[i].to);
                    vis[e[i].to]=1;
                }
            }
    }
    return 1;
}
bool ck(double mid) {
    bool flag=1;
    for (int i=1;i<=cnt;i++) e[i].w-=mid;
    if (SPFA()) flag=0;
    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 (ck(mid)) R=mid,ans=mid;
        else L=mid;
    }
    printf("%.8lf",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章