nyoj_20 吝啬的国度

来源:互联网 发布:利用老域名快速排名 编辑:程序博客网 时间:2024/04/28 22:16
题目连接:点击打开链接

邻接表中的节点储存的有用信息有两点==关联数据域:

1:节点的数据域的父亲是谁==哪一点(数据域)指向我,需要注意的是这里的父亲不是指父节点;

无用信息就是 节点与节点之间的指针域数据;


#include<iostream>#include<algorithm>#include<queue>#include<string.h>using namespace std;const int MAX=100001;typedef struct city{    int to;    struct city *next;}CITY;CITY *head;int city_num,first;queue<CITY>q;CITY city[MAX];        //用来存城市的节点int from[MAX],to[MAX];       //分别保存节点和本节点将要找到的下一个节点的数据域的值CITY *linkk;void creatlink(int from,int to){    CITY *p;    p=(CITY *)malloc (sizeof(CITY));    p->to=to;                  //节点将将向to    p->next=city[from].next;   //头插法    city[from].next=p;}void distroy(){    while(!q.empty()){        q.pop();    }}void bfs(){    from[first]=-1;         //第一个题目说是-1    q.push(city[first]);     //第一个城市节点入队    to[first]=0;              //设为已经被查找过    while(!q.empty()){        CITY p;        p=q.front();        q.pop();        linkk=p.next;        /*        这里是将把一条链上的所有to到的节点依次入队,广搜含义,所以有下面那个循环        */        while(linkk!=NULL){            if(to[linkk->to]){       //如果链上的一个节点的to到的那个节点没有被查找过                from[linkk->to]=p.to;  //被to到的这个节点来自上一条链上的头节点                q.push(city[linkk->to]);  //那么这个节点入队                to[linkk->to]=0;       //标记这个节点被找过了            }            linkk=linkk->next;          //找链上的下一个节点能to到位置        }    }}int main(){    int i,j,times;    head=(CITY *)malloc (sizeof(CITY));    head->next=NULL;    cin>>times;    while(times--){        cin>>city_num>>first;        for(i=1;i<=city_num;i++){        //初始化每一条链的头节点指向本身            city[i].to=i;            city[i].next=NULL;        }        for(i=0;i<city_num-1;i++){            int t1,t2;            cin>>t1>>t2;            creatlink(t1,t2);          //链接表本身定义所导致需要两次            creatlink(t2,t1);        }        memset(to,1,sizeof(to));            // 初始化全部没有找过        bfs();        for(i=1;i<city_num;i++){            cout<<from[i]<<" ";        }        cout<<from[city_num]<<endl;        distroy();    }    return 0;}