【最短路】 HDOJ 4885 TIANKENG’s travel

题目中要求每经过一个加油站就必须加油,所以每两个点中间不存在加油站(三点共线)就连一条权值为1的边。。。。实现的时候可以先对X轴排序,然后用set判断向量。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 1005
#define maxm 2000005
#define eps 1e-10
#define mod 1000000009
#define INF 99999999
#define lowbit(x) (x&(-x))  
#define pii pair<LL, LL>
#define mp(a, b) make_pair(a, b)
//#define lson o<<1, L, mid  
//#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
using namespace std;

int h[maxn], next[maxm], v[maxm];
struct point
{
	int x, y;
	int id;
}p[maxn];
int n;
LL l;
set<pii> save;
int done[maxn], dis[maxn];
struct node
{
	int u, d;
	bool operator < (const node &a) const {
		return a.d<d;
	}
}now, tmp;
priority_queue<node> q;

int cmp(point a, point b)
{
	if(a.x == b.x) return a.y<b.y;
	else return a.x<b.x;
}
void init(void)
{
	memset(h, -1, sizeof h);
	memset(done, 0, sizeof done);
}
void read(void)
{
	scanf("%d%I64d", &n, &l);
	l *= l;
	scanf("%d%d", &p[0].x, &p[0].y);
	p[0].id = 0;
	scanf("%d%d", &p[n+1].x, &p[n+1].y);
	p[n+1].id = n+1;
	for(int i = 1; i <= n; i++) {
		scanf("%d%d", &p[i].x, &p[i].y);
		p[i].id = i;
	}
}
bool dist(int a, int b)
{
	LL ll = (LL)(p[a].x-p[b].x)*(p[a].x-p[b].x);
	ll += (LL)(p[a].y-p[b].y)*(p[a].y-p[b].y);
	if(ll > l) return true;
	return false;
}
LL gcd(LL a, LL b)
{
	if(!b) return a;
	else return gcd(b, a%b);
}
void work(void)
{
	int xx, yy, g, cnt = 0, i, j;
	sort(p, p+n+2, cmp);
	for(i = 0; i <= n+1; i++) {
		save.clear();
		for(j = i+1; j <= n+1; j++) {
			if(dist(i, j)) continue;
			xx = p[j].x - p[i].x;
			yy = p[j].y - p[i].y;
			g = gcd(xx, yy);
			xx/=g, yy/=g;
			if(save.find(mp(xx, yy)) == save.end()) {
				save.insert(mp(xx, yy));
				next[cnt] = h[p[i].id], h[p[i].id] = cnt, v[cnt] = p[j].id, cnt++;
				next[cnt] = h[p[j].id], h[p[j].id] = cnt, v[cnt] = p[i].id, cnt++;
			}
		}
	}
}
void dijstra(int s)
{
	for(int i = 0; i <= n+1; i++) dis[i] = INF;
	now.u = s, now.d = 0, dis[s] = 0, q.push(now);
	while(!q.empty()) {
		now = q.top();
		q.pop();
		if(done[now.u]) continue;
		done[now.u] = 1;
		for(int e = h[now.u]; ~e; e = next[e])
			if(dis[v[e]] > dis[now.u] + 1) {
				dis[v[e]] = dis[now.u] + 1;
				tmp.u = v[e], tmp.d = dis[v[e]];
				q.push(tmp);
			}
	}
	
	if(dis[n+1] == INF) printf("impossible\n");
	else printf("%d\n", dis[n+1]-1);
}
int main(void)
{
	int _;
	while(scanf("%d", &_)!=EOF) {
		while(_--) {
			init();
			read();
			work();
			dijstra(0);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值