Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1214 Accepted Submission(s): 394
本题的思想就是dfs+dijkstra。本题的意思是,如果在点B出存在一条路使得从B点出发可以比从A点出发跟快的到达home,所以B到home的最短距离要比A到home得最短距离小,所以本题首先要求出各点到home得距离,然后再用记忆搜索法搜索即可
代码:
1 #include<stdio.h>
2 #include<string.h>
3 #include<queue>
4 using namespace std;
5 int dist[1005],dp[1005];
6 typedef struct t
7 {
8 int end,len;
9 struct t *next;
10 }T;
11 struct node
12 {
13 int data;
14 int len;
15 bool operator <(const node &a)const
16 {
17 return a.len<len;
18 }
19 T *next;
20 }s[1005];
21 void dijkstra(int v0)
22 {
23 s[v0].len=0;node cur;
24 int visit[1005],mark=0;
25 memset(visit,0,sizeof(visit));
26 memset(dist,-1,sizeof(dist));
27 priority_queue<node> qu;
28 qu.push(s[v0]);
29 dist[v0]=0;
30 while(!qu.empty ())
31 {
32 cur=qu.top();
33 while(visit[cur.data])
34 {
35 qu.pop();
36 if(qu.empty ())
37 {
38 mark=1;
39 break;
40 }
41 cur=qu.top();
42 }
43 if(mark)
44 break;
45 qu.pop();
46 visit[cur.data]=1;
47 T *p=cur.next;
48 while(p)
49 {
50 if(!visit[p->end])
51 {
52 if(dist[p->end]==-1||dist[cur.data]+p->len<dist[p->end] )
53 s[p->end].len=dist[p->end]=p->len+dist[cur.data];
54 qu.push (s[p->end]);
55 }
56 p=p->next;
57 }
58 }
59 }
60 int dfs(int v0)
61 {
62 int temp=0;
63 if(v0==2)
64 return 1;
65 if(dp[v0]!=-1)
66 return dp[v0];
67 t *p=s[v0].next;
68 while(p)
69 {
70 if(dist[v0]>dist[p->end])
71 {
72 dp[p->end]=dfs(p->end);
73 temp+=dp[p->end];
74 }
75 p=p->next;
76 }
77 return temp;
78 }
79 int main()
80 {
81 int n,i,m,a,b,len;
82 while(scanf("%d",&n)!=EOF)
83 {
84 if(n==0)
85 break;
86 scanf("%d",&m);
87 T *p,*q;
88 for(i=1;i<=n;i++)
89 {
90 s[i].next=NULL;
91 s[i].data=i;
92 }
93 memset(dp,-1,sizeof(dp));
94 for(i=1;i<=m;i++)
95 {
96 scanf("%d%d%d",&a,&b,&len);
97 p=(T*)malloc(sizeof(T));
98 p->end=b;
99 p->len=len;
100 p->next=s[a].next;
101 s[a].next=p;
102 q=(T*)malloc(sizeof(T));
103 q->end=a;
104 q->len=len;
105 q->next=s[b].next;
106 s[b].next=q;
107 }
108 dijkstra(2);
109 printf("%d\n",dfs(1));
110 }
111 return 0;
112 }
113