Tree Restoring
阿新 • • 發佈:2018-04-13
distance constrain there show owin exists sat its 分支
One day, Takahashi gave him an integer sequence of length N, a1,a2,…,aN, which made him want to construct a tree.
Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i=1,2,…,N, the distance between vertex i and the farthest vertex from it is ai, assuming that the length of each edge is 1.
Determine whether such a tree exists.
Constraints
2≤N≤100
1≤ai≤N?1
The input is given from Standard Input in the following format:
N
a1 a2 … aN
題目描述
Aoki loves numerical sequences and trees.One day, Takahashi gave him an integer sequence of length N, a1,a2,…,aN, which made him want to construct a tree.
Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i=1,2,…,N, the distance between vertex i and the farthest vertex from it is ai, assuming that the length of each edge is 1.
Determine whether such a tree exists.
Constraints
2≤N≤100
1≤ai≤N?1
輸入
N
a1 a2 … aN
輸出
If there exists a tree that satisfies the condition, print ‘Possible‘. Otherwise, print ‘Impossible‘.樣例輸入
5
3 2 2 3 3
樣例輸出
Possible
提示
The diagram above shows an example of a tree that satisfies the conditions. The red arrows show paths from each vertex to the farthest vertex from it.
解析
代碼比較長,整體思路就是先排序,找到最長的那一路,然後確定這個長度為主幹(比如說最長的是n,那主幹長度是n+1),然後把其他的分支都可以插在中間,但是這些分路構成的長度不能長於主幹長度,因此這些分支的距離就是主幹中間的最長距離加一,就比如說樣例,主幹長度是3,因此有4個數為主幹,因此這四個數的最長距離為3、2、2、3,剩下的一個可以在中間的兩個二中任選一個加一,就是3、2、2、3、3。
#include <bits/stdc++.h> using namespace std; typedef long long ll; int s[200]; int main() { ios::sync_with_stdio(View Codefalse); int i,j,k,m,n; int ans=0,cnt=0; int flag=0; int flag1=0; cin>>n; for(i=1; i<=n; i++) cin>>s[i]; sort(s+1,s+n+1); int gen=s[n],num=0; for(i=1; i<=n; i++) if(s[i]==gen) num++; if(num==1) cout<<"Impossible"<<endl; else { if(gen%2!=0) { k=(gen+1)/2; m=k; for(i=1;i<=n;i++) { if(s[i]==k) { cnt++; } if(cnt>2) { cout<<"Impossible"<<endl; return 0; } } for(i=1; i<=n; i++) { if(s[i]<k) { cout<<"Impossible"<<endl; return 0; } if(m==s[i]) { ans++; } if(ans==2) { ans=0; m++; } if(m==(gen+1)) { cout<<"Possible"<<endl; return 0; } } cout<<"Impossible"<<endl; } else { k=gen/2; m=k; for(i=1;i<=n;i++) { if(s[i]==k) { cnt++; } if(cnt>1) { cout<<"Impossible"<<endl; return 0; } } for(i=1; i<=n; i++) { if(s[i]<k) { cout<<"Impossible"<<endl; return 0; } if(m==s[i]) { ans++; } if(ans==2&&flag) { ans=0; m++; } else if(ans==1&&!flag) { ans=0; m++; flag=1; } if(m==gen+1) { cout<<"Possible"<<endl; return 0; } } cout<<"Impossible"<<endl; } } return 0; }
Tree Restoring