示例#1
0
文件: Particle.cpp 项目: aadah/Cloud
void Particle::printInfo(){
    if (ofGetFrameNum() % (int)ofGetFrameRate() == 0){
        cout << "Position: " << '(' << getX() << ',' << getY() << ')' << endl;
        cout << "Speed: " << getSpeed() << "\t" << "Angle:"  << getAngle() << endl;
        cout << "Flow: " << getFlow() << "\t" << "Alpha: " << getAlpha() << endl << endl;
    }
}
示例#2
0
void printGraph(GraphFlow *g) {
	int i = 0;
	int j = 0;
	
	printf("-- graph --\n");
	
	printf("-Edges:\n");
	for(i=0; i < getNumNodes(g); i++) {
		for(j=0; i < getNumNodes(g); i++) {
			printf("%d ", getEdge(g,i,j));
		}
		printf("\n");
	}
	
	printf("-Capacity:\n");
	for(i=0; i < getNumNodes(g); i++) {
		for(j=0; i < getNumNodes(g); i++) {
			printf("%d ", getCapacity(g,i,j));
		}
		printf("\n");
	}
	
	printf("-Flow:\n");
	for(i=0; i < getNumNodes(g); i++) {
		for(j=0; i < getNumNodes(g); i++) {
			printf("%d ", getFlow(g,i,j));
		}
		printf("\n");
	}
}
示例#3
0
文件: flow.cpp 项目: frePPLe/frePPLe
Flow::~Flow()
{
  // Set a flag to make sure the level computation is triggered again
  HasLevel::triggerLazyRecomputation();

  // Delete existing flowplans
  if (getOperation() && getBuffer())
  {
    // Loop over operationplans
    for(OperationPlan::iterator i(getOperation()); i != OperationPlan::end(); ++i)
      // Loop over flowplans
      for (auto j = i->beginFlowPlans(); j != i->endFlowPlans(); )
      {
        if (j->getFlow() == this)
          j.deleteFlowPlan();
        else
          ++j;
      }
  }

  // Delete the flow from the operation and the buffer
  if (getOperation())
    getOperation()->flowdata.erase(this);
  if (getBuffer())
    getBuffer()->flows.erase(this);
}
示例#4
0
int getResidualCapacity(GraphFlow *g, int node1, int node2) {
	if(!inRange(g,node1) || !inRange(g,node2)) {
		printf("Error range in getResidualCapacity of GraphFlow!\n");
		exit(-1);
	}
	
	return getCapacity(g,node1,node2) - getFlow(g,node1,node2);
}
void KisFlowOpacityOption::apply(KisPainter* painter, const KisPaintInformation& info)
{
    if (m_paintActionType == WASH && m_nodeHasIndirectPaintingSupport)
        painter->setOpacityUpdateAverage(quint8(getDynamicOpacity(info) * 255.0));
    else
        painter->setOpacityUpdateAverage(quint8(getStaticOpacity() * getDynamicOpacity(info) * 255.0));

    painter->setFlow(quint8(getFlow() * 255.0));
}
示例#6
0
PyObject* FlowPlan::getattro(const Attribute& attr)
{
  if (attr.isA(Tags::tag_operationplan))
    return PythonObject(getOperationPlan());
  if (attr.isA(Tags::tag_quantity))
    return PythonObject(getQuantity());
  if (attr.isA(Tags::tag_flow))
    return PythonObject(getFlow());
  if (attr.isA(Tags::tag_date))
    return PythonObject(getDate());
  if (attr.isA(Tags::tag_onhand))
    return PythonObject(getOnhand());
  if (attr.isA(Tags::tag_buffer)) // Convenient shortcut
    return PythonObject(getFlow()->getBuffer());
  if (attr.isA(Tags::tag_operation)) // Convenient shortcut
    return PythonObject(getFlow()->getOperation());
  return NULL;
}
示例#7
0
int flow(GraphFlow *g) {
	int result = 0;
	int node = 0;
	
	for(node = 0; node < getNumNodes(g); node++) {
		result += getFlow(g,getSource(g),node);
	}
	
	return result;
}
示例#8
0
int flowConservative2(GraphFlow *g) {
	int i = 0;
	int j = 0;
	int balance = 0;
	
	for( i=0; i < getNumNodes(g); i++) {
		if( i != getSource(g) && i != getSink(g) ) {
			for(j=0, balance =0; j < getNumNodes(g); j++) {
				balance += getFlow(g,i,j);
			}
			if(balance != 0)
				return FALSE;
		}
	}
	
	return TRUE;
}
示例#9
0
int positiveFlowFromNode(GraphFlow *g, int node) {
	int i = 0;
	int result = 0;
	int flow = 0;
	
	if(!inRange(g,node)) {
		printf("Error range in positiveFlowFromNode!\n");
		exit(-1);
	}
	
	for(i=0; i < getNumNodes(g); i++) {
		flow = getFlow(g,i,node);
		if(flow < 0)
			result += -flow;
	}
	
	return result;
}
示例#10
0
SUMOReal
GUIEdge::getScaleValue(size_t activeScheme) const {
    switch (activeScheme) {
        case 1:
            return gSelected.isSelected(getType(), getGlID());
        case 2:
            return getAllowedSpeed();
        case 3:
            return getBruttoOccupancy();
        case 4:
            return getMeanSpeed();
        case 5:
            return getFlow();
        case 6:
            return getRelativeSpeed();
    }
    return 0;
}
示例#11
0
int main ()
{
  FINISH = clock () + (CLOCKS_PER_SEC * 1800) / 1000;
  freopen ("omax.in", "rt", stdin);
  freopen ("omax.out", "wt", stdout);
#ifdef _DBG_
  freopen ("omax.err", "wt", stderr);
#endif

  scanf ("%d", &X);
  Y = X;
  n = X + Y + 2;
  for (int i = 0; i < X; i++)
    add_edge (0, i + 1, 1);
  for (int i = 0; i < Y; i++)
    add_edge (i + X + 1, n - 1, 1);
  for (int i = 0; i < X; i++)
  {
    int c;
    scanf ("%d", &c);
    for (int j = 0; j < c; j++)
    {
      int b;
      scanf ("%d", &b);
      add_edge (i + 1, b + X, 1);
    }
  }

  int flow = getFlow ();
  if (flow < X)
    noQuit ();
#ifdef _DBG_
  printf ("%d\n", flow);
#endif

  memset (vis, 0, sizeof vis);
  for (int i = 0; i < n; i++)
  {
    dfs (i);
  }
  printFlow ();
 
  return 0;
}
示例#12
0
/*
add packet to the relevent flow
*/
void buffer_write(Packet* p, bool virtual_f)
{
	bool insertP = FALSE;
	Flow* f = getFlow(p, &insertP, virtual_f);
	FHeap* heap = virtual_f ? virtual_flows : flows;
	if (!insertP) //if we didn't insert the packet
	{
		if (flow_isEmpty(f)){ // revived flow
			flow_enqueue(f, p);
			heapify(heap->data, heap->count);
			heap->weight += f->weight;
		}
		else
		{
			flow_enqueue(f, p);
		}

	}

}
示例#13
0
SUMOReal
GUIEdge::getScaleValue(int activeScheme) const {
    switch (activeScheme) {
        case 1:
            return gSelected.isSelected(getType(), getGlID());
        case 2:
            return getAllowedSpeed();
        case 3:
            return getBruttoOccupancy();
        case 4:
            return getMeanSpeed();
        case 5:
            return getFlow();
        case 6:
            return getRelativeSpeed();
        case 7:
            return MSNet::getInstance()->getInsertionControl().getPendingEmits(getLanes()[0]);
    }
    return 0;
}
示例#14
0
fxBool
ModemConfig::parseItem(const char* tag, const char* value)
{
    int i;
    for (i = (sizeof ( atcmds ) / sizeof ( atcmds [0])) -1; i >= 0; i--)
	if ((strcasecmp( tag ,  atcmds[i].name )==0) ) {
	    (*this).*atcmds[i].p = parseATCmd(value);
	    return (((fxBool)1) );
	}
    for (i = (sizeof ( fillorders ) / sizeof ( fillorders [0])) -1; i >= 0 ; i--)
	if ((strcasecmp( tag ,  fillorders[i].name )==0) ) {
	    (*this).*fillorders[i].p = getFill(value);
	    return (((fxBool)1) );
	}
    for (i = (sizeof ( numbers ) / sizeof ( numbers [0])) -1; i >= 0 ; i--)
	if ((strcasecmp( tag ,  numbers[i].name )==0) ) {
	    (*this).*numbers[i].p = atoi(value);
	    return (((fxBool)1) );
	}
    fxBool recognized = ((fxBool)1) ;
    if ((strcasecmp( tag ,  "ModemType" )==0) )
	type = value;
    else if ((strcasecmp( tag ,  "ModemSetVolumeCmd" )==0) )
	setVolumeCmds(value);
    else if ((strcasecmp( tag ,  "ModemFlowControl" )==0) )
	flowControl = getFlow(value);
    else if ((strcasecmp( tag ,  "ModemMaxRate" )==0)  || (strcasecmp( tag ,  "ModemRate" )==0) )
	maxRate = getRate(value);
    else if ((strcasecmp( tag ,  "ModemWaitForConnect" )==0) )
	waitForConnect = getBoolean(value);
    else if ((strcasecmp( tag ,  "Class2RecvDataTrigger" )==0) )
	class2RecvDataTrigger = value;
    else if ((strcasecmp( tag ,  "Class2XmitWaitForXON" )==0) )
	class2XmitWaitForXON = getBoolean(value);
    else
	recognized = ((fxBool)0) ;
    return (recognized);
}
示例#15
0
void NetworkInterface::flow_processing(ZMQ_Flow *zflow)
{
  bool src2dst_direction;
  Flow *flow;

  if((time_t)zflow->last_switched > (time_t)last_pkt_rcvd)
    last_pkt_rcvd = zflow->last_switched;

  /* Updating Flow */

  flow = getFlow(zflow->src_mac, zflow->dst_mac,
		 zflow->vlan_id,
		 &zflow->src_ip, &zflow->dst_ip,
		 zflow->src_port, zflow->dst_port,
		 zflow->l4_proto, &src2dst_direction,
		 zflow->first_switched,
		 zflow->last_switched);

  if(flow == NULL) return;

  if(zflow->l4_proto == IPPROTO_TCP) flow->updateTcpFlags(zflow->tcp_flags);
  flow->addFlowStats(src2dst_direction,
		     zflow->pkt_sampling_rate*zflow->in_pkts,
		     zflow->pkt_sampling_rate*zflow->in_bytes,
		     zflow->pkt_sampling_rate*zflow->out_pkts,
		     zflow->pkt_sampling_rate*zflow->out_bytes,
		     zflow->last_switched);
  flow->setDetectedProtocol(zflow->l7_proto);
  flow->setJSONInfo(json_object_to_json_string(zflow->additional_fields));
  flow->updateActivities();
  incStats(zflow->src_ip.isIPv4() ? ETHERTYPE_IP : ETHERTYPE_IPV6,
	   flow->get_detected_protocol(),
	   zflow->pkt_sampling_rate*(zflow->in_bytes + zflow->out_bytes),
	   zflow->pkt_sampling_rate*(zflow->in_pkts + zflow->out_pkts),
	   24 /* 8 Preamble + 4 CRC + 12 IFG */ + 14 /* Ethernet header */);

  purgeIdle(zflow->last_switched);
}
示例#16
0
void elFlowPort::updateValues()
{
    // checkInTimeCount();

    if( _emitFlow )
    {
        getFlow();
    }
    if( _emitPressure )
    {
        getPressure();
    }
    if( _emitTemperature )
    {
        getTemperature();
    }
    // updateNumInTimeValues();

    if( _setValueType != setValueType::setTypeNone
            && _autoAdjust )
    {
        // adjustValues();
    }
}
示例#17
0
文件: Particle.cpp 项目: aadah/Cloud
// Other methods
void Particle::update(){ // main method that controls all necessary movement
    // attraction and repulsion
    float dy = (ofGetWindowHeight() - ofGetMouseY()) - getY();
    float dx = ofGetMouseX() - getX();
    if (getAttract() && !getRepel()){
        float desired = atan2(dy,dx);
        float angdiff = desired-getAngle();
        if ((angdiff > 0 && abs(angdiff) <= PI) || (angdiff < 0 && abs(angdiff) > PI)){
            setAngle(getAngle() + getAlpha());
        }
        else if ((angdiff > 0 && abs(angdiff)>PI) || (angdiff < 0 && abs(angdiff) <= PI)){
            setAngle(getAngle() - getAlpha());
        }
//        if (desired+getAlpha()>getAngle() && desired-getAlpha()<getAngle()){
//            setSpeed(getSpeed()+getFlow());
//        }
//        else {
//            if (getSpeed()>ORBITAL_FACTOR*getFlow()){
//                setSpeed(getSpeed()-getFlow());
//            }
//        }
    }
    else if (getRepel() && !getAttract() && sqrt(pow(dy,2) + pow(dx,2)) <= BARRIER){
        float desired = atan2(dy,dx) > 0 ? atan2(dy,dx) - PI : atan2(dy,dx) + PI;
        float angdiff = desired - getAngle();
        if ((angdiff > 0 && abs(angdiff) <= PI) || (angdiff < 0 && abs(angdiff) > PI)){
            setAngle(getAngle() + getAlpha());
        }
        else if ((angdiff > 0 && abs(angdiff) > PI) || (angdiff < 0 && abs(angdiff) <= PI)){
            setAngle(getAngle() - getAlpha());
        }
//        if (desired+getAlpha()>getAngle() && desired-getAlpha()<getAngle()){
//            setSpeed(getSpeed()+getFlow());
//        }
//        else {
//            if (getSpeed()>ORBITAL_FACTOR*getFlow()){
//                setSpeed(getSpeed()-getFlow());
//            }
//        }
    }
    else if (getAttract() && getRepel()){
        if (getSpeed() > 0){
            setSpeed(getSpeed() - getFlow());
        }
    }
    // life
    if (getAlive()){
        setAngle(getAngle() + ofRandomf() * getAlpha());
        setSpeed(getSpeed() + ofRandomf() * getFlow());
        setRadius(getRadius() + ofRandomf() * RADIUS_NOISE);
    }
    // bounds
    if (getX() > ofGetWindowWidth() - getRadius() || getX() < getRadius()){
        setAngle(-getAngle() + PI);
    }
    if (getY() > ofGetWindowHeight() - getRadius() || getY() < getRadius()){
        setAngle(-getAngle());
    }
    // position + motion
    position += velocity;
    // color
    float r = getAttract() && getRepel() ? getColor().r + 1 : (getSpeed()/MAX_SPEED) * 255;
    float g = getAttract() ? getColor().g + 1 : (getY()/ofGetWindowHeight()) * 255;
    float b = getRepel() ? getColor().b + 1 : (1-getY()/ofGetWindowHeight()) * 255;
    setColor(r,g,b);
}
示例#18
0
void NetworkInterface::packet_processing(const u_int32_t when,
					 const u_int64_t time,
					 struct ndpi_ethhdr *eth,
					 u_int16_t vlan_id,
					 struct ndpi_iphdr *iph,
					 struct ndpi_ip6_hdr *ip6,
					 u_int16_t ipsize, u_int16_t rawsize)
{
  bool src2dst_direction;
  u_int8_t l4_proto;
  Flow *flow;
  u_int8_t *eth_src = eth->h_source, *eth_dst = eth->h_dest;
  IpAddress src_ip, dst_ip;
  u_int16_t src_port, dst_port;
  struct ndpi_tcphdr *tcph = NULL;
  struct ndpi_udphdr *udph = NULL;
  u_int16_t l4_packet_len;
  u_int8_t *l4, tcp_flags = 0;
  u_int8_t *ip;
  bool is_fragment = false;

  if(iph != NULL) {
    /* IPv4 */
    if(ipsize < 20) {
      incStats(ETHERTYPE_IP, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
      return;
    }

    if((iph->ihl * 4) > ipsize || ipsize < ntohs(iph->tot_len)
       || (iph->frag_off & htons(0x1FFF /* IP_OFFSET */)) != 0) {
      is_fragment = true;
    }

    l4_packet_len = ntohs(iph->tot_len) - (iph->ihl * 4);
    l4_proto = iph->protocol;
    l4 = ((u_int8_t *) iph + iph->ihl * 4);
    ip = (u_int8_t*)iph;
  } else {
    /* IPv6 */
    if(ipsize < sizeof(const struct ndpi_ip6_hdr)) {
      incStats(ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
      return;
    }

    l4_packet_len = ntohs(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen)-sizeof(const struct ndpi_ip6_hdr);
    l4_proto = ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt;
    l4 = (u_int8_t*)ip6 + sizeof(const struct ndpi_ip6_hdr);
    ip = (u_int8_t*)ip6;
  }

  if((l4_proto == IPPROTO_TCP) && (l4_packet_len >= 20)) {
    /* tcp */
    tcph = (struct ndpi_tcphdr *)l4;
    src_port = tcph->source, dst_port = tcph->dest;
    tcp_flags = l4[13];
  } else if((l4_proto == IPPROTO_UDP) && (l4_packet_len >= 8)) {
    /* udp */
    udph = (struct ndpi_udphdr *)l4;
    src_port = udph->source,  dst_port = udph->dest;
  } else {
    /* non tcp/udp protocols */

    src_port = dst_port = 0;
  }

  if(iph != NULL) {
    src_ip.set_ipv4(iph->saddr);
    dst_ip.set_ipv4(iph->daddr);
  } else {
    src_ip.set_ipv6(&ip6->ip6_src);
    dst_ip.set_ipv6(&ip6->ip6_dst);
  }

#if defined(WIN32) && defined(DEMO_WIN32)
  if(this->ethStats.getNumPackets() > MAX_NUM_PACKETS) {
    static bool showMsg = false;

    if(!showMsg) {
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "-----------------------------------------------------------");
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "WARNING: this demo application is a limited ntopng version able to");
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "capture up to %d packets. If you are interested", MAX_NUM_PACKETS);
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "in the full version please have a look at the ntop");
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "home page http://www.ntop.org/.");
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "-----------------------------------------------------------");
      ntop->getTrace()->traceEvent(TRACE_NORMAL, "");
      showMsg = true;
    }

    return;
  }
