BZOJ-1202 狡猾的商人

先处理成前缀和关系,然后可以很明显得看得出这是一个差分约束。那么就是最短路问题了。

顺便复习了一下SPFA加SLF优化是怎么写的,也学习到了另一个STL——Deque双向队列。

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <deque>
 
#define rep(i, l, r) for(int i = l; i <= r; i++)
#define down(i, l, r) for(int i = l; i >= r; i--)
#define N 123
#define M 2345
#define ll long long
 
using namespace std;
inline int read()
{
	int x=0, f=1; char ch=getchar();
	while (ch<'0' || ch>'9') { if (ch=='-') f=-1; ch=getchar(); }
	while (ch>='0' && ch<='9') { x=x*10+ch-'0'; ch=getchar(); }
	return x*f;
}

struct edge{int y, z, n;} e[M]; int fir[N], en;
int t, n, m, d[N], c[N], x, y, z;
bool b[N], ans;
deque <int> q;

void AddE(int x, int y, int z)
{
	en++, e[en].y = y, e[en].z = z, e[en].n = fir[x], fir[x] = en;
	en++, e[en].y = x, e[en].z = -z, e[en].n = fir[y], fir[y] = en;
}

void Init()
{
	rep(i, 1, en) e[i] = e[0];
	rep(i, 0, n) fir[i] = c[i] = 0; en = 0;
	ans = true;
}

int main()
{
	t=read();
	while (t--)
	{
		Init();
		n=read(); m=read();
		rep(i, 1, m) x=read(), y=read(), z=read(), AddE(x-1, y, z);
		rep(i, 0, n) d[i]=0, b[i]=1, c[i]=1, q.push_back(i);
		while (!q.empty())
		{
			int x = q.front(); q.pop_front(), b[x]=0;
			if (c[x]>n+1) { ans=false; break; }
			int o = fir[x], y = e[o].y;
			while (o)
			{
				if (d[y] > d[x]+e[o].z) 
				{
					d[y] = d[x]+e[o].z; if (!b[y]) 
						b[y]=1, c[y]++, !q.empty()&&d[q.front()]>d[y] ? q.push_front(y) : q.push_back(y);
				}
				o=e[o].n, y=e[o].y;
			}
		}
		if (ans) printf("true\n"); else printf("false\n");
	}
	return 0;
}

  

posted @ 2015-03-11 18:53  NanoApe  阅读(154)  评论(0编辑  收藏  举报
AmazingCounters.com