zoukankan      html  css  js  c++  java
  • 【模板】最短路计数

    洛谷 1144

    dijkstra+手写堆

    #include<cstdio>
    #include<algorithm>
    #define N 2000010
    #define Mod 100003
    #define rg register
    using namespace std;
    int n,m,tot,dis[N],last[N],cnt[N],pos[N];
    struct edge{
    	int to,pre,dis;
    }e[N];
    struct heap{
    	int poi,dis;
    }h[N];
    inline int read(){
    	int k=0,f=1; char c=getchar();
    	while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
    	while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
    	return k*f;
    }
    inline void add(int x,int y){
    	e[++tot]=(edge){y,last[x],1}; last[x]=tot;
    }
    inline void MOD(int &x){
    	if(x>=Mod) x-=Mod;
    }
    inline void up(int x){
    	int fa;
    	while((fa=x>>1)&&h[fa].dis>h[x].dis){
    		swap(h[x],h[fa]); swap(pos[h[x].poi],pos[h[fa].poi]);
    		x=fa;
    	}
    }
    inline void down(int x){
    	int son;
    	while((son=(x<<1))<=tot){
    		if(son<tot&&h[son].dis>h[son+1].dis) son++;
    		if(h[son].dis<h[x].dis){
    			swap(h[x],h[son]); swap(pos[h[x].poi],pos[h[son].poi]);
    			x=son;
    		}
    		else return;
    	}
    }
    void dijkstra(int x){
    	h[tot=pos[x]=cnt[x]=1]=(heap){1,dis[x]=0};
    	while(tot){
    		int now=h[1].poi; h[1]=h[tot--]; if(tot) down(1);
    		for(rg int i=last[now],to;i;i=e[i].pre)
    		if(dis[to=e[i].to]>=dis[now]+e[i].dis){
    			if(dis[to]==dis[now]+e[i].dis) cnt[to]+=cnt[now],MOD(cnt[to]);
    			else{
    				dis[to]=dis[now]+e[i].dis; cnt[to]=cnt[now];
    				if(!pos[to]) h[pos[to]=++tot]=(heap){to,dis[to]};
    				else h[pos[to]].dis=dis[to];
    				up(pos[to]);
    			}
    		}
    	}
    }
    int main(){
    //	freopen("testdata.in","r",stdin);
    //	freopen("my.out","w",stdout);
    	n=read(); m=read();
    	for(rg int i=1;i<=n;i++) dis[i]=0X7f7f7f7f;
    	for(rg int i=1,u,v;i<=m;i++){
    		u=read(),v=read(); 
    		//if(u==v) continue;
    		add(u,v); add(v,u);
    	}
    	dijkstra(1);
    	for(rg int i=1;i<=n;i++) printf("%d
    ",cnt[i]);
    	//puts(""); for(rg int i=1;i<=n;i++) printf("%d ",dis[i]);
    	return 0;
    }
    

      

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    基于分布式锁解决定时任务重复问题
    基于Redis的Setnx实现分布式锁
    基于数据库悲观锁的分布式锁
    使用锁解决电商中的超卖
  • 原文地址:https://www.cnblogs.com/DriverLao/p/8548923.html
Copyright © 2011-2022 走看看