BZOJ 2763 飞行路线(spfa+分层图)

来源:互联网 发布:旅游景点数据库 编辑:程序博客网 时间:2024/05/21 11:26

Description
Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多k种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?
Input
数据的第一行有三个整数,n,m,k,分别表示城市数,航线数和免费乘坐次数。
第二行有两个整数,s,t,分别表示他们出行的起点城市编号和终点城市编号。(0<=s,t < n)
接下来有m行,每行三个整数,a,b,c,表示存在一种航线,能从城市a到达城市b,或从城市b到达城市a,价格为c。(0<=a,b< n,a与b不相等,0<=c<=1000)

Output

只有一行,包含一个整数,为最少花费。
Sample Input
5 6 1
0 4
0 1 5
1 2 5
2 3 5
3 4 5
2 3 3
0 2 100

Sample Output
8

Hint
对于30%的数据,2<=n<=50,1<=m<=300,k=0;

对于50%的数据,2<=n<=600,1<=m<=6000,0<=k<=1;

对于100%的数据,2<=n<=10000,1<=m<=50000,0<=k<=10.


这个题依旧是spfa,但是加了分层图,就是对使用免费与不使用免费进行分类讨论(要保证可以使用,应再用一个变量对已经使用的免费次数进行记录)。开一个二维数组d[ ][ ],用第二维来记录花费(免费次数)。刚开始的时候想的过于简单,是想对输入的花费进行比较,讨论,如果可以使用免费就把花费最大值直接初始化为0,但是发现不太会打。。。QAQ 但是,这样会有一个问题,就是你所初始化的数不一定是走的路径花费,显然,这是错误的。以后得做题前好好理理思路!!!一上午就这么浪费了。。。

已然泪奔的我,代码见下:

#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;const int MAXN = 100000;struct dqs{    int f, t, c;}hh[MAXN <<2];   //c++中<<1是 指*2int first[MAXN], next[MAXN], tot, d[MAXN][23], n, m, k;bool used[MAXN][23];queue < int > q; void build(int f, int t, int c){    hh[++tot]=(dqs){f,t,c};    next[tot] = first[f];    first[f] = tot;}void spfa(int s){    d[s][0] = 0;    q.push(s);    q.push(0);    used[s][0] = 1;    while(!q.empty())    {        int x = q.front();        q.pop();        int cs = q.front();  //cs=次数        q.pop();        used[x][cs] = 0;        for(int i = first[x]; i != -1; i = next[i])        {            int u = hh[i].t;            if(d[u][cs] > d[x][cs] + hh[i].c)            {                d[u][cs] = d[x][cs] + hh[i].c;                if(!used[u][cs])                {                    q.push(u);                    q.push(cs);                    used[u][cs] = 1;                }            }            if(cs < k)            {                if(d[u][cs + 1] > d[x][cs])                {                    d[u][cs + 1] = d[x][cs];                    if(!used[u][cs + 1])                    {                        q.push(u);                        q.push((cs + 1));                        used[u][cs + 1] = 1;                    }                                   }            }        }    }}int main(){    int s, e;    scanf("%d%d%d", &n, &m, &k);    memset(first, -1, sizeof(first));    scanf("%d%d", &s, &e);    for(int i = 1; i <= m; i++)    {        int a, b, c;        scanf("%d%d%d", &a, &b, &c);        build(a, b, c);        build(b, a, c);    }    for(int i = 0; i < n; i++)        for(int  j = 0; j <= k; j++)            d[i][j] = 21474836;    //初始化    spfa(s);    cout<<d[e][k];    return 0;}
1 0
原创粉丝点击