二分割検索http://ac.jobdu.com/problem.php?pid=1545

2619 ワード

#include
#include
#include
#include
#include
#include
#include
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 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 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
"); 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
", 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; } } */
 
転載先:https://www.cnblogs.com/forgood/p/3360196.html