Node:链式前向星

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值