【最短路+bfs+剪枝】杭电 hdu 2433 Travel


/* THE PROGRAM IS MADE BY PYY */
/*----------------------------------------------------------------------------//
    Copyright (c) 2011 panyanyany All rights reserved.

    URL   : http://acm.hdu.edu.cn/showproblem.php?pid=2433
    Name  : 2433 Travel

    Date  : Wednesday, January 25, 2012
    Time Stage : 4 hours

    Result: 
5292805	2012-01-25 14:24:31	Accepted	2433
656MS	324K	2494 B
C++	pyy


Test Data :

Review :
不说了,直接上大牛的解题报告:
http://isomer.me/2011/08/hdu-2433-%E6%9C%80%E7%9F%AD%E8%B7%AF%E9%A2%84%E5%A4%84%E7%90%86/
http://hi.baidu.com/novosbirsk/blog/item/5c26bffbd04d4d6c034f56b7.html
//----------------------------------------------------------------------------*/

#include <cstdio>
#include <CSTRING>

#include <queue>
#include <algorithm>
#include <vector>

using namespace std ;

#define MEM(a, v)		memset (a, v, sizeof (a))	// a for address, v for value
#define max(x, y)		((x) > (y) ? (x) : (y))
#define min(x, y)		((x) < (y) ? (x) : (y))

#define INF		(0x3f3f3f3f)
#define MAXN	102

struct EDGE {
	int u, v ;
} ;

bool	used[MAXN], bCnet, bInit ;
int		n, m ;
int		dist[MAXN], map[MAXN][MAXN], sum_d[MAXN], pre[MAXN][MAXN] ;

EDGE	e[30*MAXN] ;

int bfs (int beg)
{
	int i, t ;
	queue<int>	q ;

	MEM (used, 0) ;
	MEM (dist, 0) ;

	used[beg] = 1 ;
//	dist[beg] = 0 ;
	q.push (beg) ;

	while (!q.empty ())
	{
		t = q.front() ;
		q.pop () ;

		for (i = 1 ; i <= n ; ++i)
		{
			if (!used[i] && map[t][i])
			{
				used[i] = 1 ;
				dist[i] = dist[t] + 1 ;
				// 只有要第一次 bfs 计算各边的时候才用到
				if (bInit)
					pre[beg][i] = t ;
				q.push (i) ;
			}
		}
	}
	int tmpSum = 0 ;
	// 从 beg+1 开始 和从 1 开始,效果差不多
	for (i = beg + 1 ; i <= n ; ++i)
	{
		if (!dist[i])
			return INF ;
		tmpSum += dist[i] ;
	}
	return tmpSum ;
}

int main ()
{
	int i, j ;
	int u, v, sum, res ;
	while (scanf ("%d%d", &n, &m) != EOF)
	{
		MEM (map, 0) ;
		MEM (pre, 0) ;

		for (i = 1 ; i <= m ; ++i)
		{
			scanf ("%d%d", &u, &v) ;
			e[i].u = u ;
			e[i].v = v ;
			map[u][v] = ++map[v][u] ;
		}

		sum = 0 ;
		bCnet = true ;
		bInit = true ;
		for (i = 1 ; i <= n ; ++i)
		{
			sum_d[i] = bfs (i) ;
			sum += sum_d[i] ;

			// 优化……很显然效果不大
			if (sum >= INF)
			{
				bCnet = false ;
				break ;
			}
		}
		bInit = false ;

		for (i = 1 ; i <= m ; ++i)
		{
			u = e[i].u ;
			v = e[i].v ;
			// map[u][v] 判断有无重边,可以优化300多MS
			if (bCnet && map[u][v] == 1)
			{
				res = 0 ;
				for (j = 1 ; j <= n ; ++j)
				{
					// 最重要的剪枝,否则直接超时
					if (pre[j][u] != v && pre[j][v] !=u)
						res += sum_d[j] ;
					else
					{
						--map[u][v] ;
						--map[v][u] ;
						res += bfs (j) ;
						++map[u][v] ;
						++map[v][u] ;

						if (res >= INF)
							break ;
					}
				}
			}
			else    // 一开始漏了这句,一直无限WA,气死了,思维漏洞啊!
				res = sum ;
			if (res >= INF)
				puts ("INF") ;
			else
				printf ("%d\n", res * 2) ;
		}
	}
	return 0 ;
}


你可能感兴趣的:(杭电 hdu)