P8025 [ONTAK2015] Związek Harcerstwa Bajtockiego
给一个 Dijkstra 的 分算法,正解想不出来了?
思路倒也很简单,Dijkstra 过程中记录一下路径,就可以跑最短路了,如果最短路小于等于 ,直接转移。不然就到走 步的位置上。
代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
#define int long long
const int N = 1e6 + 5;
vector<int> G[N];
int n, m, k, now, pre[N], dis[N];
bool vis[N];
int d, t;
struct Node
{
int place, dist;
Node(int a, int b): place(a), dist(b){}
bool operator<(const Node& g) const
{
return g.dist < dist;
}
};
inline void dijkstra(int start)
{
dis[start] = 0;
priority_queue<Node> q;
q.push(Node(start,0));
while (!q.empty())
{
Node l = q.top();
q.pop();
vis[l.place] = true;
for (int i = 0; i < G[l.place].size(); i++)
{
int nx = G[l.place][i];
if (dis[nx] > dis[l.place] + 1)
{
dis[nx] = dis[l.place] + 1;
pre[nx] = l.place;
if (!vis[nx])
{
q.push(Node(nx, dis[nx]));
}
}
}
}
}
signed main()
{
scanf("%lld %lld %lld", &n, &m, &k);
now = m;
for (int i = 1; i < n; i++)
{
int u, v;
scanf("%lld %lld", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
while (k--)
{
scanf("%lld %lld", &d, &t);
memset(dis, 0x3f, sizeof(dis));
memset(vis, false, sizeof(vis));
dijkstra(now);
if (dis[d] <= t) now = d;
else
{
int pr = pre[d];
while (dis[pr] > t) pr = pre[pr];
now = pr;
}
printf("%lld ", now);
}
puts("");
return 0;
}
还写了个广搜,比 Dijkstra 快一点,但还是 分:
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
#define int long long
const int N = 1e6 + 5;
vector<int> G[N];
int n, m, k, now;
bool vis[N];
int d, t;
struct Node
{
int place, dist;
vector<int> path;
Node(int a, int b, vector<int> p): place(a), dist(b), path(p){}
Node()
{
place = dist = 0;
path.clear();
}
};
inline Node bfs(int start, int end)
{
queue<Node> q;
Node b;
b.place = start, b.dist = 0;
b.path.push_back(start);
q.push(b);
vis[start] = true;
while (!q.empty())
{
Node l = q.front();
q.pop();
vector<int> copy = l.path;
copy.push_back(l.place);
if (l.place == end) return Node(end, l.dist, copy);
for (register int i = 0; i < G[l.place].size(); i++)
{
int nx = G[l.place][i];
if (!vis[nx])
{
vis[nx] = true;
q.push(Node(nx, l.dist + 1, copy));
}
}
}
}
signed main()
{
scanf("%lld %lld %lld", &n, &m, &k);
now = m;
for (register int i = 1; i < n; i++)
{
int u, v;
scanf("%lld %lld", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
while (k--)
{
scanf("%lld %lld", &d, &t);
memset(vis, false, sizeof(vis));
Node g = bfs(now, d);
if (g.dist <= t) now = d;
else
{
vector<int> temp = g.path;
int nowh = temp.size() - 1;
while (g.dist - (temp.size() - 1 - nowh) > t) nowh--;
now = temp[nowh];
}
printf("%lld ", now);
}
puts("");
return 0;
}

浙公网安备 33010602011771号