链接:戳这里
4602: [Sdoi2016]齿轮
Time Limit: 10 Sec Memory Limit: 512 MB
[Submit][Status][Discuss]
Description
现有一个传动系统,包含了N个组合齿轮和M个链条。每一个链条连接了两个组合齿轮u和v,并提供了一个传动比x
: y。即如果只考虑这两个组合齿轮,编号为u的齿轮转动x圈,编号为v的齿轮会转动y圈。传动比为正表示若编号
为u的齿轮顺时针转动,则编号为v的齿轮也顺时针转动。传动比为负表示若编号为u的齿轮顺时针转动,则编号为v
的齿轮会逆时针转动。若不同链条的传动比不相容,则有些齿轮无法转动。我们希望知道,系统中的这N个组合齿
轮能否同时转动。
Input
有多组数据,第一行给定整数T,表示总的数据组数,之后依次给出T组数据。每一组数据的第一行给定整数N和
M,表示齿轮总数和链条总数。之后有M行,依次描述了每一个链条,其中每一行给定四个整数u,v,x和y,表示
只考虑这一组联动关系的情况下,编号为u的齿轮转动x圈,编号为v的齿轮会转动y圈。请注意,x为正整数,而y为
非零整数,但是y有可能为负数。
T<=32,N<=1000,M<=10000且x与y的绝对值均不超过100
Output
输出T行,对应每一组数据。首先应该输出标识这是第几组数据,参见样例输出。之后输出判定结果,如果N个组合
齿轮可以同时正常运行,则输出Yes,否则输出No。
Sample Input
2
3 3
1 2 3 5
2 3 5 -7
1 3 3 -7
3 3
1 2 3 5
2 3 5 -7
1 3 3 7
Sample Output
Case #1: Yes
Case #2: No
思路:
一开始写的是模拟,只有产生环的时候才需要判断当前的值是否和求得值一样,可是一直wa,也不知道错在哪
改成DFS跑,存下比例。就过了。。。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
struct edge{
int v,next;
long double w;
}e[200100];
int tot,head[100100],vis[100100];
long double d[100100];
const double eps=1e-8;
int flag;
void init(){
tot=0;
mst(head,-1);
mst(vis,0);
mst(d,0);
flag=0;
}
void Add(int u,int v,long double w){
e[tot].v=v;
e[tot].w=w;
e[tot].next=head[u];
head[u]=tot++;
}
void DFS(int u,int fa){
vis[u]=1;
for(int i=head[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(v==fa) continue;
if(vis[v]){
if(fabs(d[u]*e[i].w-d[v])>eps){
flag=1;
return ;
}
} else {
d[v]=d[u]*e[i].w;
DFS(v,u);
}
}
}
int n,m;
int main(){
int T;
scanf("%d",&T);
for(int cas=1;cas<=T;cas++){
scanf("%d%d",&n,&m);
init();
for(int i=1;i<=m;i++){
int u,v;
long double x,y;
scanf("%d%d",&u,&v);
cin>>x>>y;
Add(u,v,x/y);
Add(v,u,y/x);
}
for(int i=1;i<=n;i++){
if(!vis[i]){
d[i]=1.0;
DFS(i,0);
}
}
if(flag) printf("Case #%d: No\n",cas);
else printf("Case #%d: Yes\n",cas);
}
return 0;
}