1. 程式人生 > >Codeforces 369 C Valera and Elections

Codeforces 369 C Valera and Elections

開始 () codeforce .com for def clas 遠的 sizeof

Valera and Elections

題意:現在有n個候選人, 有n-1條路, 如果選擇了這個候選人, 這個候選人就會將從自己這個城市到1號城市上所有壞的路都修復一下,現在求最小的候選人數目, 如果答案有多種情況輸出任何一種都可以。

輸入:x y k 表示x與y之間有一條雙向通道, k==1 表示這路是好的, k == 2表示這條路是壞的。

題解: 從1開始dfs搜索, 往外走, 如果遇到壞的城市就標記一下, 然後繼續往外走, 如果更遠的地方有一個壞的路就用更遠地方的城市候選人代替這個標記的這個人。

代碼:

 1 #include<bits/stdc++.h>
 2 using
namespace std; 3 #define fi first 4 #define se second 5 typedef pair<int, int> pll; 6 const int INF = 0x3f3f3f3f; 7 const int N = 1e5+5; 8 vector<pll> E[N]; 9 bool vis[N]; 10 int cnt = 0; 11 void dfs(int x, int n, int last) 12 { 13 for(int i = 0; i < E[x].size(); i++) 14 {
15 pll tmp = E[x][i]; 16 if(tmp.fi == last) continue; 17 if(tmp.se == 2) 18 { 19 cnt++; 20 if(vis[n]) cnt--, vis[n] = 0; 21 vis[tmp.fi] = 1; 22 dfs(tmp.fi, tmp.fi, x); 23 } 24 else dfs(tmp.fi, n, x); 25 }
26 } 27 int main() 28 { 29 int n; 30 scanf("%d",&n); 31 int x, y, ok; 32 for(int i = 1; i < n; i++) 33 { 34 scanf("%d%d%d",&x,&y,&ok); 35 E[x].push_back(pll(y,ok)); 36 E[y].push_back(pll(x,ok)); 37 } 38 memset(vis, 0, sizeof(vis)); 39 dfs(1,0,0); 40 printf("%d\n", cnt); 41 for(int i = 2; i <= n; i++) 42 if(vis[i]) printf("%d ",i); 43 return 0; 44 }

Codeforces 369 C Valera and Elections