1. 程式人生 > >hdu1688 Sightseeing(次短路)

hdu1688 Sightseeing(次短路)

題目連結:

題意:

給你n個點,m條有向邊,問你從s走到t點最短路加上最短路權值加一的路徑條數

資料範圍:

2n1000,1m100001s,tn,st

題解:

我們相當於求最短路和次短路,注意這裡的次短路是權值的次短。然後注意處理最小和次小的關係!!

程式碼:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<bitset> #include<set> #include<queue> #include<stack> #include<map> #include<cstdlib> #include<cmath> #define PI 2*asin(1.0) #define LL long long #define pb push_back #define pa pair<int,int> #define clr(a,b) memset(a,b,sizeof(a)) #define lson lr<<1,l,mid
#define rson lr<<1|1,mid+1,r #define bug(x) printf("%d++++++++++++++++++++%d\n",x,x) #define key_value ch[ch[root][1]][0] const int MOD = 1000000007; const int N = 1000 + 15; const int maxn = 1e4+ 14; const int letter = 130; const int INF = 1e9; const double pi=acos(-1.0); const double eps=1e-8; using namespace
std; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } int n,m,s,t,head[N],tot; int dis[N][2],vis[N][2],path[N][2]; struct edges{ int to,next,val; }e[maxn]; void add(int u,int v,int val){ e[tot].val=val,e[tot].to=v,e[tot].next=head[u],head[u]=tot++; } struct node{ int x,val,mark; node(){} node(int x,int val,int mark):x(x),val(val),mark(mark){} bool operator < (const node &p) const{ return val>p.val; } }; priority_queue<node>pq; void dijstra(int s,int t){ while(!pq.empty()) pq.pop(); for(int i=1;i<=n;i++) dis[i][0]=dis[i][1]=INF; clr(vis,0),clr(path,0); dis[s][0]=0; path[s][0]=1; pq.push(node(s,0,0)); while(!pq.empty()){ node now=pq.top(); pq.pop(); int x=now.x,mark=now.mark; if(vis[x][now.mark]) continue; vis[x][now.mark]=1; for(int i=head[x];i!=-1;i=e[i].next){ int to=e[i].to,val=e[i].val; if(dis[x][mark]+val<dis[to][0]){ if(dis[to][0]!=INF){ dis[to][1]=dis[to][0]; path[to][1]=path[to][0]; pq.push(node(to,dis[to][1],1)); } dis[to][0]=dis[x][mark]+val; path[to][0]=path[x][mark]; pq.push(node(to,dis[to][0],0)); } else if(dis[x][mark]+val==dis[to][0]){ path[to][0]+=path[x][mark]; } else if(dis[x][mark]+val<dis[to][1]){ dis[to][1]=dis[x][mark]+val; path[to][1]=path[x][mark]; pq.push(node(to,dis[to][1],1)); } else if(dis[x][mark]+val==dis[to][1]){ path[to][1]+=path[x][mark]; } } } ///for(int i=1;i<=n;i++) printf("i = %d %d %d\n",i,dis[i][0],dis[i][1]); int ans=path[t][0]; if(dis[t][0]==dis[t][1]-1) ans+=path[t][1]; printf("%d\n",ans); } int main(){ int T,u,v,w; scanf("%d",&T); while(T--){ clr(head,-1),tot=0; scanf("%d%d",&n,&m); for(int i=0;i<m;i++){ scanf("%d%d%d",&u,&v,&w); add(u,v,w); } scanf("%d%d",&s,&t); dijstra(s,t); } return 0; }