1. 程式人生 > >1606:歷屆試題 網路尋路

1606:歷屆試題 網路尋路

Description

X 國的一個網路使用若干條線路連線若干個節點。節點間的通訊是雙向的。某重要資料包,為了安全起見,必須恰好被轉發兩次到達目的地。該包可能在任意一個節點產生,我們需要知道該網路中一共有多少種不同的轉發路徑。

源地址和目標地址可以相同,但中間節點必須不同。

如下圖所示的網路。


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

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

Input

輸入資料的第一行為兩個整數N M,分別表示節點個數和連線線路的條數(1<=N<=10000; 0<=M<=100000)。

接下去有M行,每行為兩個整數 u 和 v,表示節點u 和 v 聯通(1<=u,v<=N , u!=v)。

輸入資料保證任意兩點最多隻有一條邊連線,並且沒有自己連自己的邊,即不存在重邊和自環。

Output

輸出一個整數,表示滿足要求的路徑條數。

Sample Input

樣例輸入1
3 3
1 2
2 3
1 3

樣例輸入2
4 4
1 2
2 3
3 1
1 4

Sample Output

樣例輸出1
6

樣例輸出2
10
import java.util.ArrayList;  
import java.util.Scanner;  
  
public class Main {
    public static int N, M;
    public static ArrayList<Integer> temp;
    public static ArrayList<Integer>[] list;
    public static long count = 0;
    
    public void dfs(int start, int father, int step) {
        if(step == 3&&(temp.get(0) != temp.get(2) && temp.get(1) != temp.get(3))) {
                count++;
            return;
        } 
        else {
            for(int i = 0;i < list[start].size();i++) {
                if(list[start].get(i) == father)//如果與之相連的是之前的那個點
                    continue;
                temp.add(list[start].get(i));
                dfs(list[start].get(i), start, step + 1);
                temp.remove(temp.size() - 1);//還原點
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Main test = new Main();
        Scanner in = new Scanner(System.in);
        N = in.nextInt();
        M = in.nextInt();
        list = new ArrayList[N + 1];
        for(int i = 1;i <= N;i++)
            list[i] = new ArrayList<Integer>();
        for(int i = 1;i <= M;i++) {
            int u = in.nextInt();
            int v = in.nextInt();
            list[u].add(v);
            list[v].add(u);
        }
        for(int i = 1;i <= N;i++) {
            temp = new ArrayList<Integer>();
            temp.add(i);
            test.dfs(i, -1, 0);
        }
        System.out.println(count);
    }
}