AtCoder Grand Contest 014 B - Unplanned Queries

題目描述

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.

Then, Aoki gave him M queries. The i-th of them is as follows:

Increment the number written at each edge along the path connecting vertices ai and bi, by one.
After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number. However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints
2≤N≤105
1≤M≤105
1≤ai,bi≤N
ai≠bi

輸入

Input is given from Standard Input in the following format:

N M
a1 b1
:
aM bM

輸出

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

樣例輸入
4 4
1 2
2 4
1 3
3 4
樣例輸出

YES
題目大意:給出n個點和m條路徑,每條路徑上所有的邊的權值都+1,問你能不能構建一個樹使得最後每條邊的權值都是偶數

解法:我們假設有這麼一棵樹,再往樹上加上一個0號節點作爲根,每次讀進來u,v兩個節點,設p爲lca(u,v),我們每次連接u,v就相當於連接u,p和連接v,p,如果我們再把0,p連接兩次,很明顯對答案並沒有影響,這時候連接u,p和連接v,p就變成了連接0,u和連接0,v。很明顯,我們每次連接uiu_i,0和連接pip_i,0。我們假設某一個uiu_i出現了奇數次,那麼uiu_i,0我們必然是連接了奇數次,那麼與uiu_i相連接的某一條邊一定是出現了奇數次,所以我們只需要統計每個點出現的次數,一但所有點出現的次數都是偶數,那麼肯定就存在這樣一棵樹。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int n,m;
int z[maxn];
int main()
{
    scanf("%d%d", &n, &m);
    while (m--)
    {
        int tmp1,tmp2;
        scanf("%d%d", &tmp1, &tmp2);
        ++z[tmp1];
        ++z[tmp2];
    }
    int flag = 1;
    for (int i = 1; i <= n; ++i)
        if (z[i] % 2)
            flag = 0;
    if (flag)
        puts("YES");
    else
        puts("NO");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章