二分法+BFS(or DFS)

来源:互联网 发布:设计ui的软件 编辑:程序博客网 时间:2024/05/23 23:47

一道里例题:此题,本来是用DFS的,但出现超时。改为BFS后,AC了~


原题地址:点击打开链接

题目1545:奇怪的连通图
时间限制:1 秒内存限制:128 兆特殊判题:否
题目描述:
已知一个无向带权图,求最小整数k。使仅使用权值小于等于k的边,节点1可以与节点n连通。
输入:
输入包含多组测试用例,每组测试用例的开头为一个整数n(1 <= n <= 10000),m(1 <= m <= 100000),代表该带权图的顶点个数,和边的个数。
接下去m行,描述图上边的信息,包括三个整数,a(1 <= a <= n),b(1 <= b <= n),c(1 <= c <= 1000000),表示连接顶点a和顶点b的无向边,其权值为c。
输出:
输出为一个整数k,若找不到一个整数满足条件,则输出-1。
样例输入:
3 3
1 3 5
1 2 3
2 3 2
3 2
1 2 3
2 3 5
3 1
1 2 3 
样例输出:
3
5
-1

#include <cstdio>#include <cstring>#include <queue>using namespace std;const int SIZE=10001;const int INF=0x7fffffff;int n, m;typedef struct node{    int to;    int w;    struct node * nptr;}node;int vis[SIZE];node * h[SIZE];/*bool dfs(int u0, int k){    if(u0==n) return true;    else    {        node * ptr=h[u0];        while(ptr)        {            if(!vis[ptr->to] && ptr->w<=k)            {                vis[ptr->to]=1;                if(dfs(ptr->to,k)) return true;                vis[ptr->to]=0;            }            ptr=ptr->nptr;        }        return false;    }}*/bool bfs(int k){    queue<int> Q;    int u;    node * ptr;    Q.push(1);    while(!Q.empty())    {        u=Q.front(); Q.pop();        ptr=h[u];        while(ptr)        {            if(!vis[ptr->to] && ptr->w<=k)            {                vis[ptr->to]=1;                if(ptr->to==n) return true;                Q.push(ptr->to);            }            ptr=ptr->nptr;        }    }    return false;}int bin_search(int low, int high){    int mid;    while(low<=high)    {        mid=(low+high)/2;        memset(vis,0,sizeof(vis));        vis[1]=1;        //if(dfs(1,mid))        if(bfs(mid))        {            if(low==high) return low;            else high=mid;        }        else        {            if(low==high) return -1;            else low=mid+1;        }    }}int main(){    int u,v,w,k;    int low,high;    node * ptr;    while(scanf("%d %d",&n,&m)!=EOF)    {        memset(h,0,sizeof(h));        low=INF; high=-1;        for(int i=0;i<m;i++)        {            scanf("%d %d %d",&u,&v,&w);            ptr=new node;            ptr->to=v; ptr->w=w;            ptr->nptr=h[u]; h[u]=ptr;            ptr=new node;            ptr->to=u; ptr->w=w;            ptr->nptr=h[v]; h[v]=ptr;            if(low>w) low=w;            if(high<w) high=w;        }        printf("%d\n",bin_search(low,high));    }    return 0;}