前向星是一种用来存储图的数据结构。它的构造方式很简单,读入每条边的信息,然后存到数组中,然后将数组排序,排序方法是按照起点顺序排序,若起点相同则按终点顺序排序,如果终点相同则按权重排序(如果有权重)。另外,为了方便查询,会用一个数组head[]存储起点为v的第一条边的位置。
具体实现方法如下:
const int maxn=100+10;
const int maxm=1000+10;
int head[maxn]; //存储起点为i的第一条边的位置
int n,m;
struct NODE
{
int from; //起点
int to; //终点
bool operator < (const NODE & a) const
{
return (from==a.from&&to<a.to)||from<a.from;
}
};
NODE edge[maxm];
void Init()
{
for(int i=0;i<m;++i) //读入数据
cin>>edge[i].from>>edge[i].to;
sort(edge,edge+m); //排序
memset(head,-1,sizeof(head));
head[edge[0].from]=0;
for(int i=1;i<m;++i)
if(edge[i].from!=edge[i-1].from) head[edge[i].from]=i;
}
void solve() //遍历整个图
{
for(in