Problem D: The Necklace
My little sister had a beautiful necklace made of colorful beads. Two successive beads in the necklace shared a common color at their meeting point. The figure below shows a segment of the necklace:Problem D: The Necklace |

Please help me write a program to solve the problem.
Input
The input contains T test cases. The first line of the input contains the integer T.The first line of each test case contains an integer N (

Output
For each test case in the input first output the test case number as shown in the sample output. Then if you apprehend that some beads may be lost just print the sentence ``some beads may be lost" on a line by itself. Otherwise, print N lines with a single bead description on each line. Each bead description consists of two integers giving the colors of its two ends. For
Print a blank line between two successive test cases.
Sample Input
2 5 1 2 2 3 3 4 4 5 5 6 5 2 1 2 2 3 4 3 1 2 4
Sample Output
Case #1 some beads may be lost Case #2 2 1 1 3 3 4 4 2 2 2
Miguel Revilla
2000-12-28
euler graph歐拉路計算 此處應以點為顏色,給定的bead為邊作計算,等於在一個有自環與多重邊的無向圖上找歐拉路徑 如果以bead為點的話,會變成在無向圖上找唯一路徑滿足起始顏色=終了顏色,計算複雜度過高會超時
#include<stdio.h>
#include<cstring>
#include<vector>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0
using namespace std;
int cases=1,N,top;
int adj[50][1000],idx[50][50],cnt[50],q[2001];
int euler(int v){
int b,w,i;
for(;cnt[v]>0;v=w){
if(DBG)printf("euler: %d\n",1+v);
q[top++]=v;
w=adj[v][--cnt[v]];
for(i=cnt[v]-1;i>=0;i--)if(adj[v][i]==w){idx[v][w]=i;break;} //update idx on missing end
b=adj[w][--cnt[w]];
adj[w][idx[w][v]]=b,idx[w][b]=idx[w][v];
for(i=cnt[w]-1;i>=0;i--)if(adj[w][i]==v){idx[w][v]=i;break;} //update idx on missing end
}
return v;
}
void ans(){
int v;
bool fail=0;
vector<int>seq;
rep(i,50){if(cnt[i]%2)fail=1;}
printf("Case #%d\n",cases++);
for(v=0;v<50;v++)if(cnt[v])break;
seq.push_back(v);
if(!fail){
for(top=0;euler(v)==v&⊤){
v=q[--top];
if(DBG)printf("push %d\n",v);
seq.push_back(v);
}
if(seq.size()==N+1)rep(i,seq.size()-1)printf("%d %d\n",seq[i]+1,seq[i+1]+1);
else printf("some beads may be lost\n");
}
else printf("some beads may be lost\n");
}
int main(){
int a,b,n;
bool ll=0;
scanf("%d",&n);
rep(i,n){
memset(cnt,0,sizeof(cnt));
scanf("%d",&N);
rep(i,N)scanf("%d%d",&a,&b),a--,b--,adj[a][cnt[a]++]=b,adj[b][cnt[b]++]=a;
if(ll)printf("\n");ll=1;
rep(i,50)rep(j,cnt[i])idx[i][ adj[i][j] ] = j;
ans();
}
}
沒有留言:
張貼留言