Hihocoder 第三十八周 二分答案

之前做算法题有做过这种用二分来寻找答案的,原来是一种算法。

可以找到符合答案的最值。

这个算法关键是确定时间复杂度,即能否使用。然后就是每个答案的判断函数应该怎么写。


题目:http://hihocoder.com/contest/hiho38/problem/1


原本我用的是深搜的,后来发现深搜有个弊端一直改不掉,vis数组标记的话又会造成超时。



比如这种,最大航行次数是2 的话,从1先访问 2 , 再访问 3 , 次数已经到了2 。但是2 , 3 都会被标记。之后1 ,3路径就被忽略了。

如果用vis标记的话,回溯的时候又会超时,大家画个图就可以知道了。


最后还是没办法,逐层搜索就用bfs了,很想看看有没有人把dfs优化好了。

我的代码:

#include<iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <queue>
using namespace std ;
bool ok  ;
struct Road{
	int dest ;
	int ww ;
	Road(int d,int w){
		dest = d , ww = w ;
	}
};

vector<Road> v[20005];
int vis[20005] ;
int n , m , k ,t ;
/*   原来深搜的错误代码 
void dfs(int x,const int& cost,int count)
{
	if(x == t)
	{
		ok = true ;
		return ;
	}
	int len = v[x].size();
	for(int i = 0;i < len;i++)
		if(!vis[v[x][i].dest] && v[x][i].ww <= cost && !ok && count + 1 <= k)
		{
			vis[v[x][i].dest] = 1 ;
			dfs(v[x][i].dest , cost , count + 1) ;	
		}		
}
*/
bool bfs(int cost)
{
	queue<int> q ;
	q.push(1) ;
	vis[1] = 0 ;
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		int len = v[u].size();
		for(int i = 0;i < len;i++)
			if(vis[v[u][i].dest]==-1 && v[u][i].ww <= cost && vis[u] + 1 <= k)
			{
				vis[v[u][i].dest] = vis[u] + 1 ;
				q.push(v[u][i].dest);
			}
	}
	return vis[t] != -1 && vis[t] <= k ;
}
bool check(int cost)
{
	memset(vis , -1 , sizeof(vis));  // 原来是标记有没有找过的,现在作为计数 
	//ok = false ;
	//dfs(1 , cost, 0 ) ;
	//return ok ;
	return bfs(cost) ;
}
int main()
{
	while(~scanf("%d%d%d%d",&n,&m,&k,&t))
	{
		for(int i = 1;i <= n;i++)v[i].clear();
		
		int u ,w, s ,min_ = 2147483647 , max_ = 0;
		for(int i = 0;i < m;i++)
		{
			scanf("%d%d%d",&u,&s,&w);
			v[u].push_back(Road(s, w));
			v[s].push_back(Road(u , w));
			max_ = max(max_ , w);
			min_ = min(min_ , w);
		}
		int l = min_ , r = max_ ;
		while(l < r)
		{
			int mid = (l + r) >> 1 ;
			if(check(mid))r = mid;
			else l = mid + 1 ;
		}
		printf("%d\n",l);
		
	}
} 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值