POJ1062 昂贵的聘礼

一.题目链接:http://poj.org/problem?id=1062

二.思路:设起点为0,枚举每个区间,把超出区间的置为已访问,然后Dijkstra求出0到1的最短路,取所有区间中最短的一个。

三.代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;

const int MAX_SIZE = 102,
          INF = 1<<30,
          MOD = 1000000007;

int graph[MAX_SIZE][MAX_SIZE];
int rankGap, stuffNum;
int Rank[MAX_SIZE];

void initVisited(int l, int r, bool visited[])
{
    int i;
    for(i = 1; i <= stuffNum; i++)
        if(Rank[i] < l || Rank[i] > r)
            visited[i] = true;
}

int Dijkstra(int l, int r)
{
    bool visited[MAX_SIZE];
    int dist[MAX_SIZE], i, j, minPath, startPos;

    memset(dist, 1, sizeof(dist));
    memset(visited, 0, sizeof(visited));
    initVisited(l, r, visited);

    visited[0] = true;
    dist[0] = 0;

    for(i = 0; i <= stuffNum; i++)
        dist[i] = graph[0][i];

    for(i = 0; i < stuffNum; i++){
        minPath = INF;
        for(j = 0; j <= stuffNum; j++){
            if(minPath > dist[j] && !visited[j]){
                minPath = dist[j];
                startPos = j;
            }
        }

        visited[startPos] = true;

        for(j = 0; j <= stuffNum; j++){
            if(dist[j] > minPath + graph[startPos][j] && !visited[j])
                dist[j] = minPath + graph[startPos][j];
        }
    }
    return dist[1];
}
void printGraph(){
    for(int i = 0; i <= stuffNum; i++){
        for(int j = 0; j <= stuffNum; j++){
            if(graph[i][j] == 16843009)
                cout<<"INF ";
            else
                cout<<graph[i][j]<<" ";
        }
        cout<<endl;
    }
}
int main()
{
    //freopen("in.txt", "r", stdin);

    int i, j, beginPos, weight, pathNum;

    memset(graph, 1, sizeof(graph));

    cin>>rankGap>>stuffNum;
    for(i = 1; i <= stuffNum; i++){

        cin>>weight>>Rank[i]>>pathNum;
        graph[0][i] = weight;

        for(j = 0; j < pathNum; j++){
            cin>>beginPos>>weight;
            graph[beginPos][i] = weight;
        }
    }

    int res = INF;
    for(i = Rank[1] - rankGap; i <= Rank[1]; i++)
        res = min(res, Dijkstra(i, i + rankGap));

    cout<<res<<endl;
}


你可能感兴趣的:(POJ1062 昂贵的聘礼)