試題 歷屆試題 網絡尋路
問題描述
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 count = 0;
void Init(int n);
void Insert(int n, int x);
void dfs(int x, int n, int start);
int main()
{
int n, m, u, v, i;
scanf("%d%d", &n, &m); // n表示結點個數,m表示連接線路的條數
Init(n);
while(m--) //輸入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", count);
return 0;
}
//x爲當前找的結點,n爲第幾個結點,s爲開始的結點即start
void dfs(int x, int n, int start)
{
visit[x]=1;
struct Node *p = &tab[x];
if(n>=3)
{
count++;
return ;
}
while((p=p->pNext)!=NULL)
{
if((visit[p->data])!=1 || (p->data==start&&n==2)) //如果結點沒訪問過,或者是閉環的最後一步
{
dfs(p->data, n+1, start);
if(p->data!=start)
{
visit[p->data]=0; //當是閉環時,即最後一個點是s時,不用置0,因爲總是從start爲起點,start一直被標記爲訪問過
}
}
}
}
void Init(int n)
{
int i;
for(i=1; i<=n; i++)
{
tab[i].data=i;
tab[i].pNext=NULL;
}
}
// 在n後面接上x,如果n後面已經接了,就先找到n最後一個,再接上去
void Insert(int n, int x)
{
struct Node *p = &tab[n];
while(p->pNext!=NULL)
{
p=p->pNext;
}
struct Node *ss;
ss=(struct Node*)malloc(sizeof(struct Node));
p->pNext = ss;
ss->data = x;
ss->pNext = NULL;
}