題意就是看能不能形成歐拉圖,有沒有一條歐拉道路,
圖爲無向圖,那麼需要具備以下幾點才能滿足,聯通且(最多)有2個奇數點
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 34526 | Accepted: 9009 |
Description
Input
Output
Sample Input
blue red red violet cyan blue blue magenta magenta cyan
Sample Output
Possible
代碼
:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int countn;
int countz;
int du[500100];
int fa[500100];
struct node
{
int num;
struct node *next[30];
};
node tire[250005];
node *creat()
{
for(int i=0; i<26; i++)
{
tire[countn].next[i]=NULL;
}
tire[countn].num=0;
return &tire[countn++];
}
int hash(node *&root,char s[])
{
if(!root)
root=creat();
int la=strlen(s);
node *p;
p=root;
for(int i=0; i<la; i++)
{
if(p->next[s[i]-'a']==NULL)
p->next[s[i]-'a']=creat();
p=p->next[s[i]-'a'];
}
if(!p->num)
p->num=countz++;
return p->num;
}
int find(int x)
{
if(x==fa[x])
{
return fa[x];
}
else return fa[x]=find(fa[x]);
}
void Union(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
fa[fx]=fy;
}
}
int main()
{
char s1[30];
char s2[30];
node *root=NULL;
memset(du,0,sizeof(du));
countn=0;
countz=1;
for(int i=0; i<100000; i++)
fa[i]=i;
while(scanf("%s %s",s1,s2)!=EOF)
{
int x=hash(root,s1);
int y=hash(root,s2);
du[x]++;
du[y]++;
Union(x,y);
}
//printf("%d \n",countz);
int flag=1;
int old=0;//奇數的度數大於2個,則不是歐拉圖
for(int i=1; i<countz; i++)
{
//printf("%d ",du[i]);
if(du[i]%2)
{
old++;
}
if(old>2)
{
flag=0;
break;
}
if(find(i)!=find(1))
{
flag=0;
break;
}
}
if(flag)
printf("Possible\n");
else printf("Impossible\n");
}