您的位置:首页 > 其它

Hihocoder 第三十八周 二分答案

2015-03-23 19:37 330 查看
之前做算法题有做过这种用二分来寻找答案的,原来是一种算法。

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

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

题目: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);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: