二分法+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;}
- 二分法+BFS(or DFS)
- TOJ3100 BFS or DFS
- hdu 1074 dfs or bfs
- hdu 1241 bfs or dfs
- hdu2614 Beat BFS or DFS
- hdu 4394 - Digital Square (dfs or bfs)
- UVA 439 Knight Moves --DFS or BFS
- POJ 1979--DFS or BFS(水)
- Red and Black(BFS or DFS)
- Hdu1242(bfs+优先队列or dfs)
- HDU 1242 Rescue(DFS or BFS)
- 1091. Acute Stroke (30) BFS or DFS
- POJ 2386 Lake Counting (DFS or BFS)
- POJ 2386 Lake Counting(dfs or bfs)
- HDU 1242 Rescue (BFS or DFS)
- HDU1241 Oil Deposits(dfs or bfs)
- hdu 6165(dfs or bfs or tarjan+topsort)
- UVA 439 Knight Moves 走象棋 (DFS or BFS)
- KVM虚拟机代码揭秘——QEMU代码结构分析
- minicom 自动重复发送数据的实现
- 基于Visual C++2013拆解世界五百强面试题--题3-打印螺旋数组
- SVN 与 JIRA (参考链接)
- OC——委托模式
- 二分法+BFS(or DFS)
- 映射 SQL 和 Java 类型
- BloomFilter--大规模数据处理利器
- 精准营销
- 利用python修改mp3的标签
- 为KVM虚拟机配置虚拟网桥 (英语)
- sleep和wait的区别
- BloomFilter
- 正确决解Hibernate4.*中:Connection cannot be null when 'hibernate.dialect' not set