历届试题 网络寻路

  历届试题 网络寻路  
时间限制: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<iostream>
#include<cstdio>  
#include<cstdlib>  
#include<string>

#include<cstring>
using namespace std;
struct node
{
    int data;
    struct node *pnext;
};
struct node tab[10001];
int visit[1001]={0},cnt=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 *new1 = (struct node *)malloc(sizeof(struct node));
    p ->pnext = new1;
    new1 -> data = x;
    new1 -> pnext = NULL;
}

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;
            }
        }
    }
}
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);
    }
    cout<<cnt<<endl;
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/Deng1185246160/p/3600321.html