• 自学图论的码队弟弟(dfs)


    自学图论的码队弟弟 题目描述 码队的弟弟在自学图论知识,码队跟他弟弟说,如果遇到不会的问题就来找你。现在问题来 了。 在一个 个结点(编号为 ), 条边的连通图中,每条边的权值为两个端点的权值的 和。 现在已知各边的权值,希望你求出各点的权值。 输入格式 输入数据共包含 行。 第一行为一个整数 。 接下来的 行,每行为 个整数 ,以空格分隔,表示连接点 和 的边的权值为 。 我们保证给出的数据是合法的,且没有「自环」或「重边」。给出的图中有且只有一个包括奇 数个结点的环。 输出格式 输出数据共包含 行。 每行为一个整数 ,表示点 的权值。 数据范围 输出时每行末尾的多余空格,不影响答案正确性 样例输入

    本题比较有意思

    首先我们设第一个点的权值是ans

    然后我们以第一个点为起点进行dfs

    在dfs的过程中我们可以从中推出一点关于ans的表达式

    由于保证有一个环

    肯定有一个点出现两个表达式

    那么这两个表达式一联立就解得了ans

    #include<cstdio>//1 zheng 0fu
    #include<queue>
    #include<cstring>
    #include<iostream>
    #include<map>
    #include<algorithm>
    using namespace std;
    int vis[100005];
    pair <int ,int> p[100005];
    vector<pair<int,int> >ve[100005];
    int ans;
    void dfs(int x,int fa)
    {
        for(int i=0;i<ve[x].size();i++)
        {
            int tmp1=ve[x][i].first;
            int tmp2=ve[x][i].second;
            if(vis[tmp1]==1&&tmp1!=fa)
            {
                if(p[x].second==1)//gaiweizhiwei fu
                {
                    ans=(tmp2-p[x].first-p[tmp1].first)/2;
                }
                else
                {
                    ans=(p[tmp1].first-tmp2+p[x].first)/2;
                }
            }
            if(vis[tmp1]==0)
            {
                vis[tmp1]=1;
                p[tmp1].first=tmp2-p[x].first;
                p[tmp1].second=p[x].second^1;
                dfs(tmp1,x);
            }
        }
    }
    int main()
    {
        //freopen("in.txt","r",stdin);
        memset(vis,0,sizeof(vis));
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            ve[u].push_back(make_pair(v,w));
            ve[v].push_back(make_pair(u,w));
        }
        vis[1]=1;
        p[1]=make_pair(0,1);
        dfs(1,0);
        //cout<<ans<<endl;
        for(int i=1;i<=n;i++)
        {
            if(p[i].second==0)
            printf("%d
    ",p[i].first-ans);
            else
            printf("%d
    ",p[i].first+ans);
        }
    }
    
  • 相关阅读:
    腾讯TencentOS正式开放测试:支持“傻瓜式刷机”-android
    glob.h and glob.c for the Android NDK
    (OK) 在CentOS7—编译OpenSSL 静态库—for—Android
    Android
    Pass data to CGI script and back with jQuery.ajax
    yum—repo—How to Enable EPEL Repository for RHEL/CentOS 7/6/5
    裸机版的hello world
    CodeBlock 使用手册
    (NOT OK) How To Build CyanogenMod Android for Motorola Defy ("jordan")
    error: .repo/manifests/: contains uncommitted changes 解决办法
  • 原文地址:https://www.cnblogs.com/caowenbo/p/11852244.html
Copyright © 2020-2023  润新知