HDU-1598-find the most comfortable road
http://acm.hdu.edu.cn/showproblem.php?pid=1598
并查集加贪心
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
#define N 1010
#define INF 0x7fffffff
struct cam
{
int st,ed;
int speed;
}list[4*N];
int n,m;
int f[N];
void init()
{
int i;
for(i=1;i<=n;i++)
f[i]=i;
}
int find(int x)
{
int r=x;
while(f[r]!=r)
r=f[r];
f[x]=r;
return f[x];
}
void merge(int x,int y)
{
int xx,yy;
xx=find(x);
yy=find(y);
f[xx]=yy;
}
int cmp(const void *a,const void *b)
{
return (*(struct cam *)a).speed-(*(struct cam *)b).speed;
}
int main()
{
int i,j,t;
int x,y,xx,yy,ans;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=0;i<m;i++)
scanf("%d%d%d",&list[i].st,&list[i].ed,&list[i].speed);
qsort(list,m,sizeof(struct cam),cmp);
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&x,&y);
ans=INF;
for(i=0;i<m;i++)
{
init();
for(j=i;j<m;j++)
{
merge(list[j].st,list[j].ed);
if(find(x)==find(y))
{
if(ans>list[j].speed-list[i].speed)
ans=list[j].speed-list[i].speed;
break;
}
}
if(j==m)
break;
}
if(ans==INF)
printf("-1\n");
else
printf("%d\n",ans);
}
}
return 0;
}
分享到:
相关推荐
hdu-acm源代码(上百题)hdu-acm源代码、hdu-acm源代码hdu-acm源代码
算法-数塔(HDU-2084).rar
算术(HDU-6715).rar
算法-确定比赛名次(HDU-1285).rar
最短路(HDU-2544).rar
算法-命运(HDU-2571)(包含源程序).rar
算法-连连看(HDU-1175)(包含源程序).rar
算法-欧拉回路(HDU-1878)(包含源程序).rar
算法-排列2(HDU-1716)(包含源程序).rar
算法-六度分离(HDU-1869)(包含源程序).rar
算法-迷宫城堡(HDU-1269)(包含源程序).rar
算法-免费馅饼(HDU-1176)(包含源程序).rar