bzoj1086: [SCOI2005]王室联邦

来源:互联网 发布:ubuntu jdk aptget 编辑:程序博客网 时间:2024/04/28 21:42

这道题有点坑。。
不用输出最优解。。
只需输出一组解。。
用一个栈来存当前省的城市。。
一个暴搜O(n)的算法就可以过。。
代码挺简单的。。

#include<cstdio>#include<cstring>#include<iostream>using namespace std;struct node {    int x,y,next;}a[2100];int len,last[1100];void ins(int x,int y) {    len++;    a[len].x=x;a[len].y=y;    a[len].next=last[x];last[x]=len;}int top,m,sta[1100],n;int B,d[1100],g[1100];void dfs(int x,int fa) {    int tt=top;    for(int k=last[x];k;k=a[k].next) {        int y=a[k].y;        if(y!=fa) {            dfs(y,x);            if(top-tt>=B) {                g[++m]=x;                while(top!=tt)                    d[sta[top--]]=m;            }        }    }    sta[++top]=x;}int main() {    scanf("%d%d",&n,&B);    len=0;memset(last,0,sizeof(last));    for(int i=1;i<n;i++) {        int x,y;scanf("%d%d",&x,&y);        ins(x,y);ins(y,x);    }    m=0;top=0;    memset(sta,0,sizeof(sta));    dfs(1,0);    while(top!=0)        d[sta[top--]]=m;    printf("%d\n",m);    for(int i=1;i<n;i++)        printf("%d ",d[i]);    printf("%d\n",d[n]);    for(int i=1;i<m;i++)        printf("%d ",g[i]);    printf("%d\n",g[m]);    return 0;}
0 0
原创粉丝点击