题目链接:http://poj.org/problem?id=3463
题目大意及分析:
(我这题不会,纯属抄袭)
http://www.cppblog.com/Yuan/archive/2010/04/19/112983.html
代码风格不错,学习了下dijkstra+优先队列来解决这种题目,也学到了那个Node(int v_, int f_){v=v_,f=f_;}的写法;
代码:
poj3463
1 /*3463 Accepted 572K 47MS C++ 2481B 2012-06-23 19:44:41*/ 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <iostream> 6 #include <algorithm> 7 #include <vector> 8 #include <queue> 9 using namespace std; 10 11 #define mpair make_pair 12 #define pii pair<int,int> 13 #define MM(a,b) memset(a,b,sizeof(a)); 14 typedef long long lld; 15 typedef unsigned long long u64; 16 template<class T> bool up_max(T& a,const T& b){return b>a? a=b,1 : 0;} 17 template<class T> bool up_min(T& a,const T& b){return b<a? a=b,1 : 0;} 18 #define maxn 1010 19 const int inf= 2100000000; 20 21 int n,m; 22 vector< pii > map[maxn]; 23 24 bool vis[maxn][2]; 25 int dis[maxn][2]; 26 int cnt[maxn][2]; 27 28 struct Node{ 29 int v,f; 30 Node(int v_,int f_){v=v_,f=f_;} 31 bool operator<(Node a)const{ 32 return dis[v][f] > dis[a.v][a.f]; 33 } 34 }; 35 36 priority_queue<Node>Q; 37 void Dijkstra(int st, int ed){ 38 for(int i=1;i<=n;++i){ 39 vis[i][0]= vis[i][1]= 0; 40 cnt[i][0]= cnt[i][1]= 0; 41 dis[i][0]= dis[i][1]= inf; 42 } 43 while( !Q.empty() ) Q.pop(); 44 dis[st][0]= 0, cnt[st][0]= 1; 45 Q.push( Node( st, 0 ) ); 46 while( !Q.empty() ){ 47 Node a= Q.top(); Q.pop(); 48 int u= a.v, f= a.f; 49 if( vis[u][f] ) continue; 50 vis[u][f]= 1; 51 for(int i=0;i<map[u].size();++i){ 52 int v= map[u][i].first, w= dis[u][f]+map[u][i].second; 53 if( w<dis[v][0] ){ 54 if( dis[v][0]!=inf ){ 55 dis[v][1]= dis[v][0]; 56 cnt[v][1]= cnt[v][0]; 57 Q.push( Node( v, 1 ) ); 58 } 59 dis[v][0]= w; 60 cnt[v][0]= cnt[u][f]; 61 Q.push( Node( v, 0 ) ); 62 } 63 else if( w==dis[v][0] ) cnt[v][0]+= cnt[u][f]; 64 else if( up_min( dis[v][1], w ) ){ 65 cnt[v][1]= cnt[u][f]; 66 Q.push( Node( v, 1 ) ); 67 } 68 else if( w==dis[v][1] ) cnt[v][1]+= cnt[u][f]; 69 } 70 } 71 } 72 73 int main() 74 { 75 //freopen("poj3463.in","r",stdin); 76 int Cas, i, j, x, y, t; 77 cin>>Cas; 78 while( Cas-- ){ 79 cin>>n>>m; 80 for(i=1;i<=n;++i) map[i].clear(); 81 for(i=1;i<=m;++i){ 82 scanf("%d%d%d", &x, &y, &t); 83 map[x].push_back( pii( y, t ) ); //unidirectional; 84 } 85 int st, ed; 86 scanf("%d%d", &st, &ed); 87 Dijkstra( st, ed ); 88 int ans= cnt[ed][0]; 89 if( dis[ed][0]==dis[ed][1]-1 ) ans+= cnt[ed][1]; 90 cout<< ans <<endl; 91 } 92 }