DFS風險系數

![Uploading Paste_Image_193769.png . . .]

#include<iostream>
#include<algorithm>
#include<string>
#include<cctype>
#include<sstream>
#include<stack>
#include<cstdio>
#include<vector>
#include<fstream>
#include<ctime>
#include<map>
#include<queue> 
#include<cmath>
#define ALL(x) x.begin(),x.end()
#define ALLRE(x) x.rbegin(),x.rend()
using namespace std;

vector< vector<int> >  edge;
vector<int> path;
int u, v;
map<int, int> map1;
int count1 = 0;

void f2()
{
    for (int i = 1; i != path.size(); ++i) {
        if (i != v&&i != u&&path[i] == 1) {
            ++map1[i];
        }
    }
    return;
}

void dfs(int vertex)
{
    if (vertex == v) {
        f2();
        ++count1;
        return;         
    }
    for (int i = 0; i != edge.size(); ++i) {
        if (edge[i][0] == vertex&&path[edge[i][1]]==0) {
            path[edge[i][1]] = 1;
            dfs(edge[i][1]);
            path[edge[i][1]] = 0;
        }
        else  if (edge[i][1] == vertex&&path[edge[i][0]] == 0) {
            path[edge[i][0]] = 1;
            dfs(edge[i][0]);
            path[edge[i][0]] = 0;
        }
    }
    return;
}

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 0; i != m+1; ++i)
    {
        path.push_back(0);
    }
    
    for (int i = 0; i != n-1; ++i)
    {
        cin >> u >> v;
        vector<int> temp;
        temp.push_back(u);
        temp.push_back(v);      
        edge.push_back(temp);
    }
    cin >> u >> v;
    path[u] = 1;

    dfs(u);

    if (count1 == 0) cout << -1;
    else {
        int risk = 0;
        for (map<int, int>::iterator it = map1.begin(); it != map1.end(); ++it) {
            if ((*it).second == count1) ++risk;
        }
        cout << risk;
    }

    return 0;

}

/*
7 6
1 3
2 3
3 4
3 5
4 5
5 6
1 6

*/
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容