例题9.1
#include <cstdio>
#include <queue>
using namespace std;
#define N 100001
struct Info{
int pos;
int time;
};
int main() {
int n, k;
scanf("%d%d", &n, &k);
queue<Info> posQueue;
bool isvisit[N];
for(int i = 0; i < N; ++i) {
isvisit[i] = false;
}
Info first;
first.pos = n;
first.time = 0;
posQueue.push(first);
while(posQueue.empty() == false) {
Info cur = posQueue.front();
posQueue.pop();
if(cur.pos == k) {
printf("%d\n", cur.time);
break;
}
isvisit[cur.pos] = true;
Info neighbour;
if(cur.pos - 1 >= 0 && cur.pos - 1 < N && isvisit[cur.pos - 1] == false) {
neighbour.pos = cur.pos - 1;
neighbour.time = cur.time + 1;
posQueue.push(neighbour);
}
if(cur.pos + 1 >= 0 && cur.pos + 1 < N && isvisit[cur.pos + 1] == false) {
neighbour.pos = cur.pos + 1;
neighbour.time = cur.time + 1;
posQueue.push(neighbour);
}
if(cur.pos * 2 >= 0 && cur.pos * 2 < N && isvisit[cur.pos * 2] == false) {
neighbour.pos = cur.pos * 2;
neighbour.time = cur.time + 1;
posQueue.push(neighbour);
}
}
return 0;
}
例题11.6
#include <cstdio>
#include <vector>
#include <climits>
#include <queue>
using namespace std;
#define N 300
struct Edge {
int y;
int weight;
};
vector<Edge> graph[N];
struct Node{
int dist;
int x;
};
bool operator < (Node lhs, Node rhs) {
return lhs.dist > rhs.dist;
}
int dijkstra(int s, int t, int n) {
int dist[N];
bool isvisit[N];
for(int i = 0; i < n; ++i) {
dist[i] = INT_MAX;
isvisit[i] = false;
}
priority_queue<Node> pqueue;
dist[s] = 0;
Node node;
node.dist = dist[s];
node.x = s;
pqueue.push(node);
while(pqueue.empty() == false) {
int x = pqueue.top().x;
pqueue.pop();
if(isvisit[x] == true) {
continue;
}
isvisit[x] = true;
for(int i = 0; i < graph[x].size(); ++i) {
int y = graph[x][i].y;
int weight = graph[x][i].weight;
if(dist[y] > dist[x] + weight) {
dist[y] = dist[x] + weight;
node.dist = dist[y];
node.x = y;
pqueue.push(node);
}
}
}
if(dist[t] != INT_MAX) {
return dist[t];
} else {
return -1;
}
}
int main() {
int n, m;
while(scanf("%d%d", &n, &m) != EOF) {
// printf("%d%d", n, m);
for(int i = 0; i < n; ++i) {
graph[i].clear(); // 清理每个链表中存留的边
}
for(int i = 0; i < m; ++i) {
int x, y, weight;
scanf("%d%d%d", &x, &y, &weight);
Edge edge;
edge.y = y;
edge.weight = weight;
graph[x].push_back(edge);
edge.y = x;
edge.weight = weight;
graph[y].push_back(edge);
// printf("printf = %d %d\n", Graph[x][i].y, Graph[x][i].weight);
}
int s, t;
scanf("%d%d", &s, &t);
printf("%d\n", dijkstra(s, t, n));
}
}
A1012 The best rank