POJ - 2949 Word Rings(SPFA判正环,01分数规划)

http://poj.org/problem?id=2949

在这里插入图片描述

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;

typedef pair<int,int> PII;
const int N = 703;
vector<PII> g[N];
double dist[N];
int cnt[N];
bool st[N];

bool check(double mid)
{
	memset(cnt,0,sizeof cnt);
	memset(st,false,sizeof st);
	queue<int>q;
	for (int i=0;i<=702;i++)
	{
		q.push(i); //先将所有点加进队列
		st[i]=true;
	}
	int cntt=0;
	while(!q.empty())
	{
		int t=q.front();q.pop();
		st[t]=false;
		for(int i=0;i<(int)g[t].size();i++)
		{
			int j=g[t][i].first, w=g[t][i].second;
			if(dist[j]<dist[t]+w-mid)
			{
				dist[j]=dist[t]+w-mid;
				cnt[j]=cnt[t]+1;
				if(++cntt>10001) return true; //进行过松弛操作的点的数量
				if(cnt[j]>=N) return true; //存在正环
				if(!st[j])
				{
					st[j]=true;
					q.push(j);
				}
			}
		}
	}
	return false; //没有正环
}

int main()
{
	int n;
	while(scanf("%d",&n),n)
	{
		for(int i=0;i<=702;i++) g[i].clear();
		for(int i=1;i<=n;i++)
		{
			char s[1010];scanf("%s",s);
			int len=strlen(s);
			if(len>=2)
			{
				int c1=(s[0]-'a')*26+(s[1]-'a');
				int c2=(s[len-2]-'a')*26+(s[len-1]-'a');
				g[c1].push_back((PII){c2,len});
			}
		}
		if(!check(0)) puts("No solution.");
		else
		{
            double l=0.0,r=1000.0;
            while(r-l>1e-4)
            {
                double mid=(l+r)/2;
                if(check(mid)) l=mid;
                else r=mid;
            }
            printf("%.2f\n",r);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wa_Automata

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值