弄了好长时间,终于找到错误了,原来地位可以为0,另外建立的可能是非连通的图,切记。
#include<stdio.h> #include<string.h> #define INF 10000000 #define MAXN 110 int m,n,N,mi,ans,p[MAXN],rank[MAXN],w[MAXN][MAXN], d[MAXN], vis[MAXN]; void solve(int u, int v) { memset(vis, 0, sizeof(vis)); ans = INF; for(int i = 0; i <= n; i ++) d[i] = INF; d[1] = 0; for(int i = 0; i < n; i ++) { int x, min = INF; for(int y = 1; y <= n; y ++) if(rank[y] <= v && rank[y] >= u) { if(!vis[y] && d[y] <= min) min = d[x = y]; } vis[x] = 1; for(int y = 1; y <= n; y ++) if(rank[y]<=v && rank[y] >= u) { if(d[y] > d[x] + w[x][y]) d[y] = d[x] + w[x][y]; } } for(int i = 1; i <= n; i ++) if(d[i]+p[i] < ans) {ans = d[i] + p[i];} } void init() { while(~scanf("%d%d",&m,&n)) { mi = INF; memset(w,0x3f,sizeof(w)); for(int i = 1; i <= n; i ++) { scanf("%d%d%d",&p[i],&rank[i],&N); for(int j = 0; j < N; j ++) { int a,b; scanf("%d%d",&a,&b); w[i][a] = b; } } int t = rank[1] - m; if(t < 1) t = 0; for(int i = t; i <= rank[1]; i ++) { solve(i,i+m); if(mi > ans) mi = ans; } printf("%d\n",mi); } } int main() { init(); return 0; }