zoukankan      html  css  js  c++  java
  • 【POJ3159】Candies-差分约束系统

    测试地址:Candies

    题目大意:幼儿园一个班里有N个小朋友(标号为1~N),一个小朋友flymouse(为N号)被校长指定去发糖,有M个条件,每个条件三个参数A,B,c,表示小朋友A不希望小朋友B有比他多超过c个的糖,班里还有另一个小朋友snoopy(为1号),flymouse希望自己得到的糖果比snoopy的尽量多,求最大的差值。

    做法:这里引入一个叫差分约束系统的东西,大概就是给定一系列这样形式的不等式:xi-xj<=bk,然后求某两个xa和xb的差的最大值,即max(xa-xb)。正确的方法是,如果存在一个xi-xj<=bk这样的不等式,就从j引一条指向i的边权为bk的有向边,这样就可以构成一个有向图,然后求max(xa-xb)就是求从b到a的最短路径。为什么呢?因为我们看任意一条简单路径:b,s1,s2,...,sn,a,其中相邻两点间边权依次为b0,b1,...,bn,所以xs1-xb<=b0,xs2-xs1<=b1,...,xa-xsn<=bn,所以xa-xb=(xa-xsn)+...+(xs2-xs1)+(xs1-xb)<=b0+b1+...+bn,所以我们可以得到xa-xb必定不超过任意从b到a的简单路径上边权的和,也就是说任何一条路径都是一个上界,所以要求最大值也就是求最小的上界,也就是求最短路了。

    而这一题模型比较简单,构图很容易,对于每个条件直接连A->B,边权为c即可,然后求从1到N的最短路。

    然而这道题数据不知道出了什么问题,spfa+queue的话TLE,spfa+stack就过了,神奇。

    以下是本人代码:

    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    #include <stack>
    #define inf 2147483647
    using namespace std;
    int n,m,first[30010]={0},tot=0,dis[30010];
    bool inque[30010];
    struct edge {int v,d,next;} e[200010];
    
    void insert(int x,int y,int d)
    {
      e[++tot].v=y;
      e[tot].d=d;
      e[tot].next=first[x];
      first[x]=tot;
    }
    
    int spfa(int s,int t)
    {
      stack<int> q;
      q.push(s);
      memset(inque,0,sizeof(inque));
      for(int i=1;i<=n;i++)
        dis[i]=inf;
      inque[s]=1,dis[s]=0;
      while(!q.empty())
      {
        int v=q.top();q.pop();
    	for(int i=first[v];i;i=e[i].next)
    	  if (dis[e[i].v]>dis[v]+e[i].d)
    	  {
    	    dis[e[i].v]=dis[v]+e[i].d;
    		if (!inque[e[i].v]) {inque[e[i].v]=1;q.push(e[i].v);}
    	  }
    	inque[v]=0;
      }
      return dis[t];
    }
    
    int main()
    {
      scanf("%d%d",&n,&m);
      for(int i=1,a,b,c;i<=m;i++)
      {
        scanf("%d%d%d",&a,&b,&c);
    	insert(a,b,c);
      }
      
      printf("%d",spfa(1,n));
      
      return 0;
    }
    


  • 相关阅读:
    Populating Next Right Pointers in Each Node II
    Populating Next Right Pointers in Each Node
    Construct Binary Tree from Preorder and Inorder Traversal
    Construct Binary Tree from Inorder and Postorder Traversal
    Path Sum
    Symmetric Tree
    Solve Tree Problems Recursively
    632. Smallest Range(priority_queue)
    609. Find Duplicate File in System
    poj3159最短路spfa+邻接表
  • 原文地址:https://www.cnblogs.com/Maxwei-wzj/p/9793837.html
Copyright © 2011-2022 走看看