codeforces 366D 分类: codeforces 2015-08-09 17:38 9人阅读 评论(0) 收藏


很有趣的题啊,首先要知道从 1 开始,只走一条路径到达 n 的数字一定是连续的区间,

先枚举确定答案 L,再通过拓扑排序 DP 计算最大的 R (DP过程中确定无向边的方向),

当然我直接写了一个 SPFA 来更新 DP 值,然后就 AC 了~

SPFA期望复杂度 : O(n+m)

时间复杂度:O(m(n+m))


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <utility>
#include <iostream>
#include <algorithm>

template<class Num>void read(Num &x)
{
    char c; int flag = 1;
    while((c = getchar()) < '0' || c > '9')
        if(c == '-') flag *= -1;
    x = c - '0';
    while((c = getchar()) >= '0' && c <= '9')
        x = (x<<3) + (x<<1) + (c-'0');
    x *= flag;
    return;
}
template<class Num>void write(Num x)
{
    if(x < 0) putchar('-'), x = -x;
    static char s[20];int sl = 0;
    while(x) s[sl++] = x%10 + '0',x /= 10;
    if(!sl) {putchar('0');return;}
    while(sl) putchar(s[--sl]);
}

const int maxn = 1005, maxm = 3005, INF = 0x3f3f3f3f;

struct Edge
{
    int v, l, r, next;
    Edge(int v = 0,int l = 0,int r = 0,int next = 0):v(v),l(l),r(r),next(next){}
}edge[maxm<<1];

int head[maxn], el;

void NewEdge(int u,int v,int l,int r)
{
    edge[++el] = Edge(v, l, r, head[u]), head[u] = el;
}

int n, m, ans, st;

void init()
{
    int u, v, l, r;

    read(n), read(m);

    for(int i = 1; i <= m; i++)
    {
        read(u), read(v), read(l), read(r);
        NewEdge(u, v, l, r), NewEdge(v, u, l, r);
    }
}
int SPFA(int L)
{
    static int line[maxn], dist[maxn];  
    static bool hash[maxn];

    int f = 0, r = 0;

    for(int i = 1; i <= n; i++) dist[i] = 0;

    dist[1] = INF, line[r] = 1, r = (r + 1)%maxn;
    hash[1] = true;

    while(f != r)
    {
        int x = line[f];
        f = (f + 1)%maxn, hash[x] = false;

        for(int i = head[x]; i; i = edge[i].next)
        {
            if(edge[i].l > L) continue;

            int t = std::min(edge[i].r - L + 1, dist[x]), p = edge[i].v;

            if(t > dist[p])
            {
                dist[p] = t;

                if(!hash[p])
                {
                    if(dist[p] > dist[line[f]])
                        f = (f - 1 + maxn)%maxn, line[f] = p;
                    else
                        line[r] = p, r = (r + 1)%maxn;

                    hash[p] = true;
                }

            }
        }
    }

    return dist[n];
}

int lval[maxm], len;

void solve()
{
    for(int i = 1; i <= m; i++) lval[i] = edge[i<<1].l;

    std::sort(lval + 1, lval + m + 1);  
    len = std::unique(lval + 1, lval + m + 1) - (lval + 1);

    for(int i = 1; i <= len; i++)
        ans = std::max(ans, SPFA(lval[i]));

    if(!ans)
    {
        puts("Nice work, Dima!");
        return;
    }

    write(ans), puts("");
}

int main()
{

    init(), solve();

    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-09 17:38  <Dash>  阅读(145)  评论(0编辑  收藏  举报