1 条题解

  • 0
    @ 2025-9-10 8:56:47

    C++ :

    #include<cmath>
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    using namespace std;
    struct node{
    	int x,y,d,next;	
    }a[21000];int len,last[11000];
    void ins(int x,int y,int d){
    	len++;
    	a[len].x=x;a[len].y=y;a[len].d=d;
    	a[len].next=last[x];last[x]=len;
    }
    int n,m,d[110],head,tail,list[110];bool v[110],kt[110][110];
    int main(){
    	int t;
    	while(scanf("%d",&n)){
    		if(n==0)return 0;
    		len=0;memset(last,0,sizeof(last));
    		scanf("%d",&m);
    		for(int i=1;i<=m;i++){
    			int x,y,c;
    			scanf("%d%d%d",&x,&y,&c);
    			ins(x,y,c);
    			ins(y,x,c);
    		}
    		scanf("%d",&m);memset(kt,false,sizeof(kt));
    		for(int i=1;i<=m;i++){
    			int x,y;
    			scanf("%d%d",&x,&y);
    			kt[x][y]=true;
    			kt[y][x]=true;
    		}
    		int st,ed;
    		scanf("%d%d",&st,&ed);
    		for(int i=1;i<=n;i++)d[i]=999999999;d[st]=0;
    		memset(v,false,sizeof(v));v[st]=true;
    		head=1;tail=2;list[1]=st;
    		while(head!=tail){
    			int x=list[head];
    			for(int k=last[x];k>0;k=a[k].next){
    				int y=a[k].y;
    				if(kt[a[k].x][a[k].y]==true){
    					if(d[y]>d[x]+a[k].d){
    						d[y]=d[x]+a[k].d;
    						if(v[y]==false){
    							v[y]=true;
    							list[tail++]=y;
    							if(tail==n+1)tail=1;	
    						}
    					}
    				}
    				else{
    					if(d[y]>d[x]){
    						d[y]=d[x];
    						if(v[y]==false){
    							v[y]=true;
    							list[tail++]=y;
    							if(tail==n+1)tail=1;	
    						}
    					}
    				}
    			}
    			head++;
    			v[x]=false;
    			if(head==n+1)head=1;
    		}
    		printf("%d\n",d[ed]);
    	}
    }
    
    • 1

    信息

    ID
    3386
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者