您的位置:首页 > 理论基础 > 计算机网络

二分查找 http://ac.jobdu.com/problem.php?pid=1545

2013-10-09 21:44 567 查看
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;

const int MaxInt = 0x7fffffff;
const int Max = 100010;

struct Node
{
int next;
int value;
bool flag;
Node():next(0), value(0), flag(false) { }
Node(int nxt, int val): next(nxt), value(val), flag(false) { }
};
vector<Node> pLink[10001];
bool visited[10001];
int cost[Max];

int maxValue;

void setVector(int n)
{
for (int i = 1; i <= n; ++i)
pLink[i].clear();
}

bool bfs(int bgn, int end, int limt)
{
memset(visited, 0, sizeof(visited) / sizeof(bool));
queue<int> Q;
Q.push(bgn);
visited[bgn] = true;
while (!Q.empty())
{
int u = Q.front();
Q.pop();
for (int i = 0; i < pLink[u].size(); ++i)
{
int v = pLink[u][i].next;
int val = pLink[u][i].value;
if (visited[v] || val > limt) continue;
if (v == end) return true;
visited[v] = true;
Q.push(v);
}
}

return false;
}

int main()
{

//freopen("in.txt", "r", stdin);
int n, m, a, b, c;
while (scanf("%d %d", &n, &m) != EOF)
{
setVector(n);
int cnt = 0;
while (m--)
{
scanf("%d %d %d", &a, &b, &c);
pLink[a].push_back(Node(b, c));
pLink[b].push_back(Node(a, c));
cost[cnt++] = c;
}
if (n == 1)
{
printf("0\n");
continue;
}
sort(cost, cost + cnt);
int *end = unique(cost, cost + cnt);
int ans = -1;
int L = 0;
int R = end - cost - 1;
while (L <= R)
{
int mid = (L + R)>>1;
if (bfs(1, n, cost[mid]))
{
ans = cost[mid];
R = mid - 1;
}
else
{
L = mid + 1;
}
}
printf("%d\n", ans);
}

return 0;
}

/* 超时算法
void dfs(int u, int cost, int n)
{
if (u == n)
{
if (cost < maxValue)
{
maxValue = cost;
}
return ;
}
for (int i = 0; i < pLink[u].size(); ++i)
{
int v = pLink[u][i].next;
int value = pLink[u][i].value;
if(pLink[u][i].flag == true || value >= maxValue) continue;
pLink[u][i].flag = true;
int tmpCost = cost;
if (value > tmpCost) tmpCost = value;
dfs(v, tmpCost, n);
pLink[u][i].flag = false;
}
}
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: