这道题就是Dijkstra算法的变形,枚举等级就行了,例如酋长的等级是5,M = 2 则枚举3~5,4~6,5~7就OK了,但是,我测遍Discuss区的数据,还是WA了。。最后看到了一条“这道题的数据有问题,有些wa的程序A了,有些能A的程序WA了。。。”稍微有点心安理得。。但是还是有可能自己的程序有问题,希望有大牛能指出
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define INF 99999999
using namespace std;
struct Node
{
int cla;
int price;
};
Node node[101];
int mat[101][101];
bool visited[101];
int dist[101];
int M,n;
void Dijkstra(int clas1,int clas2)
{
int min;
for(int i = 1; i<=n; i++)
{
dist[i] = INF;
if(mat[1][i] < INF && node[i].cla >= clas1 && node[i].cla <= clas2)
dist[i] = mat[1][i] + node[i].price;
visited[i] = false;
}
visited[1] = true;
for(int i = 1 ; i < n ; i++)
{
min = INF;
int flag = -1;
for(int j = 1 ; j <= n ; j++)
{
if(!visited[j] && dist[j] < min)
{
min = dist[j];
flag = j;
}
}
if(flag == -1)
return;
visited[flag] = true;
for(int j = 1 ; j <= n; j ++)
{
if(!visited[j] && node[j].cla >= clas1 && node[j].cla <= clas2)
{
if(mat[flag][j] < INF && dist[j] > dist[flag] - node[flag].price + node[j].price + mat[flag][j])
dist[j] = dist[flag] - node[flag].price + node[j].price + mat[flag][j];
}
}
//cout<<flag<<' '<<dist[flag]<<endl;
}
}
int main()
{
scanf("%d%d",&M,&n);
int p,l,x;
int t,v;
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= n ; j++)
mat[i][j] = INF;
for(int i = 1 ; i <= n ; i++)
{
scanf("%d%d%d",&node[i].price,&node[i].cla,&x);
mat[i][i] = 0;
for(int j = 1 ; j <= x ; j++)
{
scanf("%d%d",&t,&v);
mat[i][t] = v;
}
}
int clas1,clas2;
int Min = INF;
for(int i = 0 ; i <= M; i++)
{
clas1 = node[1].cla - M + i;
clas2 = clas1 + M;
memset(visited,false,sizeof(visited));
Dijkstra(clas1,clas2);
for(int i = 1 ; i <= n ; i++)
{
//cout<<dist[i]<<' ';
if(Min > dist[i])
Min = dist[i];
}
}
cout<<Min<<endl;
return 0;
}