#endif

  /* Updating Flow */
  flow = getFlow(eth_src, eth_dst, vlan_id, &src_ip, &dst_ip, src_port, dst_port,
		 l4_proto, &src2dst_direction, last_pkt_rcvd, last_pkt_rcvd);

  if(flow == NULL) {
    incStats(iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, NDPI_PROTOCOL_UNKNOWN, rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
    return;
  } else {
    flow->incStats(src2dst_direction, rawsize);
    if(l4_proto == IPPROTO_TCP) flow->updateTcpFlags(tcp_flags);
  }

  /* Protocol Detection */
  flow->updateActivities();

  if(flow->isDetectionCompleted()) {
    /* Handle aggregations here */
    switch(flow->get_detected_protocol()) {
    case NDPI_PROTOCOL_DNS:
      struct ndpi_flow_struct *ndpi_flow = flow->get_ndpi_flow();
      struct ndpi_id_struct *cli = (struct ndpi_id_struct*)flow->get_cli_id();
      struct ndpi_id_struct *srv = (struct ndpi_id_struct*)flow->get_srv_id();

      if(ndpi_flow) {
	memset(&ndpi_flow->detected_protocol_stack, 
	       0, sizeof(ndpi_flow->detected_protocol_stack));
	
	ndpi_detection_process_packet(ndpi_struct, ndpi_flow,
				      ip, ipsize, (u_int32_t)time,
				      cli, srv);
	if(ndpi_flow->protos.dns.ret_code != 0) {
	  /* 
	     This is a negative reply thus we notify the system that
	     this aggregation must not be tracked
	  */
	  flow->aggregateInfo((char*)ndpi_flow->host_server_name, l4_proto,
			      NDPI_PROTOCOL_DNS, false);
	}
      }
      break;
    }

    flow->processDetectedProtocol();
    flow->deleteFlowMemory();
    incStats(iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, flow->get_detected_protocol(), rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);
    return;
  } else
    incStats(iph ? ETHERTYPE_IP : ETHERTYPE_IPV6, flow->get_detected_protocol(), rawsize, 1, 24 /* 8 Preamble + 4 CRC + 12 IFG */);

  if(!is_fragment) {
    struct ndpi_flow_struct *ndpi_flow = flow->get_ndpi_flow();
    struct ndpi_id_struct *cli = (struct ndpi_id_struct*)flow->get_cli_id();
    struct ndpi_id_struct *srv = (struct ndpi_id_struct*)flow->get_srv_id();

    flow->setDetectedProtocol(ndpi_detection_process_packet(ndpi_struct, ndpi_flow,
							    ip, ipsize, (u_int32_t)time,
							    cli, srv));
  } else {
    // FIX - only handle unfragmented packets
    // ntop->getTrace()->traceEvent(TRACE_WARNING, "IP fragments are not handled yet!");
  }
}
示例#19
0
文件: transect.c 项目: ezhangle/swmm
void  getGeometry(int i, int j, double y)
//
//  Input:   i = index of current entry in geometry tables
//           j = transect index
//           y = depth of current entry in geometry tables
//  Output:  none
//  Purpose: computes entries in a transect's geometry tables at a given depth. 
//
{
    int    k;                // station index
    double ylo,              // lower elev. of transect slice
           yhi,              // higher elev. of transect slice
           w,                // top width of transect slice
           wp,               // wetted perimeter of transect slice
           wpSum,            // total wetted perimeter across transect
           a,                // area of transect slice
           aSum,             // total area across transect
           q,                // flow across transect slices with same roughness
           qSum;             // total flow across transect
    int   findFlow;          // true if flow thru area slice needs updating

    // --- initialize
    wpSum = 0.0;
    aSum = 0.0;
    qSum = 0.0;

    // --- examine each horizontal station from left to right
    for (k = 1; k <= Nstations; k++)
    {
        // --- determine low & high elevations for transect sub-section
        if ( Elev[k-1] >= Elev[k] )
        {
            yhi = Elev[k-1];
            ylo = Elev[k];
        }
        else
        {
            yhi = Elev[k];
            ylo = Elev[k-1];
        }

        // --- skip station if its totally dry
        if ( ylo >= y ) continue;

        // --- get top width, area & wetted perimeter values for transect
        //     slice between station k and k-1
        getSliceGeom(k, y, ylo, yhi, &w, &a, &wp);

        // --- update total transect values
        wpSum += wp;
        aSum += a;
        Transect[j].areaTbl[i] += a;
        Transect[j].widthTbl[i] += w;

        // --- must update flow if station elevation is above water level
        if ( Elev[k] >= y ) findFlow = TRUE;
        else findFlow = FALSE;

        // --- update flow across transect if called for
        q = getFlow(k, aSum, wpSum, findFlow);
        if ( q > 0.0 )
        {
            qSum += q;
            aSum = 0.0;
            wpSum = 0.0;
        }

    }   // next station k 

    // --- find hyd. radius table entry solving Manning eq. with
    //     total flow, total area, and main channel n
    aSum = Transect[j].areaTbl[i];
    if ( aSum == 0.0 ) Transect[j].hradTbl[i] = Transect[j].hradTbl[i-1];
    else Transect[j].hradTbl[i] = pow(qSum * Nchannel / 1.49 / aSum, 1.5);
}
示例#20
0
bool OperationPlan::updateFeasible()
{
  if (!getOperation()->getDetectProblems())
  {
    // No problems to be flagged on this operation
    setFeasible(true);
    return true;
  }

  // The implementation of this method isn't really cleanly object oriented. It uses
  // logic which only the different resource and buffer implementation classes should be
  // aware.
  if (firstsubopplan)
  {
    // Check feasibility of child operationplans
    for (OperationPlan *i = firstsubopplan; i; i = i->nextsubopplan)
    {
      if (!i->updateFeasible())
      {
        setFeasible(false);
        return false;
      }
    }
  }
  else
  {
    // Before current and before fence problems are only detected on child operationplans
    if (getConfirmed())
    {
      if (dates.getEnd() < Plan::instance().getCurrent())
      {
        // Before current violation
        setFeasible(false);
        return false;
      }
    }
    else
    {
      if (dates.getStart() < Plan::instance().getCurrent())
      {
        // Before current violation
        setFeasible(false);
        return false;
      }
      else if (dates.getStart() < Plan::instance().getCurrent() + oper->getFence() && getProposed())
      {
        // Before fence violation
        setFeasible(false);
        return false;
      }
    }
  }
  if (nextsubopplan
    && getEnd() > nextsubopplan->getStart() + Duration(1L)
    && !nextsubopplan->getConfirmed()
    && owner && !owner->getOperation()->hasType<OperationSplit>()
    )
  {
    // Precedence violation
    // Note: 1 second grace period for precedence problems to avoid rounding issues
    setFeasible(false);
    return false;
  }

  // Verify the capacity constraints
  for (auto ldplan = getLoadPlans(); ldplan != endLoadPlans(); ++ldplan)
  {
    if (ldplan->getResource()->hasType<ResourceDefault>() && ldplan->getQuantity() > 0)
    {
      auto curMax = ldplan->getMax();
      for (
        auto cur = ldplan->getResource()->getLoadPlans().begin(&*ldplan);
        cur != ldplan->getResource()->getLoadPlans().end();
        ++cur
        )
      {
        if (cur->getOperationPlan() == this && cur->getQuantity() < 0)
          break;
        if (cur->getEventType() == 4)
          curMax = cur->getMax(false);
        if (
          cur->getEventType() != 5
          && cur->isLastOnDate()
          && cur->getOnhand() > curMax + ROUNDING_ERROR
          )
        {
          // Overload on default resource
          setFeasible(false);
          return false;
        }
      }
    }
    else if (ldplan->getResource()->hasType<ResourceBuckets>())
    {
      for (
        auto cur = ldplan->getResource()->getLoadPlans().begin(&*ldplan);
        cur != ldplan->getResource()->getLoadPlans().end() && cur->getEventType() != 2;
        ++cur
        )
      {
        if (cur->getOnhand() < -ROUNDING_ERROR)
        {
          // Overloaded capacity on bucketized resource
          setFeasible(false);
          return false;
        }
      }
    }
  }

  // Verify the material constraints
  for (auto flplan = beginFlowPlans(); flplan != endFlowPlans(); ++flplan)
  {
    if (
      !flplan->getFlow()->isConsumer()
      || flplan->getBuffer()->hasType<BufferInfinite>()
      )
      continue;
    auto flplaniter = flplan->getBuffer()->getFlowPlans();
    for (auto cur = flplaniter.begin(&*flplan); cur != flplaniter.end(); ++cur)
    {
      if (cur->getOnhand() < -ROUNDING_ERROR && cur->isLastOnDate())
      {
        // Material shortage
        setFeasible(false);
        return false;
      }
    }
  }

  // After all checks, it turns out to be feasible
  setFeasible(true);
  return true;
}
示例#21
0
文件: B.cpp 项目: pavel-zeman/CodeJam
int main(void) {
    int t;
    scanf("%d", &t);

    for(int c=1; c<=t; c++) {

        scanf("%d %d", &h, &w);

        for(int i=0; i<h; i++)
            for(int j=0; j<w; j++) {
                scanf("%d", &map[i][j]);
                basin[i][j] = 0;
            }

        char currentBasin = 'a';

        while (1) {
            int queueStart = 0;
            int queueEnd = 0;

            for(int i=0; i<h; i++)
                for(int j=0; j<w; j++)
                    if (!basin[i][j]) {
                        queue[0].h = i;
                        queue[0].w = j;
                        queueEnd++;
                        basin[i][j] = currentBasin;
                        goto found;
                    }
            // nothing found
            break;

found:
            while (queueStart != queueEnd) {
                int h2, w2;
                getFlow(queue[queueStart].h, queue[queueStart].w, &h2, &w2);
                if (h2 >= 0 && !basin[h2][w2]) {
                    queue[queueEnd].h = h2;
                    queue[queueEnd++].w = w2;
                    basin[h2][w2] = currentBasin;
                }

                for(int i=0; i<4; i++) {
                    int h3 = queue[queueStart].h + dirs[i][0];
                    int w3 = queue[queueStart].w + dirs[i][1];
                    getFlow(h3, w3, &h2, &w2);
                    if (h2 == queue[queueStart].h && w2 == queue[queueStart].w && !basin[h3][w3]) {
                        queue[queueEnd].h = h3;
                        queue[queueEnd++].w = w3;
                        basin[h3][w3] = currentBasin;
                    }
                }
                queueStart++;
            }
            currentBasin++;
        }

        printf("Case #%d:\n", c);

        for(int i=0; i<h; i++) {
            for(int j=0; j<w; j++)
                printf("%c ", basin[i][j]);
            printf("\n");
        }
    }
}