链式前向星TLE
#include<bits/stdc++.h>
#define rep(u,x,y) for(int u=x;u<=y;++u)
#define debug cout<<__LINE__<<' '<<__FUNCTION__<<'\n';
#define gc getchar()
#define pc putchar
using namespace std;
const int N=1e6+1;
typedef long long ll;
ll read(){
ll x=0,w=1;
char ch=gc;
while(ch<'0'||ch>'9')(ch=='-')&&(w=-1,0),ch=gc;
while(ch>='0'&&ch<='9')x=(x<<3)+x+x+(ch^48),ch=gc;
return x*w;
}
void wrt(ll x){
if(x<0)pc('-'),x=-x;
if(x>9)wrt(x/10);
pc(x%10^48);
}
int pre[N],nxt[N],h[N],w[N],dist[N],vis[N],idx,n=read(),m=read(),r=read(),x,y,z,qe;
struct nd{
int dis,u;
bool operator>(const nd&a)const{return dis>a.dis;}
};
priority_queue<nd,vector<nd>,greater<nd> >q;
void add(int x,int y,int z){
h[++idx]=y;
nxt[idx]=pre[x];
w[pre[x]=idx]=z;
}
void dij(int s){
memset(dist,0x3f,(n+1)*sizeof(int));
memset(vis,0,(n+1)*sizeof(int));
dist[s]=0,q.push({0,s});
while(q.size()){
int u=q.top().u;q.pop();
if(vis[u])continue;
vis[u]=1;
for(int i=pre[u];i;i=nxt[i]){
int to=h[i],wt=w[i];
if(dist[to]>dist[u]+wt)dist[to]=dist[u]+wt,q.push({dist[to],to});
}
}
}
int main(){
puts("I'm here!");
while(m--)x=read(),y=read(),add(x,y,1),add(y,x,1);
dij(r);
qe=read();
while(qe--){
x=read(),y=read();
puts(dist[x]<=dist[y]?"Terry":"Jom");
}
return 0;
}
邻接矩阵AC
#include<bits/stdc++.h>
#define rep(u,x,y) for(int u=x;u<=y;++u)
#define debug cout<<__LINE__<<' '<<__FUNCTION__<<'\n';
#define gc getchar()
#define pc putchar
using namespace std;
const int N=1e6+1;
typedef long long ll;
ll read(){
ll x=0,w=1;
char ch=gc;
while(ch<'0'||ch>'9')(ch=='-')&&(w=-1,0),ch=gc;
while(ch>='0'&&ch<='9')x=(x<<3)+x+x+(ch^48),ch=gc;
return x*w;
}
void wrt(ll x){
if(x<0)pc('-'),x=-x;
if(x>9)wrt(x/10);
pc(x%10^48);
}
int n=read(),m=read(),r=read(),t,x,y,z;
struct nd{
int dis,u;
bool operator>(const nd&a)const{return dis>a.dis;}
};
struct edge {
int v, w;
};
struct node {
int dis, u;
bool operator>(const node& a) const { return dis > a.dis; }
};
vector<edge> e[N];
int dis[N], vis[N];
priority_queue<node, vector<node>, greater<node>> q;
void dijkstra(int s) {
memset(dis, 0x3f, (n + 1) * sizeof(int));
memset(vis, 0, (n + 1) * sizeof(int));
dis[s] = 0;
q.push({0, s});
while (!q.empty()) {
int u = q.top().u;
q.pop();
if (vis[u]) continue;
vis[u] = 1;
for (auto ed : e[u]) {
int v = ed.v, w = ed.w;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
q.push({dis[v], v});
}
}
}
}
int main(){
while(m--)x=read(),y=read(),e[x].push_back((edge){y,1}),e[y].push_back((edge){x,1});
puts("I'm here!");
dijkstra(r);
for(t=read();t--;){
x=read(),y=read();
if(dis[x]<=dis[y])puts("Terry");
else puts("Jom");
}
return 0;
}