zhber
有好多做过的题没写下来,如果我还能记得就补吧

Description

John在他的农场中闲逛时发现了许多虫洞。虫洞可以看作一条十分奇特的有向边,并可以使你返回到过去的一个时刻(相对你进入虫洞之前)。John的每个农场有M条小路(无向边)连接着N (从1..N标号)块地,并有W个虫洞。其中1<=N<=500,1<=M<=2500,1<=W<=200。 现在John想借助这些虫洞来回到过去(出发时刻之前),请你告诉他能办到吗。 John将向你提供F(1<=F<=5)个农场的地图。没有小路会耗费你超过10000秒的时间,当然也没有虫洞回帮你回到超过10000秒以前。

Input

* Line 1: 一个整数 F, 表示农场个数。

* Line 1 of each farm: 三个整数 N, M, W。

* Lines 2..M+1 of each farm: 三个数(S, E, T)。表示在标号为S的地与标号为E的地中间有一条用时T秒的小路。

* Lines M+2..M+W+1 of each farm: 三个数(S, E, T)。表示在标号为S的地与标号为E的地中间有一条可以使John到达T秒前的虫洞。

Output

* Lines 1..F: 如果John能在这个农场实现他的目标,输出"YES",否则输出"NO"。

Sample Input

2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8

Sample Output

NO
YES

spfa判负环……还写的是dfs的spfa……大概会快一点

真是斯巴达……加边的时候前m条要加双向边,后w条只加单向边……因此不明不白的wa了好几次

#include<cstdio>
#include<cstring>
int n,m,w,cnt,len,head[10001],dist[10001];
bool flag[10001],ans;
int s[10001];
struct edge{
	int to,next,v;
}e[100001];
inline void ins(int u,int v,int w)
{
	e[++cnt].to=v;
	e[cnt].next=head[u];
	e[cnt].v=w;
	head[u]=cnt;
}
inline void insert(int u,int v,int w)
{
	ins(u,v,w);
	ins(v,u,w);
}
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;
}
inline void spfa(int x)
{
	flag[x]=1;
	for (int i=head[x];i;i=e[i].next)
	  {
	  	if (dist[x]+e[i].v<dist[e[i].to])
	  	{
	  		if (flag[e[i].to]) {ans=1;return;}
	  		dist[e[i].to]=dist[x]+e[i].v;
	  		spfa(e[i].to);
	  	}
	  }
	flag[x]=0;
}
inline bool judge()
{
	ans=0;
	for (int i=1;i<=n;i++)
	{
		memset(flag,0,sizeof(flag));
		memset(dist,0,sizeof(dist));
		spfa(i);
		if (ans) return 1;
	}
	return 0;
}
inline bool work()
{
	memset(e,0,sizeof(e));
	memset(head,0,sizeof(head));
	cnt=0;
	n=read();
	m=read();
	w=read();
	for (int i=1;i<=m;i++)
	  {
	  	int x=read(),y=read(),z=read();
	  	insert(x,y,z);
	  }
	for (int i=1;i<=w;i++)
	  {
	  	int x=read(),y=read(),z=read();
	  	ins(x,y,-z);
	  }
	if (judge()) return 1;
	else return 0;
}
int T;
int main()
{
	T=read();
	while (T--)s[++len]=work();
	for (int i=1;i<=len;i++)
	  if (s[i]) printf("YES\n");
	  else printf("NO\n");
}


posted on 2014-06-16 22:23  zhber  阅读(264)  评论(0编辑  收藏  举报