編程之美15-彩色的樹,編程之美15-

來源:互聯網
上載者:User

編程之美15-彩色的樹,編程之美15-

       看第一眼以為這個題不好做,把過多的時間浪費在第二題上了。《彩色的樹》這題是一個頂點染色的問題,用點dfs去不斷染色,然後記錄子樹的個數就好,題目的內容如下:
       給定一棵n個節點的樹,節點編號為1, 2, …, n。樹中有n - 1條邊,任意兩個節點間恰好有一條路徑。這是一棵彩色的樹,每個節點恰好可以染一種顏色。初始時,所有節點的顏色都為0。現在需要實現兩種操作:

#include <stdio.h>#include <map>#include <iostream>#include <string>#include <vector>#include <math.h>#include <string.h>#include <stdlib.h>#include <algorithm>#define INF 99999999#define MAX_V 200000using namespace std;int vist[10001];int ma;int N;int color[MAX_V];vector<int> G[MAX_V];void dfs(int i) {    vist[i] = 1;    int k;    for(k=0; k<G[i].size();k++) {        if(color[i]==color[G[i][k]] && vist[G[i][k]] == 0) {            dfs(G[i][k]);        }    }    return;}int main(int argc, char* argv[]){    freopen("input.txt", "r", stdin);    int TC,C;    int i,j;    int a,b,q,l,m,n;    cin>>TC;    for( C = 1; C <= TC; C++)    {        cin>>N;        memset(vist, 0, sizeof(vist));        ma = 0;        for(i = 0; i<N-1; i++) {            color[i+1] = 0;            cin>>a>>b;            G[a].push_back(b);            G[b].push_back(a);        }        color[N] = 0;        memset(vist, 0, sizeof(vist));        for(i = 1; i<= N; i++) {            if(vist[i]==0){                ma++;                dfs(i);            }        }        cin>>q;        cout<<"Case #"<<C<<":"<<endl;        for(i = 0; i<q; i++) {            cin>>l;            if(l==1) {                cout<<ma<<endl;                continue;            }            cin>>m>>n;            color[m] = n;            ma=0;            memset(vist, 0, sizeof(vist));            for(j = 1; j<= N; j++) {                if(vist[j]==0){                    ma++;                    dfs(j);                }            }        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.