[Codeforces 623A] Graph and String

时间:2024-12-06 23:04:50

[题目链接]

http://codeforces.com/contest/623/problem/A

[算法]

首先 , 所有与其他节点都有连边的节点需标号为'b'

然后 , 我们任选一个节点 , 将其标号为'a' , 然后标记所以该节点能到达的节点

最后 , 我们需要检查这张图是否合法 , 只需枚举两个节点 , 若这两个节点均为'a'或'c' , 那么 , 若两个节点标号不同但有连边 , 不合法 , 如果两个节点标号相同但没有连边 , 也不合法

时间复杂度 : O(N ^ 2)

[代码]

#include<bits/stdc++.h>
using namespace std;
#define MAXN 510 struct edge
{
int to , nxt;
} e[MAXN * MAXN * ]; int tot , n , m;
int deg[MAXN],q[MAXN],head[MAXN];
char ans[MAXN];
bool finished[MAXN];
bool g[MAXN][MAXN]; template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); }
template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); }
template <typename T> inline void read(T &x)
{
T f = ; x = ;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
for (; isdigit(c); c = getchar()) x = (x << ) + (x << ) + c - '';
x *= f;
}
inline void addedge(int u,int v)
{
tot++;
e[tot] = (edge){v,head[u]};
head[u] = tot;
} int main()
{ read(n); read(m);
for (int i = ; i <= m; i++)
{
int u , v;
read(u); read(v);
deg[u]++; deg[v]++;
addedge(u,v);
addedge(v,u);
g[u][v] = g[v][u] = true;
}
for (int i = ; i <= n; i++)
{
if (deg[i] == n - )
{
ans[i] = 'b';
finished[i] = true;
}
}
int l = , r = ;
for (int i = ; i <= n; i++)
{
if (!finished[i])
{
ans[i] = 'a';
finished[i] = true;
q[++r] = i;
break;
}
}
while (l <= r)
{
int cur = q[l++];
for (int i = head[cur]; i; i = e[i].nxt)
{
int v = e[i].to;
if (!finished[v])
{
finished[v] = true;
ans[v] = 'a';
q[++r] = v;
}
}
}
for (int i = ; i <= n; i++)
{
if (!finished[i])
ans[i] = 'c';
}
for (int i = ; i <= n; i++)
{
if (ans[i] == 'b') continue;
for (int j = ; j <= n; j++)
{
if (i == j || ans[j] == 'b') continue;
if (ans[i] == ans[j] && !g[i][j])
{
printf("No\n");
return ;
}
if (ans[i] != ans[j] && g[i][j])
{
printf("No\n");
return ;
}
}
}
printf("Yes\n");
for (int i = ; i <= n; i++) printf("%c",ans[i]);
printf("\n"); return ; }