当前位置: 代码迷 >> 综合 >> Livestock Lineup//全排列//排位1
  详细解决方案

Livestock Lineup//全排列//排位1

热度:89   发布时间:2024-01-10 06:48:55.0

Livestock Lineup//全排列


题目

Every day, Farmer John milks his 8 dairy cows, named Bessie, Buttercup, Belinda, Beatrice, Bella, Blue, Betsy, and Sue. The cows are rather picky, unfortunately, and require that Farmer John milks them in an order that respects N constraints (1≤N≤7). Each constraint is of the form “X must be milked beside Y”, stipulating that cow X must appear in the milking order either directly after cow Y or directly before cow Y.

Please help Farmer John determine an ordering of his cows that satisfies all of these required constraints. It is guaranteed that an ordering is always possible. If several orderings work, then please output the one that is alphabetically first. That is, the first cow should have the alphabetically lowest name of all possible cows that could appear first in any valid ordering. Among all orderings starting with this same alphabetically-first cow, the second cow should be alphabetically lowest among all possible valid orderings, and so on.

Input
The first line of input contains N. The next N lines each contain a sentence describing a constraint in the form “X must be milked beside Y”, where X and Y are names of some of Farmer John’s cows (the eight possible names are listed above).

Output
Please output, using 8 lines, an ordering of cows, one cow per line, satisfying all constraints. If multiple orderings work, output the one that is alphabetically earliest.

Example

input
3
Buttercup must be milked beside Bella
Blue must be milked beside Bella
Sue must be milked beside Beatrice

output
Beatrice
Sue
Belinda
Bessie
Betsy
Blue
Bella
Buttercup
题意
某牛在某牛旁边,总共8头,求其排列
链接:http://codeforces.com/group/5yyKg9gx7m/contest/269717/problem/G

思路

数量少,暴力全排列,algorithm里有现成全排列,用就完事了

代码

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
#include <deque>
#include <queue>
#include <cmath>
#include <stack>
#define pi 3.1415926
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;string cow[8];
string a[1000],b[1000],none;
int main()
{
    cow[0]="Beatrice";cow[1]="Belinda";cow[2]="Bella";cow[3]="Bessie";cow[4]="Betsy";cow[5]="Blue";cow[6]="Buttercup";cow[7]="Sue";int t1,t2;int n;cin>>n;for(int i=0;i<n;i++){
    cin>>a[i]>>none>>none>>none>>none>>b[i];}int judge=1;do{
    judge=1;for(int i=0;i<n;i++){
    int t1,t2;for(int j=0;j<8;j++){
    if(a[i]==cow[j]) t1=j;if(b[i]==cow[j]) t2=j;}if(abs(t1-t2)>1){
    judge=0;break;}}if(judge==1){
    for(int i=0;i<8;i++)cout<<cow[i]<<endl;return 0;}}while(next_permutation(cow,cow+8));return 0;
}

注意