codeforces 107A(dfs)

时间:2022-07-28
本文章向大家介绍codeforces 107A(dfs),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

The German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).

For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.

In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.

有m条边,n个点,每个点最多有一个入水口和出水口,要求找到所有的水塔和最小的直径值

思路

如果一个点的入度为0并且出度不为0,就从这个结点开始dfs,dfs过程中记录最小的结点值。如果dfs到了一个出度为0的点,就跳出循环输出。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=3*1010;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int n,m;
int g[N][N],in[N],out[N];
void solve(){
    cin>>n>>m;
    for(int i=0;i<m;i++){
        int x,y,z;cin>>x>>y>>z;
        g[x][y]=z;
        in[y]=x;
        out[x]=y;
    }
    int cnt=0;
    for(int i=1;i<=n;i++){
        if(in[i]==0){
            if(out[i]!=0){
                cnt++;
            }
        }
    }
    cout<<cnt<<endl;
    for(int i=1;i<=n;i++){
        if(in[i]==0){
            if(out[i]!=0){
                int res=INF;
                int u=i;
                while(1){
                    int v=out[u];
                    if(!v) break;
                    res=min(res,g[u][v]);
                    u=v;
                }
                cout<<i<<' '<<u<<' '<<res<<endl;
            }
        }
    }
}
int main(){
    IOS;
    solve();
    return 0;
}