洛谷 SP338 ROADS - Roads 题解

思路

dfs(只不过要用邻接表存)邻接表是由表头结点和表结点两部分组成,其中表头结点存储图的各顶点,表结点用单向链表存储表头结点所对应顶点的相邻顶点(也就是表示了图的边)。在有向图里表示表头结点指向其它结点(a->b),无向图则表示与表头结点相邻的所有结点(a—b)

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 const int N = 1010;
 6 const int INF = 1e6;
 7 
 8 struct node {
 9     int s,e,len,cost;
10     int nxt;
11 } cc[10*N];
12 
13 int n,m,num,head[N],vis[N];
14 int ans;
15 //插入一条边 
16 void cr(int a,int b,int c,int d) {
17     cc[num].s=a;
18     cc[num].e=b;
19     cc[num].len=c;
20     cc[num].cost=d;
21     cc[num].nxt=head[a];//让插入的元素指向下一个 
22     head[a]=num++;//让之前的指向插入的 
23 }
24 //x表示当前的起点,y表示走过路径的长度,z表示当前的总费用 
25 void dfs(int x,int y,int z) {
26     if(y>ans)return;
27     if(x==n && z>=0 && y<ans) ans=y;
28     for(int i=head[x]; i!=-1; i=cc[i].nxt) {
29         int u=cc[i].e;
30         if(!vis[u] && z >= cc[i].cost) {
31             vis[u]=1;
32             dfs(u,y+cc[i].len,z-cc[i].cost);
33             vis[u]=0;
34         }
35     }
36 }
37 
38 int main() {
39     int i,a,b,c,d,k;
40     int yyy;
41     cin>>yyy;
42     while(yyy--) {
43         cin>>k>>n>>m;
44         num=0;
45         memset(head,-1,sizeof(head));
46         for(i=0; i<m; i++) {
47             scanf("%d%d%d%d",&a,&b,&c,&d);
48             cr(a,b,c,d);
49         }
50         ans=INF;
51         memset(vis,0,sizeof(vis));
52         dfs(1,0,k);
53 //      printf(ans<INF?"%d\n":"-1\n",ans);
54         if(ans<INF)cout<<ans<<endl;
55         else cout<<-1<<endl;
56     }
57 
58     return 0;
59 }
请各位大佬斧正(反正我不认识斧正是什么意思)

 

posted @ 2019-07-24 13:24  handsome_zyc  阅读(243)  评论(0编辑  收藏  举报