# bzoj1663 [Usaco2006 Open]赶集 (最短路)

4
13 9 19 3
0 10 20 3
4 0 11 2
1 15 0 12
5 5 13 0

3

Gold

## Solution

• 将点按照出现时间排好序
• 如果从i点能到达j点则从i向j连一条边。
从i点能到达j点是指：取完i点的物品后，直接走向j点，能在j点物品下落之前到达，即 p[i]+Ti,j<=p[j] $p[i]+T_{i,j} <= p[j]$
• 方便起见，我们假设出发点为0， p[0]=0,T0,i=T1,i $p[0]=0, T_{0,i}=T_{1,i}$
• 跑一边spfa求出0到其他点的最长路，其中最长的就是答案。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int n;
struct Node{
int pos, tim;
bool operator < (const Node &n) const {
return tim < n.tim;
}
}p[405];
int d[405][405];
vector<int> edges[405];
int dist[405];
bool vis[405];

int spfa() {
queue<int> q;
q.push(0);
vis[0] = 1;
while (!q.empty()) {
int current = q.front();
q.pop();
for (int i = 0; i < edges[current].size(); i++) {
if (dist[current] + 1 > dist[edges[current][i]]) {
dist[edges[current][i]] = dist[current] + 1;
if (!vis[edges[current][i]]) {
vis[edges[current][i]] = 1;
q.push(edges[current][i]);
}
}
}
vis[current] = 0;
}
int ans = 0;
for (int i = 1; i <= n; i++)
ans = max(ans, dist[i]);
return ans;
}

int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &p[i].tim);
p[i].pos = i;
}
sort(p + 1, p + n + 1);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &d[i][j]);
for (int i = 1; i <= n; i++)
d[0][i] = d[1][i];
p[0].pos = p[0].tim = 0;
for (int i = 0; i <= n; i++)
for (int j = i + 1; j <= n; j++)
if (p[i].tim + d[p[i].pos][p[j].pos] <= p[j].tim)
edges[i].push_back(j);
int ans = spfa();
printf("%d\n", ans);
return 0;
}

02-11 505

09-15 403
05-04 21
09-04 26
12-18 94
12-24 1642
12-24 50
08-23 2720