本人代码提交后洛谷显示TLE,下载数据#1后自测很快输出答案未停顿(大约就是平常的2ms)是什么原因?算法是dijkstra+优先队列。
相关信息:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<cstring>
#define N 500 + 10
#define M 100 + 10
#define EDGE ((N * (N - 1)) >> 1) * M
using namespace std;
int m, n, station[N], stationadd, cnt, road, head[N], ans, v[N];
bool vis[N];
struct edgenode { int road, nextstation, nextedge;};
edgenode edge[EDGE];
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch>'9') {
if (ch == '-') w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
s = (s << 3) + (s << 1) + (ch ^ 48);
ch = getchar();
}
return s * w;
}
void buildedge() {
++road;
for (int i = 1; i < stationadd; ++i) {
for (int j = i + 1; j <= stationadd; ++j) {
edge[++cnt].road = road;
edge[cnt].nextstation = station[j];
edge[cnt].nextedge = head[station[i]];
head[station[i]] = cnt;
}
}
}
void readline() {
//int x=read();//没有什么用
stationadd = 0;
char ch = getchar();
while (ch != '\n') {
int s = 0, w = 1;
while (ch < '0' || ch>'9') {
if (ch == '-') w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
s = (s << 3) + (s << 1) + (ch ^ 48);
ch = getchar();
}
station[++stationadd] = s * w;
}
buildedge();
}
struct Node {
int nowstation, road, ans;
Node(int nowstation, int road, int ans) : nowstation(nowstation), road(road), ans(ans){}
bool operator<(const Node& x)const {
return x.ans < ans;
}
};
int dijkstra() {
memset(v, 0x3f, sizeof(v));
priority_queue<Node>q;
q.push(Node(1, 0, 0));
v[1] = 0;
while (!q.empty()) {
Node u = q.top();
q.pop();
if (u.nowstation == n) return u.ans;
for (int i = head[u.nowstation]; i; i = edge[i].nextedge) {
if (u.road == 0) {
if (v[edge[i].nextstation] > v[u.nowstation]) q.push(Node(edge[i].nextstation, edge[i].road, 0)), v[edge[i].nextstation] = v[u.nowstation];
}
else {
if (u.road == edge[i].road && v[edge[i].nextstation] > v[u.nowstation]) q.push(Node(edge[i].nextstation, edge[i].road, u.ans)), v[edge[i].nextstation] = v[u.nowstation];
else if (u.road != edge[i].road && v[edge[i].nextstation] > v[u.nowstation] + 1) q.push(Node(edge[i].nextstation, edge[i].road, u.ans + 1)), v[edge[i].nextstation] = v[u.nowstation] + 1;
}
}
}
return -1;
}
int main() {
m = read(), n = read();
for (int i = 1; i <= m; ++i) readline();
ans=dijkstra();
if (ans != -1) printf("%d", ans);
else printf("NO");
return 0;
}