L3-023 计算图

建立结构体保存每个结点的前驱,操作符,来回两遍拓扑排序~

#include<bits/stdc++.h>
using namespace std;
const int maxn=50014;
struct node {
    vector<int> pre;
    double data;
    int fuhao=0;
}Node[maxn];
vector<int> g[maxn];
int a[maxn];
int inDegree[maxn];
int N;
stack<int> topOrder;
double getnum (node a) {
    if (a.pre.size()==0) return a.data;
    else if (a.pre.size()==1) {
        if (a.fuhao==4) return exp(Node[a.pre[0]].data);
        else if (a.fuhao==5) return log(Node[a.pre[0]].data);
        else if (a.fuhao==6) return sin(Node[a.pre[0]].data);
    } 
    else if (a.pre.size()==2) {
        if (a.fuhao==1) return Node[a.pre[0]].data+Node[a.pre[1]].data;
        else if (a.fuhao==2) return Node[a.pre[0]].data-Node[a.pre[1]].data;
        else if (a.fuhao==3) return Node[a.pre[0]].data*Node[a.pre[1]].data;
    }
}
double topSort () {
    queue<int> q;
    for (int i=0;i<N;i++)
    if (inDegree[i]==0) q.push(i);
    while (!q.empty()) {
        int u=q.front();
        q.pop();
        topOrder.push(u);
        Node[u].data=getnum(Node[u]);
        for (int i=0;i<g[u].size();i++)
        if (--inDegree[g[u][i]]==0) q.push(g[u][i]);
        if (q.empty()) return Node[u].data;
    }
}
double dfs (int u,int x) {
    if (Node[u].fuhao==0) {
        if (u==x) return 1;
        else return 0;
    }
    else if (Node[u].fuhao==1) return dfs(Node[u].pre[0],x)+dfs(Node[u].pre[1],x);
    else if (Node[u].fuhao==2) return dfs(Node[u].pre[0],x)-dfs(Node[u].pre[1],x);
    else if (Node[u].fuhao==3) return dfs(Node[u].pre[0],x)*Node[Node[u].pre[1]].data+dfs(Node[u].pre[1],x)*Node[Node[u].pre[0]].data;
    else if (Node[u].fuhao==4) return exp(Node[Node[u].pre[0]].data)*dfs(Node[u].pre[0],x);
    else if (Node[u].fuhao==5) return 1.0/Node[Node[u].pre[0]].data*dfs(Node[u].pre[0],x);
    else if (Node[u].fuhao==6) return cos(Node[Node[u].pre[0]].data)*dfs(Node[u].pre[0],x);
}
int main () {
    scanf ("%d",&N);
    int fuhao;
    double x,y;
    vector<int> v1;
    for (int i=0;i<N;i++) {
        scanf ("%d",&fuhao);
        if (fuhao==0) {
            scanf ("%lf",&x);
            Node[i].data=x;
            v1.push_back(i);
        }
        else if (fuhao>=1&&fuhao<=3) {
            scanf ("%lf %lf",&x,&y);
            Node[i].pre.push_back((int)x);
            Node[i].pre.push_back((int)y);
            inDegree[i]+=2;
            g[(int)x].push_back(i);
            g[(int)y].push_back(i);
            Node[i].fuhao=fuhao;
        }
        else if (fuhao>=4&&fuhao<=6) {
            scanf ("%lf",&x);
            Node[i].pre.push_back((int)x);
            inDegree[i]+=1;
            g[(int)x].push_back(i);
            Node[i].fuhao=fuhao;
        }
    }
    printf ("%.3f\n",topSort());
    int u=topOrder.top();
    for (int i=0;i<v1.size();i++) {
        if (i!=0) printf (" ");
        printf ("%.3f",dfs(u,v1[i]));
    }
    return 0;
}

 

posted @ 2020-02-14 22:07  zlc0405  阅读(209)  评论(0编辑  收藏  举报