您的位置:首页 > 其它

Bus System hdu 1690 (最短路 + long long int 处理)

2010-07-05 13:01 861 查看
/*
这个题目很简单,只是数据比较大所以用long long int ,一开始没有注意这个,以为是自己的BFS写错了,后来又用了
Floyd写还是错了。错了很多回的时候终于AC,多亏了xwc在回来的路上提醒了下,回来的时候灵感一来就过了
跟着他真的学到了很多,但是我很多细节的地方还是非常需要注意的,这个暑假一直在继续。。。
在审视题目的时候一定要注意数据的范围
求很多两点的最短路的时候Floyd效率高
*/

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

const long long int INF = 0x7fffffffffffff;//一开始这里数据定义太小,一直wrong
const int N = 105;
long long int dis
;
long long int cost

;
long long int L
;
long long int C
;
long long int X
;
bool hash
;

struct node
{
int num;
long long int dis;//这里要定义这个,最短路可能会很大
friend bool operator < (node a, node b)
{
return a.dis > b.dis;
}
};

long long int distance(long long int a)
{
if(a < 0)
a = -a;
if(a == 0)
return 0;
if(a > 0 && a <= L[1])
return C[1];
if(a > L[1] && a <= L[2])
return C[2];
if(a > L[2] && a <= L[3])
return C[3];
if(a > L[3] && a <= L[4])
return C[4];
else
return INF;
}

long long int BFS(int s, int e, int n)
{//2570982 2010-07-05 12:36:46 Accepted 1690 62MS 284K 2787 B C++ 悔惜晟
node P, M;
priority_queue<node> Q;
memset(hash, false, sizeof(hash));
for(int i = 1; i <= n; i++)
{
dis[i] = cost[s][i];
if(cost[s][i] != INF && s != i)
{
P.num = i;
P.dis = dis[i];
Q.push(P);
}
}
hash[s] = true;
while(!Q.empty())
{
M = Q.top();
Q.pop();
if(hash[e])
break;
hash[M.num] = true;
for (int i = 1; i <= n; i++)
{
if(!hash[i] && dis[i] > M.dis + cost[M.num][i] && cost[M.num][i] != INF)
{
dis[i] = M.dis + cost[M.num][i];
P.num = i;
P.dis = dis[i];
Q.push(P);
}
}
}
return dis[e];
}

void Floyd(int n)
{//2570982 2010-07-05 12:36:46 Accepted 1690 62MS 284K 2787 B C++ 悔惜晟
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
for(int k = 1; k <= n; k++)
{
if(cost[j][k] > cost[j][i] + cost[i][k] && cost[j][i] != INF && cost[i][k] !=INF)
cost[j][k] = cost[j][i] + cost[i][k];
}
}
int main()
{
int n, m, t;
int T = 1;
scanf("%d", &t);
while(t--)
{
for(int i = 1; i <= 4; i++)
scanf("%I64d", &L[i]);
for(int i = 1; i <= 4; i++)
scanf("%I64d", &C[i]);
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%I64d", &X[i]);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
if(i == j)
cost[i][j] = 0;
else
cost[i][j] = INF;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
long long int a = (long long int)fabs(1.0 * X[i] - X[j]);
//long long int a = X[i] - X[j];
long long int b = distance(a);
cost[i][j] = cost[j][i] = b;
}
int st, en;
long long int sum;
Floyd(n);
printf("Case %d:/n", T++);
while(m--)
{
scanf("%d %d", &st, &en);
sum = BFS(st, en, n);
//sum = cost[st][en];

if(sum == INF)
printf("Station %d and station %d are not attainable./n", st, en);
else
printf("The minimum cost between station %d and station %d is %I64d./n", st, en, sum);

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  system distance struct c 2010