历届试题 网络寻路

历届试题 网络寻路  
时间限制:1.0s   内存限制:256.0MB
      
问题描述

X 国的一个网络使用若干条线路连接若干个节点。节点间的通信是双向的。某重要数据包,为了安全起见,必须恰好被转发两次到达目的地。该包可能在任意一个节点产生,我们需要知道该网络中一共有多少种不同的转发路径。

源地址和目标地址可以相同,但中间节点必须不同。

如下图所示的网络。

1 -> 2 -> 3 -> 1 是允许的

1 -> 2 -> 1 -> 2 或者 1 -> 2 -> 3 -> 2 都是非法的。

输入格式

输入数据的第一行为两个整数N M,分别表示节点个数和连接线路的条数(1<=N<=10000; 0<=M<=100000)。

接下去有M行,每行为两个整数 u 和 v,表示节点u 和 v 联通(1<=u,v<=N , u!=v)。

输入数据保证任意两点最多只有一条边连接,并且没有自己连自己的边,即不存在重边和自环。

输出格式
输出一个整数,表示满足要求的路径条数。
样例输入1
3 3
1 2
2 3
1 3
样例输出1
6
样例输入2
4 4
1 2
2 3
3 1
1 4
样例输出2
10

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node
{
    int data;
    struct Node *pNext;
};
struct Node tab[10001];
int visit[10001]={0};
int way[10001]={0};
int cnt=0;
void Insert(int n,int x);
void Init(int n);
void dfs(int x,int n,int s);
int main()
{
    int n,m,u,v,i;
    scanf("%d%d",&n,&m);
    Init(n);
    while(m--)
    {
        scanf("%d%d",&u,&v);
        Insert(u,v);
        Insert(v,u);
    }
    for(i=1;i<=n;i++)
    {
        memset(visit,0,sizeof(int)*n);
        dfs(i,0,i);
    }
    printf("%d\n",cnt);
    return 0;
}
void dfs(int x,int n,int s)
{
    visit[x]=1;
    way[n]=x;
    struct Node *p=&tab[x];
    if(n>=3)
    {
        cnt++;
        return ;
    }
    while((p=p->pNext)!=NULL)
    {
        if((visit[p->data]!=1)||(p->data==s&&n==2))
        {
            dfs(p->data,n+1,s);
            if(p->data!=s)
            {
                visit[p->data]=0;
            }
            
        }
    }
}
void Init(int n)
{
    int i;
    for(i=1;i<=n;i++)
    {
        tab[i].data=i;
        tab[i].pNext=NULL;
    }
}
void Insert(int n,int x)
{
    struct Node *p=&tab[n];
    while(p->pNext!=NULL)
    {
        p=p->pNext;
    }
    struct Node *new=(struct Node *)malloc(sizeof(struct Node));
    p->pNext=new;
    new->data=x;
    new->pNext=NULL;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值