藍橋杯:網路尋路
阿新 • • 發佈:2018-12-27
問題描述
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 31 2
2 3
1 3 樣例輸出1 6 樣例輸入2 4 4
1 2
2 3
3 1
1 4 樣例輸出2 10
Thinking:
易知,
第一步:構造無向圖,我這裡選擇了vector作為container,因為不用經過繁瑣的插入刪除,所以vector為首選。
第二步:在所建立的圖上進行搜尋。依題意,對於每一個vertex,搜尋深度為3層,且在執行一次新的搜尋時,不能搜尋最近一次搜過的vertex。當搜尋深度到達第三層,滿足題意的路徑數+1,之後return。
#include<iostream> #include<vector> using namespace std; int counter=0; //preNode:Previous Node ; curNode: Current Node void dfs(int preNode,int curNode,vector<int>*edge,int step) { if(step==3)//當搜尋深度達到三層 { counter++; return; } if(edge[curNode].size()!=0)//若當前vertex存在相連的vertex { vector<int>::iterator it; for(it=edge[curNode].begin();it!=edge[curNode].end();it++) { if(*it!=preNode)//不能搜尋最近一次搜尋過的vertex { dfs(curNode,*it,edge,step+1);//dfs } } } } int main() { int nVertex,nEdge,i,from,to; cin>>nVertex>>nEdge; vector<int>*edge=new vector<int>[nVertex+1]; for(i=1;i<=nEdge;i++) { cin>>from>>to; edge[from].push_back(to);//構造無向圖,from可以到to edge[to].push_back(from);//to也可以到from } for(i=1;i<=nVertex;i++)//對所有vertex進行dfs { dfs(0,i,edge,0); } cout<<counter<<endl; return 0; }