【并查集+枚举】杭电 hdu 1598 find the most comfortable road

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

    URL   : http://acm.hdu.edu.cn/showproblem.php?pid=1598
    Name  : 1598 find the most comfortable road

    Date  : Monday, January 23, 2012
    Time Stage : 2.5 hours

    Result: 
5287995	2012-01-23 16:23:56	Accepted	1598
265MS	220K	1916 B
C++	pyy


Test Data :

Review :
枚举+并查集。
这题放在最短路的专题里,最短路实在不会,只好百度一下了。
牛人解题报告:
http://www.cnblogs.com/mrlai/archive/2011/03/31/2001405.html
http://blog.csdn.net/zxddavy/article/details/6612324
//----------------------------------------------------------------------------*/

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>

#include <iostream>
#include <string>
#include <queue>
#include <algorithm>

using namespace std ;

#define INF        (-1)
#define MAXN       1002

typedef __int64    LL ;

#define min(x, y)    ((x) &lt; (y) ? (x) : (y))
#define max(x, y)    ((x) &gt; (y) ? (x) : (y))
#define MEM(a, v)    memset (a, v, sizeof (a))

struct SARS {
	int s, e, c ;
	bool operator&lt; (const SARS &amp;s)
	{
		return c &lt; s.c ;
	}
};

bool    used[MAXN] ;

int			n, m, q ;
int			set[MAXN] ;

SARS		map[MAXN] ;

int find (int x)
{
	while (set[x] != x)
		x = set[x] ;
	return x ;
}

int main ()
{
    int i, j ;
    int x, y, c ;
    int res ;

    while (~scanf ("%d%d", &amp;n, &amp;m))
    {
        MEM (map, INF) ;
        for (i = 0 ; i &lt; m ; ++i)
        {
            scanf ("%d%d%d", &amp;map[i].s, &amp;map[i].e , &amp;map[i].c) ;
        }
		sort (map, map+m) ;
        scanf ("%d", &amp;q) ;
        while (q--)
        {
            scanf ("%d%d", &amp;x, &amp;y) ;

			res = INF ;
			for (i = m-1 ; i &gt;= 0 ; --i)
			{
				for (j = 0 ; j &lt; m ; ++j)
					set[j] = j ;
				for (j = i ; j &gt;= 0 ; --j)
				{
					int xx = find (map[j].s) ;
					int yy = find (map[j].e) ;
					if (xx != yy)
						set[xx] = set[yy] ;
					if (find (x) == find (y))
					{
						if (res == INF || res &gt; map[i].c - map[j].c)
						{
							res = map[i].c - map[j].c ;
						}
						break ;
					}
				}
			}
			printf ("%d\n", res) ;
        }
    }
    return 0 ;
}

</algorithm></queue></string></iostream></cmath></cstdlib></cstring></cstdio>

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