【ZJOI 2002】 昂贵的聘礼

【题目链接】

            点击打开链接

【算法】

          最短路,注意不能用dijkstra,要用SPFA

【代码】

           

#include <algorithm>
#include <bitset>
#include <cctype>
#include <cerrno>
#include <clocale>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <limits>
#include <list>
#include <map>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <utility>
#include <vector>
#include <cwchar>
#include <cwctype>
#include <stack>
#include <limits.h>
using namespace std;
#define MAXN 100

typedef long long LL;

LL i,M,N,x,t,v,ans,p;
LL dist[MAXN+10],vis[MAXN+10],level[MAXN+10];
vector<pair<LL,LL> > E[MAXN+10];

template <typename T> void read(T &x) {
        int f=1; char c = getchar(); x=0;
        for (; !isdigit(c); c = getchar()) { if (c=='-') f=-1; }
        for (; isdigit(c); c = getchar()) x=x*10+c-'0';
        x*=f;
}

void spfa(int low,int high) {
        int i,to,cost;
        queue<LL> q;
        memset(vis,0,sizeof(vis));
        for (i = 1; i <= N; i++) dist[i] = 2e9;
        dist[0] = 0; vis[0] = 1;
        q.push(0);
        while (!q.empty()) {
                x = q.front(); q.pop();
                vis[x] = 0;
                for (i = 0; i < E[x].size(); i++) {
                        to = E[x][i].first;
                        cost = E[x][i].second;
                        if ((level[to] >= low) && (level[to] <= high)) {
                                if (dist[x] + cost < dist[to]) {
                                        dist[to] = dist[x] + cost;
                                        if (!vis[to]) {
                                                vis[to] = 1;
                                                q.push(to);
                                        }
                                }
                        }
                }
        }    
}

int main() {
        
        read(M); read(N);
        for (i = 1; i <= N; i++) {
                read(p); read(level[i]); read(x);
                E[0].push_back(make_pair(i,p));
                while (x--) {
                        read(t); read(v);
                        E[t].push_back(make_pair(i,v));
                }    
        }
        
        ans = 2e9;
        for (i = level[1] - M; i <= level[1]; i++) {
                spfa(i,i+M);    
                ans = min(ans,dist[1]);
        }
        
        cout<< ans << endl;
        
        return 0;
    
}

 

posted @ 2018-03-24 09:55  evenbao  阅读(95)  评论(0编辑  收藏  举报