codeforces 369C Valera and Elections DFS

The city Valera lives in is going to hold elections to the city Parliament.The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.

題解:有n個節點n-1條邊。題意保證所給的圖是一棵樹。x,y表示x到y的路線。t==2表示這條路是壞的,t==1表示這條路沒有壞。當選一塊區域修路時,會把從該塊區域到1號區域所經過的道路全部修好。問最少可以從幾個區域開始修使得全部壞的路修好。

這個dfs寫法非常巧妙。

#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#define maxn 100010
using namespace std;
vector<int>a[maxn],ans;
int n;
void dfs(int rt,int x,int z)
{
    int y,tmp,k;
    tmp=ans.size();
    for(int i=0;i<a[x].size();i++)
    {
        y=a[x][i];
        if(y<0)
        {
            y=y*-1;
            k=2;
        }
        else
            k=1;
        if(y==rt)
            continue;
        dfs(x,y,k);
    }
    if(z==2&&ans.size()==tmp)
        ans.push_back(x);
}
int main()
{
    int x,y,t;
    while(cin>>n)
    {
        ans.clear();
        a[maxn].clear();
        for(int i=0;i<n-1;i++)
        {
            cin>>x>>y>>t;
            a[x].push_back(y*(3-2*t));
            a[y].push_back(x*(3-2*t));
        }
        dfs(0,1,1);
        cout<<ans.size()<<endl;
        for(int i=0;i<ans.size();i++)
        {
            if(i==0)
                cout<<ans[i];
            else
                cout<<" "<<ans[i];
        }
        cout<<endl;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章