#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stack>
#include <queue>
#define flush(arr,i) memset(arr,i,sizeof(arr))
using namespace std;
const int maxn=1010;
int n,cur,m;
struct Edge
{
int next,to,cost;
};
//边集
Edge edges[maxn];
//head[i]表示以i为起始点的边的开始编号
int head[maxn];
/*
for(int i=1;i<=sz;i++)
{
scanf("%d%d%d",&x,&y,&w);
edges[cur].cost=w;
edges[cur].to=y;
//向上垒砌
edges[cur].next=head[x];
//更新位置
head[x]=cur;
cur++;
}
*/
void input(int sz)
{
int x,y,w;
for(int i=1;i<sz;i++)
{
scanf("%d%d%d",&x,&y,&w);
edges[cur].to=y;
edges[cur].cost=w;
edges[cur].next=head[x];
head[x]=cur;
cur++;
}
}
void showMap()
{
for(int i=1;i<=n;i++)
{
for(int j=head[i];j!=-1;j=edges[j].next)
printf("%d-%d : %d\n",i,edges[j].to,edges[j].cost);
}
}
int main()
{
freopen("data.txt","r",stdin);
flush(head,-1);
cur=1;
scanf("%d%d",&n,&m);
input(m);
showMap();
return 0;
}
下面基于链式前向星复习一下广搜和深搜:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stack>
#include <queue>
#define flush(arr,i) memset(arr,i,sizeof(arr))
using namespace std;
const int maxn=110;
queue<int> q;
int head[maxn], to[maxn], nxt[maxn], n, cur;
bool vis[maxn];
/*
DFS >>...
BFS >>...
链式前向星
*/
void insertEdge(int x, int y)
{
to[cur] = y;
nxt[cur] = head[x];
head[x] = cur++;
}
void BFS(int s)
{
while(!q.empty())
q.pop();
vis[s] = true;
q.push(s);
printf("%d ", s);
int cur;
while(!q.empty())
{
cur = q.front();
q.pop();
for(int i = head[cur]; i != -1; i = nxt[i])
{
if(!vis[to[i]])
{
q.push(to[i]);
printf("%d ", to[i]);
}
}
}
printf("\n");
}
void DFS(int s)
{
vis[s] = true;
printf("%d ", s);
for(int i = head[s]; i != -1; i = nxt[i])
{
if(!vis[to[i]])
DFS( to[i] );
}
}
int main()
{
freopen("data.txt","r",stdin);
int x, y, root;
while(scanf("%d%d", &n, &root)!=EOF)
{
cur = 0;
flush(vis, 0), flush(head, -1);
while(n--)
{
scanf("%d%d", &x, &y);
insertEdge(x, y);
}
BFS(root);
flush(vis, 0);
DFS(root);
}
return 0;
}