清华数据结构无线广播AC100

#pragma warning(disable:4996)
#include<stdio.h>
using namespace std;
#define maxn 10000
#define Flag(i)((i==1)?2:1)
struct listnode
{
    listnode*pre;
    int num = -1;//记录该节点的编号
    listnode() {}
    listnode(int n, listnode*p = NULL) :num(n), pre(p) {}
};
struct p_list
{
    listnode*head, *trail;
    int flag = 0;
    int visit = 0;
    void init();
    p_list() { init(); }
    void insert(int&out);
};
void p_list::init()
{
    head = new listnode();
    trail = new listnode();
    head->pre = trail;
    trail->pre = NULL;
}
void p_list::insert(int&num)//越先进入的元素,越靠近队尾
{
    listnode*p = new listnode(num);
    p->pre = head->pre;
    head->pre = p;
}
p_list country[maxn];
int Queue[maxn];
int hi=0,result=1,trail=0;
void bsf(int pos)
{
    if(country[Queue[hi]].visit == 0)
    {
        auto p = country[pos].head->pre;
         while (p != country[pos].trail)
    {
        if(country[p->num].flag==0)country[p->num].flag = Flag(country[pos].flag);
        else if(country[p->num].flag == Flag(country[pos].flag));
        else{result=-1;break;}
        Queue[hi++]=p->num;
        p=p->pre;
    }
    country[pos].visit=1;
    }
    if(hi>0)
    bsf(Queue[--hi]);

}
void travel(int n, int m)
{
    country[0].flag = 1;
    for (auto i = 0; i<n&&result>0; i++)
    {
        Queue[0]=i;
        bsf(i);
    }
}
int main()
{
#ifndef _OJ_
    freopen("bfs.txt", "r", stdin);
    // freopen("travelout.txt", "w", stdout);
#endif
    int i, j, m, n;
    scanf("%d %d", &n, &m);
    auto t = m;
    while (t--) {
        scanf("%d %d", &i, &j);
        country[i - 1].insert(--j);
        country[j].insert(--i);

    }
    for (auto i = 0; i<n; i++)country[i].flag = 0;
    travel(n, m);
    printf("%d\n", result);
}

先黏贴正确的代码

本人的思路是,先将所有的边都记录下来。如2-4,4-2都得记录

那么就不会出现2初始为0,当2flag值为2正确,flag值为1错误的情况

因为我一旦遇到了4-2边,则立刻可以确定2的flag,而2之所以不同flag取值有不同的答案就是因为4边的影响,故该影响解除

这里需要注意的是,边的输入并不是2-3,2-4,2-5这样好的输入,他有时候可能会输入4-2,4-3这样,所以我就是因为这个折腾了好久,这题目坑我~

猜你喜欢

转载自blog.csdn.net/hgtjcxy/article/details/80627716