BFS广度优先搜索
框架就不给了,因为主要是一种思想。
BFS队列把一层跑完放进去,再跑第二层,直到最后一层。
一道简单的题目:
洛谷:字符变换(虽然看了题解才过了)
就是暴力枚举每一个可以替换的地方,BFS遇到第一个满足条件的就退出一定是最短路径,最少步数。
https://www.luogu.org/problemnew/show/P1032
#include<iostream>
#include<cstring>
#include<cstdio>
#include<map>
#include<queue>
using namespace std;
struct node
{
int step;
string str;
};
string st,ed;
string S[100];
string T[100];
int n,ans;
map<string,int>M;
string translate(const string &str,int i,int j)
{
string ans = "";
if(i+S[j].length()>str.length())
return ans;
for(int k=0;k<S[j].length();k++)
{
if(str[i+k]!=S[j][k])return ans;
}
ans = str.substr(0,i);
ans+=T[j];
ans+=str.substr(i+S[j].length());
return ans;
}
void BFS()
{
queue<node>q;
node s;
s.str=st;
s.step=0;
q.push(s);
while(!q.empty())
{
node u=q.front();
q.pop();
string temp;
if(M[u.str])continue;
if(u.str==ed)
{
ans=u.step;
break;
}
M[u.str]=1;
for(int i=0;i<u.str.length();i++)
for(int j=0;j<n;j++)
{
temp=translate(u.str,i,j);
if(temp!="")
{
node v;
v.str=temp;
v.step=u.step+1;
q.push(v);
}
}
}
if(ans>10||ans==0)
{
cout<<"NO ANSWER!"<<endl;
}
else cout<<ans<<endl;
}
int main()
{
cin>>st>>ed;
n=0;
while(cin>>S[n]>>T[n])
n++;
BFS();
}
Dijistra算法
借鉴https://blog.youkuaiyun.com/summer__show_/article/details/72902899
https://blog.youkuaiyun.com/u010372095/article/details/47378403
Dijistra算法是一种贪心的算法,它把点分成两组,一组A是已经求出最短路径的,一组B是还未求出的。
从源点开始,选取距A组最近的点,加入A组,然后对B组中的点更新距源点的最近距离(每个点都有个这样的距离值,更新到最后加入了A组就是最短路径),PS:一开始比较远的点都是+00,因为还没更新到中间点。
更新的操作又叫做松弛操作。
但是贪心的缘故,所以不能有负权,因为可能后面的负边加上会小于原来的距离
比如负权圈,无限转无限小。
板题:
Flowery Trails |
Time Limit: 50000ms, Special Time Limit:125000ms, Memory Limit:65536KB |
Total submit users: 23, Accepted users: 21 |
Problem 13375 : No special judgement |
Problem description |
|
Input |
The first line of the input has two integers: P and T. P is the number of points of interest and T is the number of trails. Points are identified by integers, ranging from 0 to P-1. The entrance point is 0 and the highest peak is point P-1. |
Output |
The output has a single line with the extent of flowers (in metres) needed to cover both sides of the popular trails. |
Sample Input |
|
Sample Output |
|
#include<queue>
#include<vector>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
const int maxn=10000+5;
struct Edge
{
int from,to,dist;
Edge(){}
Edge(int u,int v,int d):from(u),to(v),dist(d){}
};
struct HeapNode
{
int d,u;
HeapNode(int x,int y):d(x),u(y){}
bool operator <(const HeapNode& rhs)const
{return d>rhs.d;}
};
struct Dijkstra
{
int n,m;
vector<Edge>edges;
vector<int>G[maxn];
bool done[maxn];
int d[maxn];
int p[maxn];
void init(int n)
{
this->n=n;
for(int i=0;i<n;i++)
G[i].clear();
edges.clear();
}
void AddEdges(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
m=edges.size();
G[from].push_back((m-1));//这样G就代表了起点开始的所有边在edge数组中的编号,厉害!
}
void dijkstra(int s)
{
priority_queue<HeapNode> Q;
for(int i=0;i<n;i++)
d[i]=INF;
d[s]=0;
memset(done,0,sizeof(done));
Q.push(HeapNode(0,s));
while(!Q.empty())
{
HeapNode x=Q.top();
Q.pop();
int u=x.u;
if(done[u])continue;
done[u]=true;
for(int i=0;i<G[u].size();i++)
{
Edge& e=edges[G[u][i]];
if(d[e.to]>d[u]+e.dist)
{
d[e.to]=d[u]+e.dist;//松弛操作
p[e.to]=e.from;//用于记录终点的起点边(最小路径上的)
Q.push(HeapNode(d[e.to],e.to));//优先队列存储点和源点到点的距离
}
}
}
}
}t[2];
int n,m;
Edge a[250050];
int main()
{
while(~scanf("%d%d",&n,&m))
{
t[0].init(n);
t[1].init(n);
for(int i=1;i<=m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
t[0].AddEdges(u,v,w);
t[0].AddEdges(v,u,w);
t[1].AddEdges(u,v,w);
t[1].AddEdges(v,u,w);
a[i].from=u,a[i].to=v,a[i].dist=w;
}
t[0].dijkstra(0);
t[1].dijkstra(n-1);
LL value=t[0].d[n-1];
LL ans=0;
for(int i=1;i<=m;i++)
{
int u=a[i].from,v=a[i].to,w=a[i].dist;
if(t[0].d[u]+t[1].d[v]+w==value||t[0].d[v]+t[1].d[u]+w==value)
ans+=w;
}
printf("%I64d\n",ans*2);
}
}
接下来的代码是
邻接表的优化,与本题无关(代码是借用某位大神的但是是以前找的了现在找不到作者,希望作者看见之后能够告诉我,我把地址补上)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
#define maxn 10010 //最大顶点个数
int n; //顶点个数
struct arcnode //边结点
{
int vertex; //与表头结点相邻的顶点编号
int weight; //连接两顶点的边的权值
arcnode * next; //指向下一相邻接点
arcnode() {}
arcnode(int v,int w):vertex(v),weight(w),next(NULL) {}
};
struct vernode //顶点结点,为每一条邻接表的表头结点
{
int vex; //当前定点编号
arcnode * firarc; //与该顶点相连的第一个顶点组成的边
}Ver[maxn];
void Init() //建立图的邻接表需要先初始化,建立顶点结点
{
for(int i = 1; i <= n; i++)
{
Ver[i].vex = i;
Ver[i].firarc = NULL;
}
}
void Insert(int a, int b, int w) //尾插法,插入以a为起点,b为终点,权为w的边,效率不如头插,但是可以去重边
{
arcnode * q = new arcnode(b, w);
if(Ver[a].firarc == NULL)
Ver[a].firarc = q;
else
{
arcnode * p = Ver[a].firarc;
if(p->vertex == b)
{
if(p->weight > w)
p->weight = w;
return ;
}
while(p->next != NULL)
{
if(p->next->vertex == b)
{
if(p->next->weight > w)
p->next->weight = w;
return ;
}
p = p->next;
}
p->next = q;
}
}
void Insert2(int a, int b, int w) //头插法,效率更高,但不能去重边
{
arcnode * q = new arcnode(b, w);
if(Ver[a].firarc == NULL)
Ver[a].firarc = q;
else
{
arcnode * p = Ver[a].firarc;
q->next = p;
Ver[a].firarc = q;
}
}
struct node //顶点节点,保存id和到源顶点的估算距离,优先队列需要的类型
{
int id; //源顶点id和估算距离
int w;
friend bool operator<(node a, node b) //因要实现最小堆,按升序排列,因而需要重载运算符,重定义优先级,以小为先
{
return a.w > b.w;
}
};
#define INF 0xfffff //权值上限
int parent[maxn]; //每个顶点的父亲节点,可以用于还原最短路径树
bool visited[maxn]; //用于判断顶点是否已经在最短路径树中,或者说是否已找到最短路径
node d[maxn]; //源点到每个顶点估算距离,最后结果为源点到所有顶点的最短路。
priority_queue<node> q; //优先队列stl实现
void Dijkstra(int s) //Dijkstra算法,传入源顶点
{
for(int i = 1; i <= n; i++) //初始化
{
d[i].id = i;
d[i].w = INF; //估算距离置INF
parent[i] = -1; //每个顶点都无父亲节点
visited[i] = false; //都未找到最短路
}
d[s].w = 0; //源点到源点最短路权值为0
q.push(d[s]); //压入队列中
while(!q.empty()) //算法的核心,队列空说明完成了操作
{
node cd = q.top(); //取最小估算距离顶点
q.pop();
int u = cd.id;
if(visited[u]) //注意这一句的深意,避免很多不必要的操作
continue;
visited[u] = true;
arcnode * p = Ver[u].firarc;
//松弛操作
while(p != NULL) //找所有与他相邻的顶点,进行松弛操作,更新估算距离,压入队列。
{
int v = p->vertex;
if(!visited[v] && d[v].w > d[u].w+p->weight)
{
d[v].w = d[u].w+p->weight;
parent[v] = u;
q.push(d[v]);
}
p = p->next;
}
}
}
int main()
{
int m, a, b, c, st, ed;
printf("请输入顶点数和边数:\n");
scanf("%d%d", &n, &m);
printf("请输入边以及权值(a, b, c)\n");
Init(); //计算前必须初始化
while(m--)
{
scanf("%d%d%d", &a, &b, &c);
Insert2(a+1, b+1, c); //无向图注意存储两条边
Insert2(b+1, a+1, c);
}
st=1;
Dijkstra(st);
cout<<d[n].w;
return 0;
}//测试可以成功。
堆优化最短路:https://blog.youkuaiyun.com/largecub233/article/details/73321440
松弛操作:
对于新加入的中间点,遍历所有与之有关的点,判断是否能通过新的边更新到源点的距离,如果更新了,说明有更小的距离了,需要加入队列,但之前较大的也加过了没法删去。
但是不能用较大的,优先队列会优先使用最小的距离加入确定最短路径的区域,赋值表示已经加入,再次遇到加入的点直接continue即可。
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<map>
#include<vector>
#include<set>
#include<cctype>
#include<queue>
#define rep(a,b) for(register int i=a;i<=b;i++)
#define red(a,b) for(register int i=a;i>=b;i--)
#define ULL unsigned long long
#define LL long long
using namespace std;
const int N = 1e5 + 5;
struct node
{
int dist;
int id;
};
struct pnode
{
int to, next, w;
}a[500005];
int head[N],d[N],pre;
bool vis[N];
int n, m, x, y, z, S;
void init(int x, int y, int w)
{
a[++pre].to = y;
a[pre].w = w;
a[pre].next = head[x];
head[x] = pre;
}//用于遍历一个点发出的所有边
node M(int dist, int id) { node a; a.dist = dist, a.id = id; return a; }
bool operator <(node x, node y) { return x.dist > y.dist; };
void dijkstra()
{
for (int i = 0; i <= n; i++)d[i] = 2147483647;
priority_queue<node>Q; d[S] = 0;
Q.push(M(0, S));
while (!Q.empty())
{
node c = Q.top(); Q.pop();
if (vis[c.id])continue;
int x = c.id; vis[x] = 1;
for (int k = head[x]; k; k = a[k].next)
if (!vis[a[k].to] && d[a[k].to] > d[x] + a[k].w)
d[a[k].to] = d[x] + a[k].w, Q.push(M(d[a[k].to], a[k].to));
}
}
int main()
{
cin >> n >> m >> S;
rep(1, m)
{
scanf("%d%d%d", &x, &y, &z);
init(x, y, z);
}
dijkstra();
for (int i = 1; i <= n; i++)cout << d[i] << " ";
system("pasue");
}