FAFU OJ 寻路问题

85 阅读1分钟

寻路问题

Time Limit:2000MSMemory Limit:65536KB
Total Submissions:183Accepted:89

Share

Description:

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

如: 
1 -> 2 -> 3 -> 1或1->2->3->4是合法的(刚好经过两个不同的结点) ,而 
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:

3 3

1 2

2 3

1 3

Sample Output:

6

Source:

#include<stdio.h>
#include<vector>
using namespace std;
const int N=10005;
int ans=0;
int mark[N];
vector<int>G[N];
void dfs(int cur,int x,int start)
{
	if(cur==3)
		ans++;
	else
	{
		for(int i=0;i<G[x].size();i++)
		{
			int y=G[x][i];
			if(cur==2&&y==start)
			{
				ans++;
			}
			else if(!mark[y])
			{
				mark[y]=true;
				dfs(cur+1,y,start);
				mark[y]=false;
			}
		}
	}
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	while(m--)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		G[a].push_back(b);
		G[b].push_back(a);
	}

	int i;
	for(i=1;i<=n;i++)
	{
		mark[i]=true;
		dfs(0,i,i);
		mark[i]=false;
	}
	printf("%d",ans);
	return 0;
}


\

\