dfs 遍历 codeforces 24A

//题目中明确说了,这是一个环,要充分利用性质

//答案一定是在从1出发的两条路径中的一条,如果当前边反向,则更新当前值,最后答案就是两条路径中小的

//dfs时,记录父亲节点,这样就可以避免在向下一步走的时候,又回到了父亲

/*************************************************************************
    > File Name: 24A.cpp
    > Author: flyasdfvcxz
    > Mail: [email protected] 
    > Created Time: Fri 07 Nov 2014 08:10:08 PM CST
 ************************************************************************/

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define ll long long
using namespace std;
const int N = 110;
int n, cur, ans;
int g[N][N];
void dfs(int x, int sum, int fa)
{
	//cout << " x = " << x << " sum = " << sum << endl;
	if (x == 1)
	{
		++cur;
		if (cur > 1) 
		{
			ans = min(ans, sum);
			return;
		}
	}
	for (int i = 1; i <= n; ++i)
	{
		if (i == fa) continue;
		if (g[x][i])
		{
			dfs(i, sum, x);
		}
		else if (g[i][x])
		{
			dfs(i, sum + g[i][x], x);
		}
	}
}
int main()
{
	//freopen("in.txt", "r", stdin);
	while (cin >> n)
	{
		memset(g, 0, sizeof(g));
		for (int i = 1; i <= n; ++i)
		{
			int a, b, c;
			cin >> a >> b >> c;
			g[a][b] = c;
		}
		ans = 1e9;
		cur = 0;
		dfs(1, 0, -1);
		cout << ans << endl;
	}
	return 0;
}


你可能感兴趣的:(ACM)