结构体存储
1 struct Edge 2 { 3 int to,val,next; 4 }edge[maxn]; 5 int head[maxn]; 6 void addedge(int x,int y,int val) 7 { 8 edge[++cnt].to=y; 9 edge[cnt].val=val; 10 edge[cnt].next=head[x]; 11 head[x]=cnt; 12 }
调用
1 void use(int x){ 2 int u=x;//x为头结点; 3 for(int i=head[u];i!=-1;i=E[i].next){ 4 v=E[i].to; 5 6 } 7 }
vector存储
1 #include <cstdio> 2 #include <vector> 3 struct edge{ 4 int v,w; 5 edge(int _v,int _w){ 6 v=_v;w=_w; 7 } 8 }; 9 vector <edge> g[maxn]; 10 void add(int x,int y,int z){ 11 g[x].push_back(edge(y,z)); 12 }
调用
1 void use(int x){ 2 int ans=g[x].size(); 3 for(int i=0;i<ans;i++){ 4 int v=g[x][i].v; 5 6 } 7 }
数组模拟
1 const int maxn = 1e5+10; 2 const int maxr = 2e5+10; 3 int index = 1, to[maxn], w[maxn], pre[maxn], p1[maxn]; 4 //插入 5 int x, y, z; 6 for(int i = 0; i < n; ++i){ 7 scanf("%d%d%d", &x, &y, &z); 8 to[index] = y, w[index] = z, pre[index] = p[x], p[x] = index++; 9 } 10 11 //遍历 12 for(int i = p[v]; i; i = pre[i]){ 13 int vv = to1[i], ww = w[i]; 14 }
----------------------------------------------------------
例题:一般与搜索一起用
南洋理工 --吝啬的国度 http://acm.nyist.net/JudgeOnline/problem.php?pid=20
vector(动态数组) 好用
上代码
1 #include <iostream> 2 #include <string.h> 3 #include <vector> 4 #include <algorithm> 5 using namespace std; 6 const int maxn = 1e5+10; 7 vector<int> v[maxn]; 8 int a[maxn]; 9 void dfs(int x){ 10 for(int i = 0; i < v[x].size(); i++){ 11 if(!a[v[x][i]]) a[v[x][i]] = x, dfs(v[x][i]); 12 } 13 } 14 int main(){ 15 // freopen("in.txt", "r", stdin); 16 // freopen("out.txt", "w", stdout); 17 int t,n,m,p,q; 18 cin>>t; 19 while(t--){ 20 cin>>n>>m; 21 for(int i = 0; i < n-1; i++){ 22 cin>>p>>q; 23 v[p].push_back(q); 24 v[q].push_back(p); 25 } 26 dfs(m); 27 a[m]=-1; 28 for(int i = 1; i <= n; i++){ 29 if(i != 1) cout<<" "; 30 cout<<a[i]; 31 } 32 cout<<endl; 33 memset(v,0,sizeof(v)); 34 memset(a,0,sizeof(a)); 35 } 36 return 0; 37 }
hdu 2586 :http://acm.split.hdu.edu.cn/showproblem.php?pid=2586
1 #include <iostream> 2 #include <string.h> 3 #include <vector> 4 #include <algorithm> 5 using namespace std; 6 const int maxn = 1e5+10; 7 vector<int> v[maxn]; 8 vector<int> vn[maxn]; 9 int a[maxn]; 10 int dfs(int x, int y, int sum){ 11 for(int i = 0; i < v[x].size(); i++){ 12 // cout<<sum<<endl; 13 if(v[x][i] == y) {cout<<sum+vn[x][i]<<endl; return 0;} 14 else if(!a[v[x][i]]) 15 a[v[x][i]] = 1, dfs(v[x][i], y, sum+vn[x][i]); 16 } 17 } 18 int main(){ 19 // freopen("in.txt", "r", stdin); 20 // freopen("out.txt", "w", stdout); 21 int n, flag = 0; 22 cin>>n; 23 while(n--){ 24 if(flag) cout<<endl; 25 memset(v, 0, sizeof(v)); 26 memset(vn, 0, sizeof(vn)); 27 int x, y, p, q, r; 28 cin>>x>>y; 29 for(int i = 0; i < x-1; i++){ 30 cin>>p>>q>>r; 31 v[p].push_back(q); 32 vn[p].push_back(r); 33 v[q].push_back(p); 34 vn[q].push_back(r); 35 } 36 for(int i = 0; i < y; i++){ 37 memset(a, 0, sizeof(a)); 38 cin>>p>>q; 39 a[p] = 1; 40 dfs(p, q, 0); 41 } 42 flag = 1; 43 } 44 return 0; 45 }
只有不断学习才能进步!