洛谷__P1333 瑞瑞的木棍(欧拉路径)
题目链接:P1333 瑞瑞的木棍 - 洛谷
题目大意:
给定若干木棍,每根两端有颜色。
要求判断能否将所有木棍连成一条线,使得相邻木棍接触端颜色相同。
思路:
欧拉路径裸体,坑点是要判断图是否联通 (并查集),若不连通肯定是不能连成一条线的
代码:
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>//pb_ds库
#include<cctype>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define mst(a,x) memset(a,x,sizeof (a))
using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
typedef pair<int, int> pii;
const int N = 500086, mod = 998244353;
int n, m;
int d[N];
int p[N];
gp_hash_table<string, int> mp;
int idx = 0;
int find(int u) {
if (p[u] == u) return u;
return p[u] = find(p[u]);
}
void solve() {
int t = 0;
string a, b;
for (int i = 1; i < N; i++) p[i] = i;
while (cin >> a >> b) {
if (!mp[a]) mp[a] = ++idx;
if (!mp[b]) mp[b] = ++idx;
int t1 = mp[a], t2 = mp[b];
d[t1]++, d[t2]++;
t1 = find(t1), t2 = find(t2);
if (t1 != t2) p[t1] = t2;
t = t2;
}
for (int i = 1; i <= idx; i++) {
if (find(i) != find(t)) {//不连通肯定不能连成一条线
cout << "Impossible" << endl;
return;
}
}
int cnt = 0;
for (int i = 1; i <= idx; i++) {
if (d[i] & 1) cnt++;
}
//欧拉路径判断
if (cnt == 0 || cnt == 2) cout << "Possible" << endl;
else cout << "Impossible" << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
// cin >> T;
while (T--) solve();
return 0;
}

浙公网安备 33010602011771号