1. 程式人生 > >洛谷 P2962 [USACO09NOV]燈Lights

洛谷 P2962 [USACO09NOV]燈Lights

tps hold 題目 cau chang usaco step ring nes

P2962 [USACO09NOV]燈Lights

題目描述

Bessie and the cows were playing games in the barn, but the power was reset and the lights were all turned off. Help the cows get all the lights back on so they can resume their games.

The N (1 <= N <= 35) lights conveniently numbered 1..N and their switches are arranged in a complex network with M (1 <= M <= 595) clever connection between pairs of lights (see below).

Each light has a switch that, when toggled, causes that light -- and all of the lights that are connected to it -- to change their states (from on to off, or off to on).

Find the minimum number of switches that need to be toggled in order to turn all the lights back on.

It‘s guaranteed that there is at least one way to toggle the switches so all lights are back on.

貝希和她的閨密們在她們的牛棚中玩遊戲。但是天不從人願,突然,牛棚的電源跳閘了,所有的燈都被關閉了。貝希是一個很膽小的女生,在伸手不見拇指的無盡的黑暗中,她感到驚恐,痛苦與絕望。她希望您能夠幫幫她,把所有的燈都給重新開起來!她才能繼續快樂地跟她的閨密們繼續玩遊戲! 牛棚中一共有N(1 <= N <= 35)盞燈,編號為1到N。這些燈被置於一個非常複雜的網絡之中。有M(1 <= M <= 595)條很神奇的無向邊,每條邊連接兩盞燈。 每盞燈上面都帶有一個開關。當按下某一盞燈的開關的時候,這盞燈本身,還有所有有邊連向這盞燈的燈的狀態都會被改變。狀態改變指的是:當一盞燈是開著的時候,這盞燈被關掉;當一盞燈是關著的時候,這盞燈被打開。 問最少要按下多少個開關,才能把所有的燈都給重新打開。 數據保證至少有一種按開關的方案,使得所有的燈都被重新打開。

輸入輸出格式

輸入格式:

  • Line 1: Two space-separated integers: N and M.

  • Lines 2..M+1: Each line contains two space-separated integers representing two lights that are connected. No pair will be repeated.

輸出格式:

  • Line 1: A single integer representing the minimum number of switches that need to be flipped in order to turn on all the lights.

輸入輸出樣例

輸入樣例#1:
5 6 
1 2 
1 3 
4 2 
3 4 
2 5 
5 3 
輸出樣例#1:
3 

說明

There are 5 lights. Lights 1, 4, and 5 are each connected to both lights 2 and 3.

Toggle the switches on lights 1, 4, and 5.

思路:meet in the middle

蒟蒻實在不會HZWER大神

#include<map>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
map<long long,int>mp;
int n,m;
int mid,flag,minn=0x7f7f7f7f;
long long ed,qwq[40],mmp[40];
void dfs(int x,long long now,int step){
    if(x==mid+1){
        if(now==ed)
            minn=min(step,minn);
        if(!flag){
            int tmp=mp[now];
            if(!tmp||tmp>step)
                mp[now]=step;
        }
        else{
            int tmp=mp[ed-now];
            if(!tmp)    return ;
            minn=min(tmp+step,minn);
        }
        return ;
    }
    dfs(x+1,now,step);
    dfs(x+1,now^qwq[x],step+1);
}
int main(){
    mmp[1]=1;
    for(int i=2;i<=40;i++)
        mmp[i]=mmp[i-1]<<1;
    scanf("%d%d",&n,&m);
    ed=mmp[n+1]-1;
    for(int i=1;i<=m;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        qwq[x]+=mmp[y];
        qwq[y]+=mmp[x];
    }
    for(int i=1;i<=n;i++)
        qwq[i]+=mmp[i];
    mid=n/2;
    dfs(1,0,0);
    flag=1;
    mid=n;
    dfs(n/2+1,0,0);
    cout<<minn;
}

洛谷 P2962 [USACO09NOV]燈Lights