题意:幼稚园分糖果,输入a,b,c表示,小孩a最多只能忍受小孩b的糖果比他多c个。求第一个小孩和最后一个小孩最多可以相差多少个糖果。
题解:卡队列呀···。手写了一个循环队列果断超时。改成栈则AC。貌似还有许多优化的方法,比如用优先级队列或者堆。
#include <iostream> using namespace std; #define N 150009 int n, m; bool mark[N]; int head[N], dis[N], Stack[N]; struct Edge { int v, cost, next; }; Edge edge[N]; void Spfa() { memset(mark,0,sizeof(mark)); for ( int i = 0; i <= n; i++ ) dis[i] = INT_MAX; int u, v, top = 0; Stack[++top] = 1; mark[1] = true; dis[1] = 0; while ( top >= 1 ) { u = Stack[top--]; mark[u] = false; for ( int i = head[u]; i != -1; i = edge[i].next ) { v = edge[i].v; if ( dis[v] > dis[u] + edge[i].cost ) { dis[v] = dis[u] + edge[i].cost; if ( ! mark[v] ) { Stack[++top] = v; mark[v] = true; } } } } } int main() { int a, b, c, cnt; while ( scanf("%d%d",&n,&m) != EOF ) { cnt = 0; memset(head,-1,sizeof(head)); while ( m-- ) { scanf("%d%d%d",&a,&b,&c); edge[cnt].v = b; edge[cnt].cost = c; edge[cnt].next = head[a]; head[a] = cnt++; } Spfa(); printf("%d\n",dis[n]); } return 0; }