【第22期】观点:IT 行业加班,到底有没有价值?

Connections between cities

原创 2016年08月30日 13:40:45
</pre><pre name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int maxn=10010;
typedef pair<int, int>wuyu;
vector<wuyu> edge[maxn],query[maxn];
int fa[maxn],ans[100*maxn],dis[maxn],anc[maxn];
bool p[maxn];

int father(int x){
    return fa[x]=fa[x]==x?x:father(fa[x]);    
}

void dfs(int u,int d,int an){
    fa[u]=u;
    dis[u]=d;
    p[u]=true;
    anc[u]=an;
    for(int i=0;i<edge[u].size();i++){
        int v=edge[u][i].first;
        int w=edge[u][i].second;
        if(p[v]==false){
            dfs(v,d+w,an);
            fa[v]=u;
            //printf("(%d->%d)\n",u,v);    
        }
    }
    for(int i=0;i<query[u].size();i++){
        int v=query[u][i].first;
        int w=query[u][i].second;
        if(p[v]==true && anc[v]==an){
            ans[w]=dis[u]+dis[v]-2*dis[father(fa[v])];
        }
    }
}

int main(){
    int m,n,k;
    int a,b,c;
    while(scanf("%d%d%d",&n,&m,&k)!=EOF){
        for(int i=1;i<=n;i++){
            edge[i].clear();
            query[i].clear();
        }
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&a,&b,&c);
            edge[a].push_back(wuyu(b,c));
            edge[b].push_back(wuyu(a,c));
        }
        int x,y;
        for(int i=1;i<=k;i++){
            scanf("%d%d",&x,&y);    
            query[x].push_back(wuyu(y,i));
            query[y].push_back(wuyu(x,i));
        }
        //memset(p,false,sizeof(p));
        memset(ans,-1,sizeof(ans));
        for(int i=1;i<=n;i++){
            if(p[i]==false)    dfs(i,0,i);
        }
        for(int i=1;i<=k;i++){
            if(ans[i]!=-1)printf("%d\n",ans[i]);    
            else printf("Not connected\n");
        }
    }
    return 0;    
}


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

hdoj 2874 Connections between cities 【并查集合并森林成一棵树 + LCA转RMQ】

Connections between cities Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (...

mysql开发者sql权威指南

原文地址:http://www.r20.nl/SQLforMySQL_V1_All_SQL_Statements.txt Example 4.1: CREATE USER 'BOOKSQL'@'localhost' IDENTIFIED BY 'BOOKSQLPW' Example 4.2: GRANT ALL PRIVILEGES ON *.* TO 'BOOKSQL'@'localhost' WITH GRANT OPTION Example 4.3: CREATE DATABASE TENNIS Example 4.4:

【HDU】2874 Connections between cities 离线LCA

Connections between cities Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (...

Connections between cities(LCA + 并查集)

Connections between cities Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tot

hdu2874 Connections between cities (LCA离线)

Connections between citiesTime Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Ja...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)