1291. Gear-wheels

http://acm.timus.ru/problem.aspx?space=1&num=1291

dfs 遍历树的节点 根据齿轮数量的比 求得转速 注意用 gcd 化减

代码:

#include<iostream>

#include<cstdio>

#include<cstring>

#include<cmath>

#include<algorithm>

#include<vector>

#include<set>

#include<queue>

#include<stack>

#include<map>

#include<string>

#include<iomanip>

using namespace std;



#define LL long long

const int INF=0x3f3f3f3f;

const int N=1005;

int head[N],I;

struct node

{

    int j,next;

}side[N*2];

bool visited[N];

int a[N];

int numerator[N];

int denominator[N];

void add(int i,int j)

{

    side[I].j=j;

    side[I].next=head[i];

    head[i]=I++;

}

int gcd(int x,int y)

{

    if(x%y==0)

    return y;

    return gcd(y,x%y);

}

void Fans(int x,int y)

{

    numerator[y]=-numerator[x]*a[x];

    denominator[y]=denominator[x]*a[y];

    int k=gcd(abs(numerator[y]),abs(denominator[y]));

    numerator[y]/=k;

    denominator[y]/=k;

}

void dfs(int x)

{

    visited[x]=true;

    for(int t=head[x];t!=-1;t=side[t].next)

    {

        int l=side[t].j;

        if(visited[l])

        continue;

        Fans(x,l);

        dfs(l);

    }

}

int main()

{

    //freopen("data.in","r",stdin);

    int n;

    while(cin>>n)

    {

        memset(head,-1,sizeof(head));

        I=0;

        for(int i=1;i<=n;++i)

        {

            cin>>a[i];

            int k;

            while(cin>>k)

            {

                if(!k)

                break;

                add(i,k);

            }

        }

        for(int i=1;i<=n;++i)

        {

            numerator[i]=0;

            denominator[i]=1;

        }

        int s,v;

        cin>>s>>v;

        numerator[s]=v;

        memset(visited,false,sizeof(visited));

        dfs(s);

        for(int i=1;i<=n;++i)

        cout<<numerator[i]<<"/"<<denominator[i]<<endl;

    }

    return 0;

}

 

你可能感兴趣的:(EL)