QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#669271#8232. Yet Another Shortest Path Queryqzez#TL 8927ms14140kbC++141.8kb2024-10-23 17:55:402024-10-23 17:55:41

Judging History

你现在查看的是最新测评结果

  • [2024-10-23 17:55:41]
  • 评测
  • 测评结果:TL
  • 用时:8927ms
  • 内存:14140kb
  • [2024-10-23 17:55:40]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10,INF=1e9;
int n,m,q;
vector<tuple<int,int,int>>E;
mt19937 rnd(time(0));
vector<tuple<int,int,int>>Q;
int p[N];
int find(int x){
    return p[x]==x?x:p[x]=find(p[x]);
}
struct edges{
    int to,w,nex;
}edge[N*2];
int kk,head[N];
void add(int u,int v,int w){
    edge[++kk]={v,w,head[u]},head[u]=kk;
}
int vis[N],fa[N];
int dis[N];
void dfs(int u,int fa=0){
    ::fa[u]=fa;
    for(int i=head[u];i;i=edge[i].nex){
        int v=edge[i].to;
        if(v==fa)continue;
        dis[v]=dis[u]+edge[i].w;
        dfs(v,u);
    }
}
void run(){
    shuffle(E.begin(),E.end(),rnd);
    iota(p,p+1+n,0);
    kk=0,fill(head,head+1+n,0);
    for(auto [u,v,w]:E){
        int x=find(u),y=find(v);
        if(x==y)continue;
        add(u,v,w),add(v,u,w);
        p[x]=y;
    }
    fill(vis,vis+1+n,0);
    for(int i=1;i<=n;i++)if(!vis[i])dis[i]=0,dfs(i);
    for(auto &[u,v,ans]:Q){
        if(dis[u]>dis[v])swap(u,v);
        if(fa[v]==u)ans=min(ans,dis[v]-dis[u]);
        else if(fa[v]==fa[u])ans=min(ans,dis[u]+dis[v]-dis[fa[u]]*2);
        else if(fa[fa[v]]==u)ans=min(ans,dis[v]-dis[u]);
        else if(fa[fa[fa[v]]]==u)ans=min(ans,dis[v]-dis[u]);
        else if(fa[fa[v]]==fa[u])ans=min(ans,dis[v]+dis[u]-dis[fa[u]]*2);
        else if(fa[v]==fa[fa[u]])ans=min(ans,dis[v]+dis[u]-dis[fa[v]]*2);
    }
}
int main(){
    scanf("%d%d",&n,&m);
    E.resize(m);
    for(auto &[u,v,w]:E){
        scanf("%d%d%d",&u,&v,&w);
    }
    scanf("%d",&q);
    Q.resize(q);
    for(auto &[u,v,ans]:Q){
        scanf("%d%d",&u,&v);
        ans=INF;
    }
    for(;;){
        run();
        if(1.0*clock()/CLOCKS_PER_SEC>10.5)break;
    }
    for(auto [u,v,ans]:Q)printf("%d\n",ans<INF?ans:-1);
    return 0;
}

详细

Test #1:

score: 100
Accepted
time: 8927ms
memory: 14140kb

input:

6 9
1 2 4
2 3 6
3 6 5
6 5 3
5 4 2
4 1 3
3 4 9
1 3 100
5 3 1
5
1 3
1 6
3 4
3 5
2 5

output:

6
8
3
1
7

result:

ok 5 number(s): "6 8 3 1 7"

Test #2:

score: 0
Accepted
time: 7361ms
memory: 14084kb

input:

6 4
1 2 1
2 3 1
3 4 1
4 5 1
3
1 4
1 5
1 6

output:

3
-1
-1

result:

ok 3 number(s): "3 -1 -1"

Test #3:

score: -100
Time Limit Exceeded

input:

40005 79608
1 2 70031203
1 3 99924845
1 4 61645659
1 5 9324967
2 3 15761918
3 4 62534796
4 5 35260314
5 2 35948540
6 2 23727405
6 7 83302920
7 3 31010426
7 8 75060393
8 4 94275932
8 9 99663793
9 5 81701979
9 6 439297
10 6 46955645
10 11 89514237
11 7 21257310
11 12 53896253
12 8 67933315
12 13 26161...

output:


result: