Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 23; const int MOD = 1e9 + 7; const int SZ = 2e5 + 100; vector<pair<int, int> > G[SZ]; vector<int> ans[SZ]; int nr[SZ]; void dfs(int v, int par) { int p = 0; for (auto& it : G[v]) { int u = it.first, id = it.second; if (u == par) continue; ++p; if (p == nr[v]) ++p; ans[p].push_back(id); nr[u] = p; dfs(u, v); } } int main() { ios_base::sync_with_stdio(0); int n, a, b, st = 1; cin >> n; for (int i = 1; i < n; ++i) { cin >> a >> b; G[a].emplace_back(b, i); G[b].emplace_back(a, i); if (G[a].size() > G[st].size()) { st = a; } if (G[b].size() > G[st].size()) { st = b; } } dfs(st, -1); stringstream ss; ss << G[st].size() << "\n"; for (int i = 1; i <= G[st].size(); ++i) { ss << ans[i].size(); for (auto it : ans[i]) { ss << " " << it; } ss << "\n"; } cout << ss.str(); return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.io.*; import java.util.*; /* */ public class C { static FastReader sc=null; static int days[]; public static void main(String[] args) { sc=new FastReader(); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(); Node nodes[]=new Node[n]; for(int i=0;i<n;i++)nodes[i]=new Node(i); for(int i=0;i+1<n;i++) { int v=sc.nextInt()-1,w=sc.nextInt()-1; nodes[v].adj.add(new Edge(i,nodes[w])); nodes[w].adj.add(new Edge(i,nodes[v])); nodes[v].indeg++; nodes[w].indeg++; } int s=0; for(Node nn:nodes)s=Math.max(s, nn.indeg); days=new int[n-1]; dfs(nodes[0],null,-1); //print(days); ArrayList<Integer> ans[]=new ArrayList[s]; for(int i=0;i<s;i++)ans[i]=new ArrayList<>(); for(int i=0;i+1<n;i++) { ans[days[i]].add(i+1); } out.println(s); for(int i=0;i<s;i++) { out.print(ans[i].size()+" "); for(int e:ans[i])out.print(e+" "); out.println(); } out.close(); } static void dfs(Node v,Node par,int prev) { int curr=0; for(Edge e:v.adj) { Node nn=e.to; if(nn==par)continue; if(curr==prev)curr++; days[e.id]=curr; dfs(nn,v,curr); curr++; } } static class Node{ int id,indeg; ArrayDeque<Edge> adj=new ArrayDeque<>(); Node(int id){ this.id=id; } } static class Edge{ int id,day; Node to; Edge(int id,Node to){ this.id=id; this.to=to; } } static int[] ruffleSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al); for(int i=0;i<a.length;i++)a[i]=al.get(i); return a; } static void print(int a[]) { for(int e:a) { System.out.print(e+" "); } System.out.println(); } static class FastReader{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while(!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); return a; } } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<vector<pair<int, int> > > g(200100); bool used[200100]; int wayChet[200100]; int wayTime[200100]; vector<vector<int> > res(200100); void dfs(int j, int last) { used[j] = 1; int time = 1; if (last == 1) time = 2; if (last == 0) time = 1; for (int i = 0; i < g[j].size(); i++) { if (used[g[j][i].first] == 0) { wayTime[g[j][i].second] = time; dfs(g[j][i].first, time); time++; if (time == last) time++; } } } int main() { ios::sync_with_stdio(false); int n; cin >> n; n--; for (int i = 0; i < n; i++) { int tmp1, tmp2; cin >> tmp1 >> tmp2; g[tmp1].push_back(make_pair(tmp2, i)); g[tmp2].push_back(make_pair(tmp1, i)); } for (int i = 1; i <= n + 2; i++) { if (g[i].size() == 1) { int last = 0; dfs(i, last); } } int count = 0; for (int i = 0; i <= n + 2; i++) { if (count < wayTime[i]) count = wayTime[i]; res[wayTime[i]].push_back(i); } cout << count << endl; for (int i = 1; i <= n + 2; i++) { if (res[i].size() > 0) { cout << res[i].size() << " "; for (int j = 0; j < res[i].size(); j++) { cout << res[i][j] + 1 << " "; } cout << endl; } } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int maxn = 2e5 + 10; int n, k, col[maxn]; vector<pair<int, int> > g[maxn]; vector<int> d[maxn]; void dfs(int v, int p) { int mx = 1; for (int i = 0; i < g[v].size(); i++) { if (g[v][i].first != p) { if (mx == col[v]) mx++; col[g[v][i].first] = mx; d[mx].push_back(g[v][i].second); k = max(mx, k); mx++; dfs(g[v][i].first, v); } } } int main() { cin >> n; for (int i = 1; i < n; i++) { int v, u; cin >> v >> u; g[u].push_back(make_pair(v, i)); g[v].push_back(make_pair(u, i)); } dfs(1, 0); cout << k << endl; for (int i = 1; i <= k; i++) { cout << d[i].size() << " "; for (int j = 0; j < d[i].size(); j++) cout << d[i][j] << " "; cout << endl; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 7; vector<pair<int, int> > adj[N]; vector<int> ans[N]; void dfs(int u, int p, int idx) { int cnt = 0; for (auto it : adj[u]) if (it.first != p) { ++cnt; cnt += (cnt == idx); ans[cnt].push_back(it.second); dfs(it.first, u, cnt); } } int main() { ios_base ::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, root = 1; cin >> n; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; adj[u].push_back({v, i}); adj[v].push_back({u, i}); if (adj[u].size() > adj[root].size()) root = u; if (adj[v].size() > adj[root].size()) root = v; } dfs(root, 0, 0); cout << (int)adj[root].size() << endl; for (int i = 1; i <= adj[root].size(); i++) { cout << ans[i].size() << " "; for (int j : ans[i]) cout << j << " "; cout << endl; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; struct Valence { int index; int valence; bool operator<(Valence const &b) const { return valence < b.valence; } }; struct Edge { int from; int to; }; struct EdgeId { int edge; int id; bool operator<(EdgeId const &b) const { return edge < b.edge; } bool operator==(EdgeId const &b) const { return edge == b.edge; } }; std::stack<int> dfsStack; Edge dfs(std::vector<bool> &used, int vertex, std::vector<std::vector<EdgeId>> &graph, std::array<Valence, 200001> &vertexValence) { dfsStack.push(vertex); int edgeFrom = -1; int maxValence = -1; int edgeTo = -1; while (!dfsStack.empty()) { vertex = dfsStack.top(); dfsStack.pop(); used[vertex] = true; if (vertexValence[vertex].valence > maxValence) { maxValence = vertexValence[vertex].valence; edgeFrom = vertex; } int maxValenceTo = -1; for (auto &u : graph[vertex]) { if (edgeFrom == vertex) { if (vertexValence[u.edge].valence > maxValenceTo) { maxValenceTo = vertexValence[u.edge].valence; edgeTo = u.edge; } } if (!used[u.edge]) { if (vertexValence[u.edge].valence > 1) { dfsStack.push(u.edge); } else { used[u.edge] = true; } } } } Edge res; res.from = edgeFrom; res.to = edgeTo; return res; } std::queue<int> bfsStarQueue; void bfsStar(std::vector<bool> &used, int vertex, std::vector<std::vector<EdgeId>> &graph) { used[vertex] = true; for (auto &u : graph[vertex]) { used[u.edge] = true; } } struct Work { int vertexId; bool isWorking; }; std::queue<Work> bfsDeleteQueue; void bfsDelete(std::vector<bool> &used, int vertex, std::vector<std::vector<EdgeId>> &graph, std::array<Valence, 200001> &vertexValence, std::vector<std::vector<int>> &answers, int day) { Work firstWork; firstWork.isWorking = false; firstWork.vertexId = vertex; bfsDeleteQueue.push(firstWork); while (!bfsDeleteQueue.empty()) { Work top = bfsDeleteQueue.front(); bfsDeleteQueue.pop(); used[top.vertexId] = true; int maxValence = -1; EdgeId EdgeTo; EdgeTo.edge = -1; EdgeTo.id = -1; if (top.isWorking == false) { for (auto &u : graph[top.vertexId]) { if (!used[u.edge] && vertexValence[u.edge].valence > maxValence) { maxValence = vertexValence[u.edge].valence; EdgeTo.edge = u.edge; EdgeTo.id = u.id; } } } for (auto &u : graph[top.vertexId]) { if (!used[u.edge]) { if (u.edge != EdgeTo.edge) { Work newWork; newWork.isWorking = false; newWork.vertexId = u.edge; if (vertexValence[u.edge].valence > 1) { bfsDeleteQueue.push(newWork); } else { used[u.edge] = true; } } else { Work newWork; newWork.isWorking = true; newWork.vertexId = u.edge; if (vertexValence[u.edge].valence > 1) { bfsDeleteQueue.push(newWork); } else { used[u.edge] = true; } } } } if (top.isWorking == false && EdgeTo.edge != -1) { EdgeId Edgetop; Edgetop.edge = top.vertexId; graph[top.vertexId].erase(find(graph[top.vertexId].begin(), graph[top.vertexId].end(), (EdgeTo))); graph[EdgeTo.edge].erase( find(graph[EdgeTo.edge].begin(), graph[EdgeTo.edge].end(), Edgetop)); vertexValence[top.vertexId].valence--; vertexValence[EdgeTo.edge].valence--; answers[day].push_back(EdgeTo.id); } } } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int vertexSize; int edgeSize; int day = 0; std::array<Valence, 200001> vertexValence; cin >> vertexSize; edgeSize = vertexSize - 1; std::vector<bool> used(vertexSize); std::vector<bool> star(vertexSize); std::vector<std::vector<EdgeId>> graph(vertexSize); std::vector<std::vector<int>> answers(vertexSize); std::vector<pair<int, int>> starVertexDay; starVertexDay.reserve(200001); for (int i = 0; i < vertexSize; i++) { vertexValence[i].valence = 0; vertexValence[i].index = i; used[i] = 0; answers[i].reserve(200); } for (int i = 0; i < edgeSize; i++) { int p1, p2; cin >> p1 >> p2; p1--; p2--; EdgeId first, second; first.edge = p1; first.id = i + 1; second.edge = p2; second.id = i + 1; graph[p1].push_back(second); graph[p2].push_back(first); vertexValence[p1].valence++; vertexValence[p2].valence++; } std::vector<bool> usedBFSDelete(vertexSize); bool loop = true; std::vector<int> go[2]; int id = 0; go[0].resize(vertexSize); go[1].resize(vertexSize); int count[2]; count[0] = vertexSize; for (int i = 0; i < count[0]; i++) { go[id][i] = i; } while (loop) { loop = false; count[1 - id] = 0; for (int i = 0; i < count[id]; i++) { if (!star[go[id][i]] && graph[go[id][i]].size() > 0) { used[go[id][i]] = false; go[1 - id][count[1 - id]++] = go[id][i]; usedBFSDelete[go[id][i]] = false; } } id = 1 - id; for (int i = 0; i < count[id]; i++) { if (used[go[id][i]]) { continue; } loop = true; Edge res = dfs(used, go[id][i], graph, vertexValence); if (vertexValence[res.to].valence == 1) { bfsStar(star, res.from, graph); starVertexDay.push_back(std::pair<int, int>(day, res.from)); } else { bfsDelete(usedBFSDelete, res.from, graph, vertexValence, answers, day); } } day++; } int all = day - 1; for (pair<int, int> &dayAndstar : starVertexDay) { int startDay = dayAndstar.first; int starId = dayAndstar.second; int endDay = startDay + vertexValence[starId].valence; all = max(all, endDay); auto StarTo = graph[starId].begin(); for (int i = startDay; i < endDay; i++) { answers[i].push_back((*StarTo).id); ++StarTo; } } std::cout << all << "\n"; for (int i = 0; i < all; i++) { std::cout << answers[i].size() << " "; for (int j = 0; j < answers[i].size(); j++) { std::cout << answers[i][j] << " "; } std::cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<int> ans[200005]; vector<pair<int, int> > g[200005]; int n, m, k, i, j, a[200005], b[200005], res; set<int> st; void dfs(int v, int p, int c) { int cur = 1; for (int j = 0; j < g[v].size(); j++) if (g[v][j].first != p) { if (cur == c) cur++; res = max(res, cur); ans[cur].push_back(g[v][j].second); dfs(g[v][j].first, v, cur); cur++; } } int main() { cin >> n; for (i = 1; i < n; i++) { cin >> a[i] >> b[i]; g[a[i]].push_back(make_pair(b[i], i)); g[b[i]].push_back(make_pair(a[i], i)); } dfs(1, 0, 123123123); cout << res << endl; for (i = 1; i <= res; i++) { cout << ans[i].size() << " "; for (j = 0; j < ans[i].size(); j++) cout << ans[i][j] << " "; cout << endl; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<vector<int> > g; bool used[1234567]; map<pair<int, int>, int> mapka; void dfs(int v, vector<vector<int> >& ans, int p = -1) { used[v] = 1; int cur = 0; for (int i = 0; i < g[v].size(); ++i) { int to = g[v][i]; if (!used[to]) { if (cur > p) { ans[cur].push_back(mapka[make_pair(v, to)]); dfs(to, ans, cur); ++cur; } else { if (cur == p) { ++cur; } ans[cur].push_back(mapka[make_pair(v, to)]); dfs(to, ans, cur); ++cur; } } } } int main() { cin.tie(0); ios_base::sync_with_stdio(0); int n; cin >> n; g.resize(n + 1); int mx = 0; vector<int> h(n + 1, 0); for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; mapka[make_pair(u, v)] = i + 1; mapka[make_pair(v, u)] = i + 1; g[u].push_back(v); g[v].push_back(u); h[u]++, h[v]++; } for (int i = 1; i <= n; ++i) mx = max(mx, h[i]); vector<vector<int> > ans(mx); dfs(1, ans); cout << mx << "\n"; for (int i = 0; i < mx; ++i) { cout << ans[i].size() << " "; for (int j = 0; j < ans[i].size(); ++j) cout << ans[i][j] << " "; cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.io.*; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by Leonti on 2016-03-20. */ public class C { public static void main(String[] args) { InputReader inputReader = new InputReader(System.in); PrintWriter printWriter = new PrintWriter(System.out, true); int n = inputReader.nextInt(); ArrayDeque<Integer[]>[] adj = new ArrayDeque[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayDeque<>(); } for (int i = 0; i < n - 1; i++) { int u = inputReader.nextInt() - 1; int v = inputReader.nextInt() - 1; adj[u].offer(new Integer[] {v, i + 1}); adj[v].offer(new Integer[] {u, i + 1}); } int count = 0; ArrayDeque<Integer>[] schedule = new ArrayDeque[n + 1]; for (int i = 0; i < n; i++) { schedule[i] = new ArrayDeque<>(); } int[][] nextFree = new int[n][2]; boolean[] isVisited = new boolean[n]; ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(0); isVisited[0] = true; while (!stack.isEmpty()) { int u = stack.poll(); for (Integer[] k : adj[u]) { int v = k[0]; if (!isVisited[v]) { if (nextFree[u][0] + 1 != nextFree[u][1]) { nextFree[v][1] = ++nextFree[u][0]; } else { nextFree[u][0] += 2; nextFree[v][1] = nextFree[u][0]; } count = count < nextFree[u][0] ? nextFree[u][0] : count; schedule[nextFree[u][0]].offer(k[1]); stack.push(v); isVisited[v] = true; } } } printWriter.println(count); for (int i = 1; i <= count; i++) { printWriter.print(schedule[i].size() + " "); for (Integer j : schedule[i]) { printWriter.print(j + " "); } printWriter.println(); } printWriter.close(); } private static class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public int[] nextIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; ++i) { array[i] = nextInt(); } return array; } public long[] nextLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; ++i) { array[i] = nextLong(); } return array; } public double[] nextDoubleArray(int size) { double[] array = new double[size]; for (int i = 0; i < size; ++i) { array[i] = nextDouble(); } return array; } public String[] nextStringArray(int size) { String[] array = new String[size]; for (int i = 0; i < size; ++i) { array[i] = next(); } return array; } public boolean[][] nextBooleanTable(int rows, int columns, char trueCharacter) { boolean[][] table = new boolean[rows][columns]; for (int i = 0; i < rows; ++i) { String row = next(); assert row.length() == columns; for (int j = 0; j < columns; ++j) { table[i][j] = (row.charAt(j) == trueCharacter); } } return table; } public char[][] nextCharTable(int rows, int columns) { char[][] table = new char[rows][]; for (int i = 0; i < rows; ++i) { table[i] = next().toCharArray(); assert table[i].length == columns; } return table; } public int[][] nextIntTable(int rows, int columns) { int[][] table = new int[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { table[i][j] = nextInt(); } } return table; } public long[][] nextLongTable(int rows, int columns) { long[][] table = new long[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { table[i][j] = nextLong(); } } return table; } public double[][] nextDoubleTable(int rows, int columns) { double[][] table = new double[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { table[i][j] = nextDouble(); } } return table; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = readLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(readLine()); } return tokenizer.nextToken(); } public String readLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " = " << arg1 << '\n'; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " = " << arg1 << " || "; __f(comma + 1, args...); } template <class Ch, class Tr, class Container> basic_ostream<Ch, Tr>& operator<<(basic_ostream<Ch, Tr>& os, Container const& x) { os << "{ "; for (auto& y : x) os << y << " ; "; return os << "}"; } template <class X, class Y> ostream& operator<<(ostream& os, pair<X, Y> const& p) { return os << "[ " << p.first << ", " << p.second << "]"; } long long power(long long x, long long y, long long p) { long long res = 1; x = x % p; while (y > 0) { if (y & 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } const long long L = 2e5 + 5; set<long long> ad[L]; long long deg[L]; long long vis[L]; map<pair<long long, long long>, long long> edge; vector<long long> vals[L]; long long ans; void dfs(long long ind, long long day) { vis[ind] = 1; day %= ans; for (long long v : ad[ind]) { if (!vis[v]) { vals[day].push_back(edge[{ind, v}]); dfs(v, day + 1); day = (day + 1) % ans; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long n, u, v; cin >> n; for (long long i = 0; i < n - 1; i++) { cin >> u >> v; ad[u].insert(v); ad[v].insert(u); edge[{u, v}] = i + 1; edge[{v, u}] = i + 1; deg[u]++; deg[v]++; ans = max(ans, deg[u]); ans = max(ans, deg[v]); } cout << ans << '\n'; long long ind = 1; for (long long i = 1; i <= n; i++) { if (deg[i] == ans) { ind = i; break; } } dfs(ind, 0); for (long long i = 0; i < ans; i++) { cout << (long long)(vals[i].size()) << ' '; for (long long ind : vals[i]) cout << ind << ' '; cout << '\n'; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import os,sys n = int(raw_input()) nbs = [[] for i in xrange(n+1)] t=sys.stdin.read().split("\n") for i in range(n-1): l=t[i] u,v=map(int,l.split()) nbs[u].append((v,i+1)) nbs[v].append((u,i+1)) left,right = 0,1 ans = [[] for i in xrange(n+1)] total = 0 stateL = [[1,1,0] for i in xrange(1,n+1)] while left<right: x,y,color = stateL[left] c = 1 left+=1 total = max(total,color) for nb in nbs[x]: xnb,iseq = nb if xnb != y: if c == color: c+=1 ans[c].append(iseq) stateL[right] = [xnb,x,c] c+=1 right+=1 #print stateL print total for i in xrange(1,total+1): print len(ans[i]),' '.join(map(str,ans[i]))
PYTHON
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<pair<int, int>> g[200007]; bool visited[200007]; int reservedDay[200007]; int res[200007]; vector<int> printRes[200007]; int maxDay = 0; void visit(int u) { visited[u] = true; int avDay = 1; for (int i = 0; i < g[u].size(); i++) { if (!visited[g[u][i].second]) { if (reservedDay[u] == avDay) { avDay++; } res[g[u][i].first] = avDay; reservedDay[g[u][i].second] = avDay; printRes[avDay].push_back(g[u][i].first); avDay++; visit(g[u][i].second); } } maxDay = max(maxDay, avDay); } int main() { cin.sync_with_stdio(false); int n; cin >> n; vector<pair<int, int>> v; int a, b; v.push_back(make_pair(0, 0)); for (int i = 1; i < n; i++) { cin >> a >> b; v.push_back(make_pair(a, b)); } for (int i = 1; i < n; i++) { g[v[i].first].push_back(make_pair(i, v[i].second)); g[v[i].second].push_back(make_pair(i, v[i].first)); } visit(1); cout << --maxDay << endl; for (int i = 1; i <= maxDay; i++) { cout << printRes[i].size() << " "; for (int j = 0; j < printRes[i].size(); j++) { cout << printRes[i][j] << " "; } cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; void bfs(vector<vector<uint64_t>>& v, map<tuple<uint64_t, uint64_t>, uint64_t>& road_nr) { uint64_t len = v.size(); vector<bool> visited(len, false); visited[0] = true; visited[1] = true; deque<tuple<uint64_t, uint64_t>> p; map<uint64_t, vector<uint64_t>> res; uint64_t d = 1; for (auto i : v[1]) { p.push_back({i, d}); auto f = road_nr.find({1, i}); res[d].push_back(f->second); d += 1; } while (!p.empty()) { tuple<uint64_t, uint64_t> x = p[0]; p.pop_front(); if (visited[get<0>(x)]) { continue; } else { visited[get<0>(x)] = true; uint64_t d = 1; for (auto i : v[get<0>(x)]) { if (visited[i]) { continue; } if (d == get<1>(x)) { d += 1; } p.push_back({i, d}); uint64_t mi = min(i, get<0>(x)); uint64_t mx = max(i, get<0>(x)); auto f = road_nr.find({mi, mx}); res[d].push_back(f->second); d += 1; } } } cout << res.size() << endl; for (auto i : res) { cout << i.second.size() << " "; for (auto j : i.second) { cout << j << " "; } cout << endl; } } int main() { ios::sync_with_stdio(false); uint64_t n; cin >> n; vector<vector<uint64_t>> v(n + 1); map<tuple<uint64_t, uint64_t>, uint64_t> road_nr; for (uint64_t i = 0; i < n - 1; i++) { uint64_t a; uint64_t b; cin >> a >> b; v[a].push_back(b); v[b].push_back(a); uint64_t x = min(a, b); uint64_t y = max(a, b); road_nr[{x, y}] = i + 1; } bfs(v, road_nr); return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } const int MAXN = 2 * 200000; const int MAXM = MAXN - 1; int n; int deg[MAXN]; int ghead[MAXN], gprv[2 * MAXM], gnxt[2 * MAXM], gto[2 * MAXM]; int ihead[MAXN], iprv[2 * MAXM], inxt[2 * MAXM]; int qhead, qprv[MAXN], qnxt[MAXN], qcopy[MAXN], nqcopy; int mark[MAXN], curmark; int rhead[MAXM], rcnt[MAXM], rnxt[MAXM]; void remdedge(int idx, int* head, int* prv, int* nxt) { if (head[gto[idx ^ 1]] == idx) head[gto[idx ^ 1]] = nxt[idx]; if (prv[idx] != -1) nxt[prv[idx]] = nxt[idx]; if (nxt[idx] != -1) prv[nxt[idx]] = prv[idx]; prv[idx] = nxt[idx] = -1; } void remnode(int idx) { if (qhead == idx) qhead = qnxt[idx]; if (qprv[idx] != -1) qnxt[qprv[idx]] = qnxt[idx]; if (qnxt[idx] != -1) qprv[qnxt[idx]] = qprv[idx]; qprv[idx] = qnxt[idx] = -1; } void repair(int idx) { rnxt[idx] = rhead[curmark]; rhead[curmark] = idx; ++rcnt[curmark]; int a = gto[2 * idx + 1], b = gto[2 * idx + 0]; mark[a] = mark[b] = curmark; remdedge(2 * idx + 0, ghead, gprv, gnxt); remdedge(2 * idx + 1, ghead, gprv, gnxt); remdedge(2 * idx + 0, ihead, iprv, inxt); remdedge(2 * idx + 1, ihead, iprv, inxt); if (--deg[a] == 1) remdedge(ghead[a] ^ 1, ihead, iprv, inxt), remnode(a); if (--deg[b] == 1) remdedge(ghead[b] ^ 1, ihead, iprv, inxt), remnode(b); } void process(int at) { int idx = -1; for (int x = ghead[at]; x != -1; x = gnxt[x]) if (mark[gto[x]] != curmark) { idx = x >> 1; break; } if (idx == -1) { printf("error: curmark=%d, cnt=%d, at=%d\n", curmark, rcnt[curmark], at); exit(0); } repair(idx); for (int x = ihead[gto[2 * idx + 0]]; x != -1;) { int y = x; x = inxt[x]; if (mark[gto[y]] != curmark) process(gto[y]); } for (int x = ihead[gto[2 * idx + 1]]; x != -1;) { int y = x; x = inxt[x]; if (mark[gto[y]] != curmark) process(gto[y]); } } void run() { n = MAXN; scanf("%d", &n); for (int i = (0); i < (n); ++i) ghead[i] = -1, deg[i] = 0; for (int i = (0); i < (n - 1); ++i) { int a = 0, b = i + 1; scanf("%d%d", &a, &b); --a, --b; gnxt[2 * i + 0] = ghead[a]; ghead[a] = 2 * i + 0; gto[2 * i + 0] = b; gprv[2 * i + 0] = -1; if (gnxt[2 * i + 0] != -1) gprv[gnxt[2 * i + 0]] = 2 * i + 0; ++deg[a]; gnxt[2 * i + 1] = ghead[b]; ghead[b] = 2 * i + 1; gto[2 * i + 1] = a; gprv[2 * i + 1] = -1; if (gnxt[2 * i + 1] != -1) gprv[gnxt[2 * i + 1]] = 2 * i + 1; ++deg[b]; } for (int at = (0); at < (n); ++at) { ihead[at] = -1; for (int x = ghead[at]; x != -1; x = gnxt[x]) if (deg[gto[x]] >= 2) { inxt[x] = ihead[at]; ihead[at] = x; iprv[x] = -1; if (inxt[x] != -1) iprv[inxt[x]] = x; } else iprv[x] = inxt[x] = -1; } qhead = -1; for (int at = (0); at < (n); ++at) if (deg[at] >= 2) { qnxt[at] = qhead; qhead = at; qprv[at] = -1; if (qnxt[at] != -1) qprv[qnxt[at]] = at; } else qprv[at] = qnxt[at] = -1; for (int at = (0); at < (n - 1); ++at) rnxt[at] = -1; memset(mark, -1, sizeof(mark)); curmark = -1; while (true) { ++curmark; rhead[curmark] = -1, rcnt[curmark] = 0; nqcopy = 0; for (int at = qhead; at != -1; at = qnxt[at]) qcopy[nqcopy++] = at; if (nqcopy == 0) for (int at = (0); at < (n); ++at) if (deg[at] >= 1) qcopy[nqcopy++] = at; if (nqcopy == 0) break; for (int i = (0); i < (nqcopy); ++i) { int at = qcopy[i]; if (mark[at] != curmark) process(at); } } printf("%d\n", curmark); for (int i = (0); i < (curmark); ++i) { printf("%d", rcnt[i]); fflush(stdout); for (int x = rhead[i]; x != -1; x = rnxt[x]) printf(" %d", x + 1), fflush(stdout); puts(""); fflush(stdout); } } int main() { run(); return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<pair<int, int>> g[n + 1]; for (int i = 1; i <= n - 1; ++i) { int u, v; cin >> u >> v; g[u].emplace_back(v, i); g[v].emplace_back(u, i); } int sum = 0; vector<vector<int>> ans(n + 1); function<void(int, int, int)> dfs = [&](int u, int f, int d) { int t = 0; for (auto i : g[u]) { int v = i.first; int id = i.second; if (v != f) { ++t; if (t == d) { ++t; } sum = max(sum, t); ans[t].push_back(id); dfs(v, u, t); } } }; dfs(1, 0, 0); cout << sum << '\n'; for (int i = 1; i <= sum; ++i) { cout << ans[i].size() << ' '; for (auto j : ans[i]) { cout << j << ' '; } cout << '\n'; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; int mn = 1; vector<vector<pair<int, int>>> G; vector<vector<int>> day; vector<int> used; void DFS(int n, int cl) { int cc = 1; for (int i = 0; i < G[n].size(); i++) { if (cl == cc) { cc++; } if (!used[G[n][i].first]) { day[cc - 1].push_back(G[n][i].second); used[G[n][i].first] = 1; DFS(G[n][i].first, cc); cc++; } } } int main() { int n; cin >> n; G.resize(n); for (int i = 0; i < n - 1; i++) { int t1, t2; cin >> t1 >> t2; G[t1 - 1].push_back(make_pair(t2 - 1, i)); G[t2 - 1].push_back(make_pair(t1 - 1, i)); } for (int i = 0; i < n; i++) { if (G[i].size() > mn) { mn = G[i].size(); } } day.resize(mn); used.assign(n, 0); used[0] = 1; DFS(0, 0); cout << mn << endl; for (int i = 0; i < mn; i++) { cout << day[i].size(); for (int j = 0; j < day[i].size(); j++) { cout << " " << day[i][j] + 1; } cout << endl; } cin >> n; return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1 << " | "; __f(comma + 1, args...); } const int N = int(2e5) + 10; const int M = 2 * N; int last[N], edges, to[M], prv[M], deg[N]; vector<int> ans[N]; bool same(int e1, int e2) { if (e1 == -1 || e2 == -1) return false; return (e1 ^ e2) == 1; } void addEdge(int u, int v) { to[edges] = v; prv[edges] = last[u]; last[u] = edges++; } void dfs(int u, int edge, int ctime = -1) { int curr = 0; for (int e = last[u]; e >= 0; e = prv[e]) { if (same(e, edge)) continue; if (curr == ctime) curr++; int w = to[e]; ans[curr].push_back(e / 2); dfs(w, e, curr); curr++; } } int main() { int n; scanf("%d", &n); int mx = 0; memset(last, -1, sizeof(last)); for (int i = 1; i < n; i++) { int u, v; scanf("%d", &u); scanf("%d", &v); deg[u]++; deg[v]++; mx = max(mx, deg[u]); mx = max(mx, deg[v]); addEdge(u, v); addEdge(v, u); } printf("%d\n", mx); dfs(1, -1); for (int i = 0; i < mx; i++) { printf("%d ", (int)(ans[i].size())); for (auto x : ans[i]) printf("%d ", 1 + x); puts(""); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; long long n; vector<pair<long long, long long> > g[200005]; long long sz; vector<long long> ans[200005]; void dfs(long long s, long long pr, long long tt) { long long cur = 0; for (auto i : g[s]) { if (i.first == pr) continue; cur++; if (cur == tt) cur += 1; sz = max(sz, cur); ans[cur].push_back(i.second); dfs(i.first, s, cur); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; for (long long i = 1; i < n; i++) { long long a, b; cin >> a >> b; g[a].push_back(make_pair(b, i)); g[b].push_back(make_pair(a, i)); } dfs(1, -1, 0); cout << sz << "\n"; for (long long i = 1; i <= sz; i++) { cout << ans[i].size(); for (auto j : ans[i]) cout << " " << j; cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<long long> v[200001]; long long ans = 0; vector<long long> m[200001]; map<pair<long long, long long>, long long> edges; void dfs(long long x, long long p, long long w) { long long d = 1; for (long long i = 0; i < (long long)v[x].size(); i++) { if (v[x][i] == p) continue; if (d == w) d++; ans = max(ans, d); m[d].push_back(edges[{x, v[x][i]}]); dfs(v[x][i], x, d); d++; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n; cin >> n; for (long long i = 0; i < n - 1; i++) { long long x, y; cin >> x >> y; v[x].push_back(y); v[y].push_back(x); edges[{x, y}] = i + 1; edges[{y, x}] = i + 1; } dfs(1, 1, 0); cout << ans << "\n"; for (long long i = 1; i <= ans; i++) { cout << m[i].size() << " "; for (long long j = 0; j < (long long)m[i].size(); j++) cout << m[i][j] << " "; cout << "\n"; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MM = 2e5 + 127; vector<pair<int, int> > edge[MM]; int degree[MM]; vector<int> ans[MM]; int maxT; void dfs(int cur, int par, int when) { int timer = 0; for (auto u : edge[cur]) { if (u.first != par) { if (timer == when) { timer++; } ans[timer].push_back(u.second); dfs(u.first, cur, timer); timer++; } } maxT = max(maxT, timer); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int N; cin >> N; for (int i = 0; i < N - 1; i++) { int p1, p2; cin >> p1 >> p2; p1--; p2--; edge[p1].push_back({p2, i}); edge[p2].push_back({p1, i}); } dfs(0, -1, -1); cout << maxT << '\n'; for (int i = 0; i < maxT; i++) { cout << ans[i].size() << ' '; for (int j : ans[i]) { cout << j + 1 << ' '; } cout << '\n'; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int maxn = 200100, mod = 1e9 + 7, maxa = 1e6 + 100, maxb = 23; const long long inf = 2e18 + 13; long long max(long long x, long long y) { return (x > y ? x : y); } long long min(long long x, long long y) { return (x < y ? x : y); } vector<pair<int, int> > e; vector<int> v[maxn]; vector<int> dans[maxn]; bool visited[maxn]; map<pair<int, int>, int> mp; long long dad[maxn]; long long ans = 0; void dfs(int x) { visited[x] = 1; int tmp = 1; for (int i = 0; i < v[x].size(); i++) { int u = v[x][i]; if (!visited[u]) { if (tmp == dad[x]) { tmp++; } ans = max(ans, tmp); dad[u] = tmp; mp[make_pair(u, x)] = tmp; mp[make_pair(x, u)] = tmp; tmp++; dfs(u); } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long n; cin >> n; for (int i = 0; i < n - 1; i++) { int a, b; cin >> a >> b; a--; b--; v[a].push_back(b); v[b].push_back(a); e.push_back(make_pair(a, b)); } dad[0] = inf; dfs(0); cout << ans << endl; for (int i = 0; i < e.size(); i++) { dans[mp[e[i]]].push_back(i + 1); } for (int i = 1; i <= ans; i++) { cout << dans[i].size() << ' '; for (int j = 0; j < dans[i].size(); j++) { cout << dans[i][j] << ' '; } cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> const double pi = 3.14159265359; const int MOD = 1000000007; const int dr[4] = {-1, 1, 0, 0}; const int dc[4] = {0, 0, -1, 1}; double sinA(double dig) { return sin(dig * pi / 180); } double cosA(double dig) { return cos(dig * pi / 180); } double tanA(double dig) { int we = dig; if (we == dig) { if (we % 90 == 0) { if ((we / 90) % 2 == 1) std::cout << "ERROR\n"; else return 0; } } return tan(dig * pi / 180); } double secA(double dig) { int qw = cos(dig * pi / 180); if (qw == 0) std::cout << "ERROR\n"; else return (1 / qw); } double cosecA(double dig) { int qw = sin(dig * pi / 180); if (qw == 0) std::cout << "ERROR\n"; else return (1 / qw); } double cotA(double dig) { int qw = tan(dig * pi / 180); if (qw == 0) std::cout << "ERROR\n"; else return (1 / qw); } bool isPrime(long long num) { if (num < 0) num *= -1; if (num == 1 || num == 0) return false; else if (num == 2) return true; else { if (num % 2 == 0) { return false; } else for (int x = 3; x <= sqrt(num); x += 2) { if (num % x == 0) { return false; } } return true; } } long long gcd(long long A, long long B) { if (B == 0) return A; return gcd(B, A % B); } long long lcm(long long f, long long l) { return (f / gcd(f, l) * l); } long long fact(long long number) { if (number < 0) number *= -1; if (number == 0) return 1; if (number == 1) return number; else return number * fact(number - 1); } long long fib(long long n) { auto sqrt_5 = std::sqrt(5); if (n == 0) return 0; if (n == 1) return 1; return static_cast<long long>( (std::pow(1 + sqrt_5, n) - std::pow(1 - sqrt_5, n)) / (std::pow(2, n) * sqrt_5)); } long long cdiv(long long a, long long b) { return a / b + ((a ^ b) > 0 && a % b); } long long fdiv(long long a, long long b) { return a / b - ((a ^ b) < 0 && a % b); } int power(int x, int n) { if (n == 0) return 1; int temp = power(x, n / 2); temp *= temp; if (n % 2) temp *= x; return temp; } long long powerMOD(long long x, long long n, long long m) { if (n == 0) return (1); long long temp = powerMOD(x, n / 2, m); temp = ((temp % m) * (temp % m)) % m; if (n % 2) temp = ((temp % m) * (x % m)) % m; return temp; } int ETF(int n) { int ans = 1; for (int x = 2; x * x <= n; x++) { if (n % x == 0) { int count = 0; while (n % x == 0) { count++; n /= x; } ans *= (power(x, count - 1) * (x - 1)); } } if (n != 1) ans *= (n - 1); return ans; } long long SUM(long long number) { long long ans = 0; while (number) { ans += number % 10; number /= 10; } return ans; } std::map<long long, long long> f; long long fibb(long long n) { if (f.count(n)) return f[n]; if (n == 0) return 0; if (n == 1 || n == 2) return 1; if (n % 2 == 0) { long long k = n / 2; long long ret1 = fibb(k - 1), ret2 = fibb(k); return f[n] = ((((2ll * ret1) % MOD + ret2) % MOD) * ret2) % MOD; } else { long long k = (n + 1) / 2; long long ret1 = fibb(k - 1), ret2 = fibb(k); return f[n] = ((ret1 * ret1) % MOD + (ret2 * ret2) % MOD) % MOD; } } void generateNthrow(int N) { int prev = 1; std::cout << prev; for (int i = 1; i <= N; i++) { int curr = (prev * (N - i + 1)) / i; std::cout << ", " << curr; prev = curr; } } int logNM(int num1, int num2) { int counter = 0; while (num2) { num2 /= num1; counter++; } return counter + 1; } const int S = 200007; std::vector<std::pair<int, int>> v[S]; std::vector<int> ans[S]; void dfs(int node, int par, int cnt) { int z = 0; for (auto ch : v[node]) { if (ch.first == par) continue; z++; if (z == cnt) z++; dfs(ch.first, node, z); ans[z].push_back(ch.second); } } void run() { int num; std::cin >> num; for (int x = 1; x < num; x++) { int a, b; std::cin >> a >> b; v[a].push_back({b, x}); v[b].push_back({a, x}); } dfs(1, -1, 0); int counter = 0; for (int x = 0; x < S; x++) { if (ans[x].size()) counter++; } std::cout << counter << "\n"; for (int x = 0; x < S; x++) { if (ans[x].size()) { std::cout << ans[x].size() << " "; for (auto z : ans[x]) std::cout << z << " "; std::cout << "\n"; } } } int main() { run(); }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; struct Edge { int to; int index; int color; size_t inv_pos; Edge(int to = -1, int index = 0, size_t inv_pos = 0) : to(to), index(index), color(-1), inv_pos(inv_pos) {} }; int n; vector<vector<Edge>> g; void bfs(int start) { queue<pair<int, int>> q; q.push(make_pair(start, -1)); while (!q.empty()) { int from = q.front().first; int parent = q.front().second; q.pop(); int exclude_color = -1; if (parent != -1) { for (const Edge& edge : g[from]) if (edge.to == parent) { exclude_color = edge.color; break; } } int color = -1; for (Edge& edge : g[from]) { if (edge.to == parent) continue; if (++color == exclude_color) ++color; edge.color = color; g[edge.to][edge.inv_pos].color = color; q.push(make_pair(edge.to, from)); } } } int main() { scanf("%d", &n); g.resize(n); for (int i = 1; i < n; ++i) { int from, to; scanf("%d%d", &from, &to); --from, --to; int from_pos = g[from].size(), to_pos = g[to].size(); g[from].push_back(Edge(to, i, to_pos)); g[to].push_back(Edge(from, i, from_pos)); } size_t max_deg = 0; for (const vector<Edge>& edges : g) max_deg = max(max_deg, edges.size()); bfs(0); vector<vector<int>> result(max_deg); for (int from = 0; from < n; ++from) { const vector<Edge>& edges = g[from]; for (const Edge& edge : edges) { if (edge.to <= from) continue; result[edge.color].push_back(edge.index); } } printf("%lu\n", max_deg); for (int i = 0; i < max_deg; ++i) { printf("%lu", result[i].size()); for (int index : result[i]) printf(" %d", index); puts(""); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MN = 2e5 + 44; vector<pair<int, int> > graph[MN]; vector<int> ans[MN]; void dfs(int x, int y = -1, int color = -1) { int last = 0; for (auto v : graph[x]) if (v.first != y) { if (last == color) last++; ans[last].push_back(v.second); dfs(v.first, x, last); last++; } } int main() { int n; scanf("%d", &n); for (int i = 1; i < n; ++i) { int a, b; scanf("%d%d", &a, &b); graph[a].push_back(make_pair(b, i)); graph[b].push_back(make_pair(a, i)); } dfs(1); int max; for (max = 0; ans[max].size(); ++max) ; printf("%d\n", max); for (int i = 0; i < max; ++i) { printf("%d", (int)ans[i].size()); for (auto x : ans[i]) printf(" %d", x); printf("\n"); } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<int> gr[200500], v[200500]; map<pair<int, int>, int> mp; int c[200500]; void dfs(int v, int par, int last) { int col = 1; if (last == col) col++; for (int x : gr[v]) { if (x == par) continue; c[mp[make_pair(v, x)]] = col; dfs(x, v, col); col++; if (last == col) col++; } } int main() { ios_base::sync_with_stdio(0); int n, a, b; cin >> n; for (int i = 1; i < n; i++) { cin >> a >> b; a--; b--; gr[a].push_back(b); gr[b].push_back(a); mp[make_pair(a, b)] = i; mp[make_pair(b, a)] = i; } int ans = 0; for (int i = 0; i < n; i++) ans = max(ans, (int)gr[i].size()); dfs(0, -1, -1); for (int i = 1; i < n; i++) v[c[i]].push_back(i); cout << ans << "\n"; for (int i = 1; i <= ans; i++) { cout << v[i].size() << " "; for (int x : v[i]) cout << x << " "; if (i != ans) cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class C { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<ArrayList<edge>> g; static long mod=(long)1e9+7,INF=Long.MAX_VALUE; static boolean set[],col[]; static int par[],tot[],partial[]; static int D[],P[][]; static long dp[][],max=0; static long seg[]; //static pair moves[]= {new pair(-1,0),new pair(1,0), new pair(0,-1), new pair(0,1)}; public static void main(String args[])throws IOException { int N=i(); int A[]=new int[N+1]; int B[]=new int[N+1]; setGraph(N); HashMap<Integer,Integer> mp=new HashMap<>(); int max=0; int sc=0; for(int i=1; i<N; i++) { A[i]=i(); B[i]=i(); g.get(A[i]).add(new edge(B[i],i)); g.get(B[i]).add(new edge(A[i],i)); int f=mp.getOrDefault(A[i], 0)+1; mp.put(A[i], f); max=Math.max(max,f); if(max==f)sc=A[i]; f=mp.getOrDefault(B[i], 0)+1; mp.put(B[i], f); if(max==f)sc=A[i]; max=Math.max(max,f); } ArrayList<Integer> fin[]=new ArrayList[max]; for(int i=0; i<max; i++)fin[i]=new ArrayList<Integer>(); dfs(sc,-1,max,fin); for(ArrayList<Integer> a:fin) { ans.append(a.size()+" "); for(int i:a)ans.append(i+" "); ans.append("\n"); } out.println(max); out.println(ans); out.close(); } static void dfs(int N,int p,int D,ArrayList<Integer> A[]) { int d=0; for(edge c:g.get(N)) { if(c.a==p)continue; if(d==D)d++; A[d].add(c.road); dfs(c.a,N,d,A); d++; } } static long f1(long a,long A[],long bits[],long sum) { long s=A.length; s=mul(s,a); s=(s+(sum%mod))%mod; long p=1L; for(long x:bits) { if((a&p)!=0)s=((s-mul(x,p))+mod)%mod; p<<=1; } return s; } static long f2(long a,long A[],long bits[]) { long s=0; long p=1L; for(long x:bits) { if((a&p)!=0) { s=(s+mul(p,x))%mod; } p<<=1; } return s; } static long f(long x1,long y1,long x2,long y2) { return Math.abs(x1-x2)+Math.abs(y1-y2); } static long f(long x,long max,long s) { long l=-1,r=(x/s)+1; while(r-l>1) { long m=(l+r)/2; if(x-m*s>max)l=m; else r=m; } return l+1; } static int f(long A[],long x) { int l=-1,r=A.length; while(r-l>1) { int m=(l+r)/2; if(A[m]>=x)r=m; else l=m; } return r; } static void build(int v,int tl,int tr,long A[]) { if(tl==tr) { seg[v]=A[tl]; return; } int tm=(tl+tr)/2; build(v*2,tl,tm,A); build(v*2+1,tm+1,tr,A); seg[v]=GCD(seg[v*2],seg[v*2+1]); } static long ask(int v,int tl,int tr,int l,int r) { if(tl==l && tr==r)return seg[v]; int tm=(tl+tr)/2; if(r<=tm) { return ask(v*2,tl,tm,l,r); } else if(l>tm) { return ask(v*2+1,tm+1,tr,l,r); } else { return GCD(ask(v*2,tl,tm,l,tm),ask(v*2+1,tm+1,tr,tm+1,r)); } } static int bin(int x,ArrayList<Integer> A) { int l=0,r=A.size()-1; while(l<=r) { int m=(l+r)/2; int a=A.get(m); if(a==x)return m; if(a<x)l=m+1; else r=m-1; } return 0; } static int left(int x,ArrayList<Integer> A) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; int a=A.get(m); if(a<=x)l=m; else r=m; } return l; } static int right(int x,ArrayList<Integer> A) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; int a=A.get(m); if(a<x)l=m; else r=m; } return r; } static boolean equal(long A[],long B[]) { for(int i=0; i<A.length; i++)if(A[i]!=B[i])return false; return true; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { par[a]+=par[b]; par[b]=a; } } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } static void setGraph(int N) { tot=new int[N+1]; partial=new int[N+1]; D=new int[N+1]; P=new int[N+1][(int)(Math.log(N)+10)]; set=new boolean[N+1]; g=new ArrayList<ArrayList<edge>>(); for(int i=0; i<=N; i++) { g.add(new ArrayList<>()); D[i]=0; //D2[i]=INF; } } static long pow(long a,long b) { //long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static int kadane(int A[]) { int lsum=A[0],gsum=A[0]; for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } } class edge //implements Comparable<edge> { int a,road; edge(int s,int max) { this.a=s; this.road=max; } // public int compareTo(edge x) // { // return this.d-x.d; // } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<int> adj[200004], ans[200004]; int clr[200004], mx = 0; map<int, map<int, int> > mp; void bfs(int src) { int u, v, p, q, r, sz; queue<int> qu; qu.push(src); while (!qu.empty()) { u = qu.front(); qu.pop(); sz = adj[u].size(); p = 0; for (int lp = 0; lp < sz; lp++) { v = adj[u][lp]; if (clr[v] == 0) { p++; if (p == clr[u]) p++; if (p > mx) mx = p; ans[p].push_back(mp[u][v]); qu.push(v); clr[v] = p; } } } } int main() { int n, m, a, b, c, d, i, j; scanf("%d", &n); for (i = 1; i < n; i++) { scanf("%d %d", &a, &b); adj[a].push_back(b); adj[b].push_back(a); mp[a][b] = i; mp[b][a] = i; } clr[1] = -1; bfs(1); printf("%d\n", mx); for (i = 1; i <= mx; i++) { d = ans[i].size(); printf("%d ", d); for (j = 0; j < d; j++) { printf("%d ", ans[i][j]); } printf("\n"); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int nmax = 300010; int n; vector<pair<int, int> > g[nmax]; int u[nmax]; int color[nmax], cnt[nmax]; vector<int> ans[nmax]; void dfs(int v, int p = -1, int come = 0) { int ptr = 1; for (int i = 0; i < g[v].size(); i++) { int num = g[v][i].second, to = g[v][i].first; if (color[num] == 0) { color[num] = ptr++; if (color[num] == come) color[num] = ptr++; } } for (int i = 0; i < g[v].size(); i++) { int num = g[v][i].second, to = g[v][i].first; if (to != p) dfs(to, v, color[num]); } } int main() { ios::sync_with_stdio(0); scanf("%d", &n); int mx = 0; for (int i = 1, a, b; i < n; i++) { scanf("%d %d", &a, &b); g[a].push_back(make_pair(b, i)); g[b].push_back(make_pair(a, i)); cnt[a]++; cnt[b]++; mx = max(mx, max(cnt[a], cnt[b])); } dfs(1); printf("%d\n", mx); for (int i = 1; i < n; i++) ans[color[i]].push_back(i); for (int i = 1; i <= mx; i++) { printf("%d ", ans[i].size()); for (int j = 0; j < ans[i].size(); j++) printf("%d ", ans[i][j]); puts(""); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MaxN = 2e5, MaxM = 4e5; int n, all; int pre[MaxM + 5], last[MaxN + 5], other[MaxM + 5]; bool vis[MaxN + 5]; int ans[MaxM + 5], num[MaxM + 5], used[MaxN + 5]; int seq[MaxM + 5]; vector<int> v[MaxN + 5]; void Build(int x, int y, int d) { pre[++all] = last[x]; last[x] = all; other[all] = y; num[all] = d; } void Init() { all = -1; memset(last, -1, sizeof(last)); for (int i = 1; i <= n - 1; i++) { int u, v; scanf("%d%d", &u, &v); Build(u, v, i); Build(v, u, i); } } void Bfs(int s) { memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; i++) v[i].clear(); int head = 1, tail = 0; seq[++tail] = s; vis[s] = true; while (head <= tail) { int now = seq[head]; int ed = last[now], dr; int tot = 0; while (ed != -1) { dr = other[ed]; if (!vis[dr]) { ++tot; if (used[now] == tot) ++tot; ans[num[ed]] = tot; used[dr] = tot; seq[++tail] = dr; vis[dr] = true; } ed = pre[ed]; } head++; } int MaX = 0; for (int i = 1; i <= n - 1; i++) v[ans[i]].push_back(i), MaX = max(MaX, ans[i]); printf("%d\n", MaX); for (int i = 1; i <= MaX; i++) { printf("%d ", v[i].size()); for (int j = 0; j < v[i].size(); j++) printf("%d ", v[i][j]); printf("\n"); } } int main() { while (~scanf("%d", &n)) { Init(); Bfs(1); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; int cunt[200000 + 342]; bool printed[200000 + 342]; vector<pair<int, int> > adj[200000 + 342]; int pussy[200000 + 342]; vector<int> bc[200000 + 342]; void solve(int cur, int par, int t) { int now = 0; for (int i = 0; i < adj[cur].size(); i++) { int nxt = adj[cur][i].first; if (nxt == par) { continue; } now++; if (now == t) { now++; } bc[now].push_back(adj[cur][i].second); solve(nxt, cur, now); } } int main() { ios::sync_with_stdio(false); int n; cin >> n; int x, y; set<int> nodes; int ans = 0; for (int k = 1; k < n; k++) { cin >> x >> y; cunt[x]++; cunt[y]++; if (cunt[x] > 1) nodes.insert(x); if (cunt[y] > 1) nodes.insert(y); adj[x].push_back(make_pair(y, k)); adj[y].push_back(make_pair(x, k)); ans = max(ans, max(cunt[x], cunt[y])); } if (n == 2) { cout << "1\n1 1"; return 0; } cout << ans << "\n"; int vis = 0; int day = 0; solve(1, -1, 0); for (int i = 1; i <= ans; i++) { cout << bc[i].size() << " "; for (int j = 0; j < bc[i].size(); j++) { cout << bc[i][j] << " "; } cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; int read() { int ans = 0, f = 1; char c = getchar(); while (c > '9' || c < '0') { if (c == '-') f = -1; c = getchar(); } while (c >= '0' && c <= '9') { ans = ans * 10 + c - '0'; c = getchar(); } return ans * f; } const int N = 2e5 + 5; int n, du[N], head[N], tot, ans; vector<int> agg[N]; struct Edge { int v, ne; } e[N * 2]; inline void add(int u, int v); inline void dfs(int u, int fa, int last); int main() { n = read(); for (int i = 1; i < n; ++i) { int u = read(), v = read(); du[u]++, du[v]++; add(u, v); add(v, u); ans = max(ans, max(du[u], du[v])); } printf("%d\n", ans); dfs(1, -1, 0); for (int i = 1; i <= ans; ++i) { printf("%d ", agg[i].size()); for (int j = 0; j < agg[i].size(); ++j) printf("%d ", agg[i][j]); printf("\n"); } return 0; } inline void add(int u, int v) { e[++tot] = (Edge){v, head[u]}; head[u] = tot; } inline void dfs(int u, int fa, int last) { int j = 1; for (int i = head[u]; i; i = e[i].ne) { int v = e[i].v; if (v == fa) continue; if (j == last) j++; agg[j].push_back((i + 1) / 2); dfs(v, u, j); ++j; } return; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 5; const int INF = 0x3f3f3f3f; int n, du[MAXN]; struct Edge { int to, next; } G[MAXN << 1]; int sz, head[MAXN]; void add(int u, int v) { G[sz] = {v, head[u]}; head[u] = sz++; } vector<int> ret[MAXN]; void dfs(int u, int fa, int last) { int now = 1; for (int i = head[u]; ~i; i = G[i].next) { int v = G[i].to; if (v == fa) continue; now += now == last; ret[now].push_back(i / 2); dfs(v, u, now); now++; } } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 1; i <= n; i++) head[i] = -1; for (int i = 1, u, v; i < n; i++) { cin >> u >> v; du[u]++, du[v]++; add(u, v); add(v, u); } int mx = *max_element(du + 1, du + n + 1); cout << mx << '\n'; dfs(1, 0, 0); for (int i = 1; i <= mx; i++) { cout << ret[i].size(); for (int& x : ret[i]) cout << ' ' << x + 1; cout << '\n'; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int N = (int)2e5 + 5; const int INF = (int)1e9; const int mod = (int)1e9 + 7; const long long LLINF = (long long)1e18; int n; vector<pair<int, int> > g[N]; vector<int> roads[N]; void dfs(int v, int p = -1, int id = -1) { int pos = -1; for (auto t : g[v]) { int to = t.first; int num = t.second; if (to == p) continue; ++pos; if (pos == id) ++pos; roads[pos].push_back(num); dfs(to, v, pos); } } int main() { cin >> n; for (int i = 1; i < n; ++i) { int x, y; cin >> x >> y; --x; --y; g[x].push_back({y, i}); g[y].push_back({x, i}); } dfs(0); int cnt = 0; for (int i = 0; i < N; ++i) { if (roads[i].size() > 0) ++cnt; } cout << cnt << '\n'; for (int i = 0; i < cnt; ++i) { cout << roads[i].size() << ' '; for (int r : roads[i]) cout << r << ' '; cout << '\n'; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int max_n = 2e5 + 100; struct edge { int to, num, color, rev, next; } E[max_n << 1]; int head[max_n]; int cnt = 1; void add(int from, int to, int num, int rev, int color = 0) { E[cnt].to = to; E[cnt].next = head[from]; E[cnt].num = num; E[cnt].color = color; E[cnt].rev = rev; head[from] = cnt++; } int n; void dfs(int u, int color) { int tot = 1; for (int i = head[u]; i; i = E[i].next) { if (E[i].color == color) continue; if (tot == color) ++tot; E[i].color = tot; E[E[i].rev].color = tot; dfs(E[i].to, tot); ++tot; } } vector<int> res[max_n]; int main() { ios::sync_with_stdio(0); cin >> n; for (int i = 1, u, v; i < n; ++i) { cin >> u >> v; add(u, v, i, cnt + 1); add(v, u, i, cnt - 1); } dfs(1, -1); int tot = 0; for (int u = 1; u <= n; ++u) { for (int i = head[u]; i; i = E[i].next) { tot = max(tot, E[i].color); if (u < E[i].to) res[E[i].color].push_back(E[i].num); } } cout << tot << endl; for (int i = 1; i <= tot; ++i) { cout << res[i].size() << " "; while (!res[i].empty()) { cout << res[i].back() << " "; res[i].pop_back(); } cout << endl; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; long long mod = 1e9 + 7; long long min(long long a, long long b) { return (a < b) ? a : b; } long long max(long long a, long long b) { return (a > b) ? a : b; } long long fp(long long a, long long b) { if (b == 0) return 1; long long x = fp(a, b / 2); x = (x * x) % mod; if (b & 1) x = (x * a) % mod; return x; } long long n; const long long N = 2e5 + 5; vector<array<long long, 2>> v[N]; long long ans[N] = {0}; void dfs(long long node, long long p, long long mx) { long long x = 1; for (auto i : v[node]) { if (i[0] == p) continue; if (x == mx) x++; ans[i[1]] = x; dfs(i[0], node, x); x += 1; } } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; long long x, y; for (long long i = 1; i < n; i++) { cin >> x >> y; v[x].push_back({y, i}); v[y].push_back({x, i}); } dfs(1, -1, 0); map<long long, vector<long long>> mp; for (long long i = 1; i < n; i++) { mp[ans[i]].push_back(i); } cout << mp.size() << "\n"; for (auto i : mp) { cout << i.second.size() << " "; for (auto j : i.second) cout << j << " "; cout << "\n"; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<long long> vis(200010); vector<long long> adj[200010]; vector<long long> res[200010]; map<pair<long long, long long>, long long> M; long long n, groups = 0; void dfs(long long node, long long col) { vis[node] = 1; for (int i = 0; i < adj[node].size(); i++) { long long child = adj[node][i]; if (!vis[child]) { col = (col % groups) + 1; res[col].push_back(M[{node, child}]); dfs(child, col); } } } int main() { cin >> n; for (int i = 1; i < n; i++) { long long u, v; cin >> u >> v; M[{u, v}] = i; M[{v, u}] = i; adj[u].push_back(v); adj[v].push_back(u); groups = max(groups, (long long)adj[u].size()); groups = max(groups, (long long)adj[v].size()); } dfs(1, 0); cout << groups << endl; for (int i = 1; i <= groups; i++) { cout << res[i].size() << " "; for (auto j : res[i]) { cout << j << " "; } cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 10; vector<pair<int, int> > g[MAXN]; int n; bool read() { if (scanf("%d", &n) < 1) { return false; } for (int i = 0; i < (int)n; ++i) { g[i].clear(); } for (int i = 0; i < (int)n - 1; ++i) { int a, b; scanf("%d%d", &a, &b); --a; --b; g[a].push_back(make_pair(b, i)); g[b].push_back(make_pair(a, i)); } return true; } int dp[MAXN]; vector<int> who[MAXN]; void dfs(int v, int p) { int mx = 0; int sons = 0; for (auto e : g[v]) { int to = e.first; if (to == p) { continue; } dfs(to, v); mx = max(mx, dp[to]); ++sons; } if (sons < mx) { dp[v] = mx; } else if (sons == mx) { dp[v] = mx + 1; } else { dp[v] = sons + 1; } } void make(int v, int p, int t) { int sons = 0; int mx = 0; for (auto e : g[v]) { int to = e.first; if (to == p) { continue; } ++sons; mx = max(mx, dp[to]); } if (t >= sons) { int tt = 0; for (auto e : g[v]) { int to = e.first; if (to == p) { continue; } who[tt].push_back(e.second); make(to, v, tt); ++tt; } } else { int tt = 0; for (auto e : g[v]) { int to = e.first; if (to == p) { continue; } if (tt == t) { ++tt; } who[tt].push_back(e.second); make(to, v, tt); ++tt; } } } void solve() { int r = 0; dfs(r, -1); int mx = 0; int sons = 0; for (auto e : g[r]) { int to = e.first; ++sons; mx = max(mx, dp[to]); } dp[r] = max(sons, mx); for (int i = 0; i < (int)n + 1; ++i) { who[i].clear(); } int t = 0; for (auto e : g[r]) { who[t].push_back(e.second); make(e.first, r, t); ++t; } int ans = 0; for (int i = 0; i < (int)n + 1; ++i) { if (!who[i].empty()) { ans = i + 1; } } printf("%d\n", ans); for (int t = 0; t < (int)ans; ++t) { printf("%d ", ((int)(who[t]).size())); for (int id : who[t]) { printf("%d ", id + 1); } puts(""); } } int main() { while (read()) { solve(); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; long long int node, edge, vis[200010], dist[200010], col[200010], in[200010], out[200010], timer = 1; vector<long long int> gh[200010], ind[200010], ans[200010]; void dfs(long long int current, long long int blocked) { long long int cnt = 0; vis[current] = 1; for (long long int i = 0; i < gh[current].size(); i++) { long long int child = gh[current][i]; long long int idx = ind[current][i]; if (vis[child] == 0) { cnt++; if (cnt == blocked) cnt++; ans[cnt].push_back(idx); dfs(child, cnt); } } } int main() { ios ::sync_with_stdio(false); cin.tie(0); ; vector<long long int> u, v, uu, vv; map<long long int, long long int> mp, mq; vector<pair<long long int, long long int> > vp; set<long long int> sett; map<long long int, long long int>::iterator it; long long int x, y, z, c, d, e, f, g, h, j, k, l, n, m, o, p, q = 0, r, t, ck = 0, sum = 0; string s, s1, s2, tt; cin >> node; edge = node - 1; for (long long int k = 1; k < edge + 1; k++) { cin >> x >> y; gh[x].push_back(y); gh[y].push_back(x); ind[x].push_back(k); ind[y].push_back(k); } long long int root = 1; for (long long int j = 2; j < node + 1; j++) { if (gh[j].size() > gh[root].size()) root = j; } dfs(root, 0); cout << gh[root].size() << "\n"; for (k = 1; k <= gh[root].size(); k++) { cout << ans[k].size() << " "; for (j = 0; j < ans[k].size(); j++) { cout << ans[k][j] << " "; } cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; struct Edge { size_t to, id; Edge(size_t t = 0, size_t i = 0) : to(t), id(i) {} }; vector<Edge> edges[200005]; vector<size_t> ans[200005]; void dfs(size_t v, size_t p = -1, size_t day = -1) { size_t currDay = 0; if (currDay == day) ++currDay; for (size_t i = 0; i < edges[v].size(); i++) { if (edges[v][i].to != p) { ans[currDay].push_back(edges[v][i].id); dfs(edges[v][i].to, v, currDay); ++currDay; if (currDay == day) ++currDay; } } } int main() { ios::sync_with_stdio(0); cin.tie(0); size_t n; cin >> n; for (size_t i = 1; i <= n - 1; i++) { size_t from, to; cin >> from >> to; edges[from].emplace_back(to, i); edges[to].emplace_back(from, i); } size_t ansv = 0; for (size_t i = 1; i <= n; i++) if (edges[i].size() > edges[ansv].size()) ansv = i; cout << edges[ansv].size() << endl; dfs(ansv); for (size_t i = 0; i < edges[ansv].size(); i++) { cout << ans[i].size() << ' '; for (size_t j = 0; j < ans[i].size() - 1; j++) cout << ans[i][j] << ' '; cout << ans[i].back() << endl; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); } template <class T1, class T2> inline void gmax(T1 &a, T2 b) { if (b > a) a = b; } template <class T1, class T2> inline void gmin(T1 &a, T2 b) { if (b < a) a = b; } const int N = 2e5 + 10, M = 0, Z = 1e9 + 7, inf = 0x3f3f3f3f; template <class T1, class T2> inline void gadd(T1 &a, T2 b) { a = (a + b) % Z; } int n; vector<pair<int, int> > a[N]; int ans; vector<int> work[N]; void dfs(int x, int fa, int t) { int now = 0; for (auto it : a[x]) if (it.first != fa) { if (++now == t) ++now; dfs(it.first, x, now); gmax(ans, now); work[now].push_back(it.second); } } int main() { while (~scanf("%d", &n)) { for (int i = 1; i <= n; ++i) a[i].clear(), work[i].clear(); for (int i = 1; i < n; ++i) { int x, y; scanf("%d%d", &x, &y); a[x].push_back({y, i}); a[y].push_back({x, i}); } ans = 0; dfs(1, 0, 0); printf("%d\n", ans); for (auto i = 1; i <= ans; ++i) { printf("%d", work[i].size()); for (auto it : work[i]) printf(" %d", it); puts(""); } } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int M = 200005; const int mod = 1e9 + 7; map<int, int> id[M]; vector<int> adj[M], ans[M]; int n, mans; void dfs(int node, int p, int l) { mans = max(mans, (int)adj[node].size()); int turn = 1; for (auto i : adj[node]) { if (i == p) continue; if (turn == l) ++turn; ans[turn].push_back(id[node][i]); dfs(i, node, turn); ++turn; } return; } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1; i < n; ++i) { int a, b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); id[a][b] = i; id[b][a] = i; } dfs(1, 0, 0); cout << mans << "\n"; for (int i = 1; i <= mans; ++i) { cout << ans[i].size() << " "; for (auto j : ans[i]) cout << j << " "; cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > adjList[200010]; vector<int> day[200010]; void dfs(int u, int p, int sk) { int currd = 0; for (auto x : adjList[u]) { int v = x.first; if (v == p) continue; if (currd == sk) currd += 1; day[currd].push_back(x.second); dfs(v, u, currd); currd += 1; } } int main() { int N; scanf("%d", &N); for (int i = 0; i + 1 < N; i++) { int u, v; scanf("%d %d", &u, &v); adjList[u].push_back(make_pair(v, i + 1)); adjList[v].push_back(make_pair(u, i + 1)); } int maxidx = 1; for (int i = 1; i <= N; i++) if (adjList[i].size() > adjList[maxidx].size()) maxidx = i; dfs(maxidx, -1, -1); cout << adjList[maxidx].size() << endl; for (int i = 0; i < adjList[maxidx].size(); i++) { cout << day[i].size() << " "; for (int j = 0; j < day[i].size(); j++) cout << day[i][j] << " "; cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int mn = 200010; int n, k; vector<int> ans[mn]; vector<pair<int, int> > e[mn]; int clr[mn]; void dfs(int v, int p, int cl) { int q = 1; for (int i = 0; i < e[v].size(); i++) { if (e[v][i].first == p) { continue; } if (q == cl) { q++; } clr[e[v][i].second] = q; dfs(e[v][i].first, v, q); q++; } } int main() { cin >> n; for (int i = 0; i < n - 1; i++) { int x, y; cin >> x >> y; x--; y--; e[x].push_back(make_pair(y, i)); e[y].push_back(make_pair(x, i)); } k = 0; for (int i = 0; i < n; i++) { if (e[i].size() > e[k].size()) { k = i; } } cout << e[k].size() << "\n"; dfs(k, k, 0); for (int i = 0; i < n - 1; i++) { ans[clr[i]].push_back(i + 1); } for (int i = 1; i <= e[k].size(); i++) { cout << ans[i].size() << " "; for (int j = 0; j < ans[i].size(); j++) { cout << ans[i][j] << " "; } cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.util.*; import java.io.*; public class TaskC { private FastScanner in; private PrintWriter out; private class Edge { int from; int to; int index; public Edge(int from, int to, int index) { this.from = from; this.to = to; this.index = index; } } List<Edge>[] to; List<Edge>[] days; boolean[] used; public void solve() throws IOException { int n = in.nextInt(); to = new List[n]; days = new List[n]; used = new boolean[n]; for (int i = 0; i < n; i++) { to[i] = new ArrayList<>(); days[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { Edge cur = new Edge(in.nextInt() - 1, in.nextInt() - 1, i + 1); Edge revCur = new Edge(cur.to, cur.from, i + 1); to[cur.from].add(cur); to[revCur.from].add(revCur); } for (int i = 0; i < n; i++) { if (!used[i]) { dfs(i, 0, -1); } } int lastNonEmpty = -1; for (int i = 0; i < n; i++) { if (!days[i].isEmpty()) { lastNonEmpty = i; } } out.println(lastNonEmpty + 1); for (int i = 0; i < lastNonEmpty + 1; i++) { out.print(days[i].size() + " "); for (Edge cur : days[i]) { out.print(cur.index + " "); } out.println(); } } private void dfs(int u, int len, int badDay) { used[u] = true; int curDay = badDay == 0 ? 1 : 0; for (int i = 0; i < to[u].size(); i++) { if (used[to[u].get(i).to]) { continue; } days[curDay].add(to[u].get(i)); dfs(to[u].get(i).to, len + 1, curDay); curDay++; if (curDay == badDay) { curDay++; } } } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new TaskC().run(); } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; public class C { static ArrayList<Integer>[][] way; static ArrayList<ArrayList<Integer>> answer; static PrintWriter out; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = Integer.valueOf(in.readLine()); String str[]; way = new ArrayList[n][2]; answer = new ArrayList<>(); for (int i = 0; i < n; i++) { way[i][0] = new ArrayList<>(); way[i][1] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { str = in.readLine().split(" "); int ind1 = Integer.valueOf(str[0]) - 1; int ind2 = Integer.valueOf(str[1]) - 1; way[ind1][0].add(ind2); way[ind2][0].add(ind1); way[ind1][1].add(i + 1); way[ind2][1].add(i + 1); } rec(0, -1, 0); out.println(answer.size()); for (int i = 0; i < answer.size(); i++) { out.print(answer.get(i).size() + " "); for (int j = 0; j < answer.get(i).size(); j++) { out.print(answer.get(i).get(j) + " "); } out.println(); } out.flush(); } static void rec(int now, int last, int day) { int nday = 0; for (int i = 0; i < way[now][0].size(); i++) { if (way[now][0].get(i) != last) { nday++; if (nday == day) nday++; rec(way[now][0].get(i), now, nday); } } if (day > 0) { while (answer.size() < day) { answer.add(new ArrayList<>()); } int ind = 0; while (way[now][0].get(ind) != last) ind++; answer.get(day - 1).add(way[now][1].get(ind)); } } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200000; std::vector<int> ans[N]; std::vector<std::pair<int, int> > edge[N]; int maxi = 0; void dfs(int u, int par, int day) { int cnt = 0; for (int i = 0; i < edge[u].size(); i++) { std::pair<int, int> v = edge[u][i]; if (v.first == par) continue; if (day == cnt) cnt++; ans[cnt].push_back(v.second); dfs(v.first, u, cnt++); } maxi = (maxi < cnt ? cnt : maxi); } int main() { int n; scanf("%d", &n); int u, v; for (int i = 1; i < n; i++) { scanf("%d %d", &u, &v); u--, v--; edge[u].push_back(std::make_pair(v, i)); edge[v].push_back(std::make_pair(u, i)); } dfs(0, 0, -1); printf("%d\n", maxi); for (int i = 0; i < maxi; i++) { printf("%d", ans[i].size()); for (int j = 0; j < ans[i].size(); j++) { printf(" %d", ans[i][j]); } printf("\n"); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; using LL = long long; using VI = vector<int>; using VC = vector<char>; using VS = vector<string>; using VL = vector<long long>; using VVI = vector<VI>; using VVL = vector<VL>; using MII = map<int, int>; using MIVI = map<int, VI>; using MSS = map<string, string>; using MLL = map<LL, LL>; int READ_INT() { int temp; cin >> temp; return temp; } LL READ_LONG() { LL temp; cin >> temp; return temp; } void mcs(VI &series, int &max_sum) { int s = 0; for (auto x : series) { s += x; max_sum = max(max_sum, s); if (s < 0) s = 0; } } template <typename T> T MAX(T t) { return t; } template <typename T, typename... Args> T MAX(T t, Args... args) { return max(t, MAX(args...)); } const int MOD = int(1e9) + 7; const int INF = 1e9 + 5; const double PI = acos(-1.0); const double EPS = 1e-9; int n; map<int, VI> adj_list; VI visited; map<pair<int, int>, int> edge_index; map<pair<int, int>, int> edge_order; void dfs(int node) { visited[node] = 1; VI allowed; set<int> not_allowed; for (auto c : adj_list[node]) { int u = min(c, node), v = max(c, node); not_allowed.insert(edge_order[{u, v}]); } for (int i = 1; i <= adj_list[node].size(); ++i) { if (not_allowed.find(i) == not_allowed.end()) allowed.push_back(i); } int j = 0; for (auto c : adj_list[node]) { int u = min(c, node), v = max(c, node); if (edge_order[{u, v}] == 0) { edge_order[{u, v}] = allowed[j]; j++; } } for (auto c : adj_list[node]) { if (!visited[c]) dfs(c); } } int main() { ios::sync_with_stdio(false); cin >> n; for (int i = 0; i < n - 1; ++i) { int u, v; cin >> u >> v; adj_list[u].push_back(v); adj_list[v].push_back(u); edge_index[{min(u, v), max(u, v)}] = i + 1; edge_order[{min(u, v), max(u, v)}] = 0; } visited.assign(n + 1, 0); dfs(1); map<int, VI> ans; for (auto p : edge_order) ans[p.second].push_back(edge_index[{p.first.first, p.first.second}]); cout << ans.size() << "\n"; for (int i = 1; i <= ans.size(); ++i) { cout << ans[i].size() << " "; { for (auto x___ : ans[i]) cout << x___ << " "; cout << "\n"; }; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int N = 200123; vector<pair<int, int> > nbs[N]; int deg[N]; int act[N]; int taken[N]; int par[N]; int paredge[N]; int asparent[N]; int h[N]; int n, a, b; void dfs(int v, int p = -1, int e = -1, int ch = 0) { par[v] = p; paredge[v] = e; h[v] = ch; for (pair<int, int> w : nbs[v]) { if (w.first != p) dfs(w.first, v, w.second, ch + 1); } } int main() { ios_base::sync_with_stdio(0); cin >> n; for (int i = 0; i < (int)n - 1; i++) { cin >> a >> b; --a; --b; nbs[a].push_back({b, i}); nbs[b].push_back({a, i}); act[i] = 1; } dfs(0); priority_queue<pair<int, int> > pq; int maxdeg = 0; for (int i = 0; i < (int)n; i++) { deg[i] = nbs[i].size(); if (deg[i]) pq.push({deg[i], i}); maxdeg = max(maxdeg, deg[i]); } cout << maxdeg << endl; int curdeg; int nday = 0; while (pq.size()) { nday++; vector<int> day; vector<pair<int, int> > todo; curdeg = pq.top().first; while (pq.size() && curdeg == pq.top().first) { pair<int, int> c = pq.top(); pq.pop(); int d = c.first, v = c.second; if (deg[v] != d) continue; todo.push_back({h[v], v}); } sort(todo.begin(), todo.end()); for (int i = 0; i < (int)todo.size(); i++) { int v = todo[i].second; if (taken[v] == nday) continue; pair<int, int> w = {-1, -1}; taken[v] = nday; if (par[v] != -1 && taken[par[v]] < nday && act[paredge[v]]) { taken[par[v]] = nday; w = {par[v], paredge[v]}; } else for (int i = 0; i < (int)nbs[v].size(); i++) { if (!act[nbs[v][i].second]) { swap(nbs[v][i], nbs[v].back()); nbs[v].pop_back(); i--; } else if (taken[nbs[v][i].first] < nday) { taken[nbs[v][i].first] = nday; w = nbs[v][i]; break; } } assert(w.first >= 0); deg[v]--; deg[w.first]--; if (deg[v]) pq.push({deg[v], v}); if (deg[w.first]) pq.push({deg[w.first], w.first}); day.push_back(w.second); assert(act[w.second]); act[w.second] = 0; } cout << day.size() << " "; for (int e : day) { cout << e + 1 << " "; } cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int N = (int)2e5 + 1; struct v { int i, c; }; int n, a, b; map<int, map<int, int>> tr; int que[N], l, r; stack<int> st; int bV[N] = {0}; v V[N] = {0}; bool d[N] = {0}; deque<deque<int>> de; void rec(int i = V[0].i, int c = 1) { for (map<int, int>::iterator it = tr[i].begin(); it != tr[i].end(); ++it) { if (d[it->second] != 0) continue; d[it->second] = c; de[c - 1].push_back(it->second); c = c % V[0].c + 1; rec(it->first, c); } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for (int i = 1; i < n; ++i) { cin >> a >> b; --a; --b; tr[a][b] = i; tr[b][a] = i; V[a].i = a; V[b].i = b; ++V[a].c; ++V[b].c; } sort(V, V + n, [](v a, v b) { return a.c > b.c; }); de.resize(V[0].c); rec(); cout << V[0].c << endl; for (int i = 0; i < de.size(); ++i) { cout << de[i].size() << ' '; for (int j = 0; j < de[i].size(); ++j) cout << de[i][j] << ' '; cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<int> ans[200001]; vector<pair<int, int> > v[200001]; int vis[200001]; void dfs(int s, int r) { int d = 0; vis[s] = 1; for (auto i : v[s]) { if (vis[i.first] == 0) { int a = i.first; int b = i.second; d++; if (r == d) { d++; } ans[d].push_back(b); dfs(a, d); } } } int main(int argc, char const *argv[]) { int n; cin >> n; for (int i = 0; i < n - 1; ++i) { int a, b; cin >> a >> b; v[a].push_back(make_pair(b, i + 1)); v[b].push_back(make_pair(a, i + 1)); } int degree = -5; for (int i = 1; i <= n; ++i) { int k = v[i].size(); if (degree < k) { degree = v[i].size(); } } cout << degree << "\n"; dfs(1, -1); for (int i = 1; i <= degree; ++i) { int p = ans[i].size(); cout << p << " "; for (int j = 0; j < p; ++j) { cout << ans[i][j] << " "; } cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; inline long long in() { int32_t x; scanf("%d", &x); return x; } inline string getStr() { char ch[1000000]; scanf("%s", ch); return ch; } inline string getStr2() { char ch[5]; scanf("%s", ch); return ch; }; template <class P, class Q> inline P smin(P &a, Q b) { if (b < a) a = b; return a; } template <class P, class Q> inline P smax(P &a, Q b) { if (a < b) a = b; return a; } const long long MAX_N = 3e5 + 10; const long long MOD = 1e9 + 7; inline long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } inline char getCh() { char ch; scanf(" %c", &ch); return ch; } vector<pair<long long, long long> > g[MAX_N]; long long maxi = 0; vector<long long> res[MAX_N]; inline void dfs(long long v, long long used = -1, long long pr = -1) { long long cur = 1; smax(maxi, g[v].size()); for (auto u : g[v]) { if (u.first == pr) continue; if (cur == used) cur++; res[cur].push_back(u.second + 1); dfs(u.first, cur, v); cur++; } } int32_t main() { long long n = in(); for (long long i = 0; i < n - 1; i++) { long long v = in(), u = in(); g[v].push_back({u, i}), g[u].push_back({v, i}); } dfs(1); cout << maxi << "\n"; for (long long i = 1; i <= maxi; i++) { cout << res[i].size() << " "; for (long long j = 0; j < res[i].size(); j++) { cout << res[i][j] << " "; } cout << "\n"; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 5; int n, result = 0, lab[MAXN]; vector<pair<int, int> > adj_list[MAXN]; vector<vector<int> > ans; void dfs(int u, int last, int skip) { int curr; if (skip != 1) curr = 1; else curr = 2; for (int i = 0; i < adj_list[u].size(); i++) { int v = adj_list[u][i].first; int num = adj_list[u][i].second; if (v != last) { if (curr == skip) curr++; ans[curr].push_back(num); lab[num] = curr; curr++; if (curr == skip) curr++; } } for (int i = 0; i < adj_list[u].size(); i++) { int v = adj_list[u][i].first; int num = adj_list[u][i].second; if (v != last) { if (adj_list[v].size() > 1) { dfs(v, u, lab[num]); } } } } int main() { ios_base::sync_with_stdio(0); cin >> n; for (int i = 1; i < n; i++) { int x, y; cin >> x >> y; adj_list[x].push_back(make_pair(y, i)); adj_list[y].push_back(make_pair(x, i)); result = max(result, (int)adj_list[x].size()); result = max(result, (int)adj_list[y].size()); } ans.assign(result + 2, vector<int>()); dfs(1, 1, 0); cout << result << endl; for (int i = 1; i <= result; i++) { cout << ans[i].size() << " "; for (int j = 0; j < ans[i].size(); j++) { cout << ans[i][j] << " "; } cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { ArrayList<Integer>[] g; ArrayList<Integer>[] id; ArrayList<Integer>[] at; boolean[] was; int[] par; int[] parColor; public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); g = new ArrayList[n]; id = new ArrayList[n]; for (int i = 0; i < n; i++) { g[i] = new ArrayList<>(); id[i] = new ArrayList<>(); } par = new int[n]; parColor = new int[n]; was = new boolean[n]; for (int i = 0; i < n - 1; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; g[a].add(b); g[b].add(a); id[a].add(i); id[b].add(i); } int maxV = 0; for (int i = 0; i < n; i++) if (g[i].size() > g[maxV].size()) maxV = i; int v = maxV; int res = g[v].size(); Arrays.fill(par, -1); Arrays.fill(parColor, -1); at = new ArrayList[res]; for (int d = 0; d < res; d++) at[d] = new ArrayList<>(); ArrayDeque<Integer> queue = new ArrayDeque<>(); queue.addLast(v); was[v] = true; while (!queue.isEmpty()) { int from = queue.pollFirst(); //System.err.println(from); int color = 0; for (int i = 0; i < g[from].size(); i++) { int to = g[from].get(i); int curId = id[from].get(i); if (to == par[from]) continue; if (color == parColor[from]) color++; was[to] = true; par[to] = from; parColor[to] = color; at[color].add(curId); queue.addLast(to); color++; } } out.println(at.length); for (ArrayList<Integer> atDay : at) { out.print(atDay.size() + " "); for (int elem : atDay) out.print((elem + 1) + " "); out.println(); } } public static void main(String[] args)throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); new Main().solve(0, in, out); in.close(); out.close(); } } class FastScanner { private StringTokenizer tokenizer; private BufferedReader reader; public FastScanner(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) return null; tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } tokenizer = null; return line; } public void close() { try { reader.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<pair<int, int>> e[200005]; vector<int> ans[200005]; int n, all; void dfs(int fa, int u, int k) { int day = 0; for (auto i : e[u]) { int v = i.first, id = i.second; if (fa != v) { if (++day == k) { day++; } all = max(all, day); ans[day].push_back(id); dfs(u, v, day); } } } void get() { dfs(-1, 1, -1); cout << all << endl; for (int i = 1; i <= all; i++) { cout << ans[i].size() << " "; for (auto day : ans[i]) cout << day << " "; cout << endl; } } int main() { scanf("%d", &n); int u, v; for (int i = 1; i < n; i++) { scanf("%d %d", &u, &v); e[u].push_back(make_pair(v, i)); e[v].push_back(make_pair(u, i)); } get(); return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import javafx.geometry.Pos; import javafx.util.Pair; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.security.cert.PolicyNode; import java.util.*; public class Solution { BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } final int inf = Integer.MAX_VALUE / 2; final double eps = 0.0000000001; int rd() throws IOException { return Integer.parseInt(nextToken()); } class Edge { int b, e, num, day; Edge(int b, int e, int num) { this.b = b; this.e = e; this.num = num; } } List<Edge>[] r; List<Integer>[] ans; int maxDays = 0; void dfs(int q, int p, int day) { int d = 1; for (Edge e : r[q]) if (e.e != p) { if (d == day) d++; ans[d].add(e.num); maxDays = Math.max(maxDays, d); dfs(e.e, e.b, d); d++; } } void solve() throws IOException { int n = rd(); r = new ArrayList[n]; ans = new ArrayList[n]; for (int i = 0; i < n; i++) { r[i] = new ArrayList<>(); ans[i] = new ArrayList<>(); } for (int i = 0; i < n - 1; i++) { int u = rd() - 1; int v = rd() - 1; r[u].add(new Edge(u, v, i + 1)); r[v].add(new Edge(v, u, i + 1)); } dfs(0, -1, 0); out.println(maxDays); for (int i = 1; i <= maxDays; i++) { out.print(ans[i].size() + " "); for (int j : ans[i]) out.print(j + " "); out.println(); } } void run() throws IOException { try { // in = new BufferedReader(new FileReader("notation.in")); // out = new PrintWriter("notation.out"); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Locale.setDefault(Locale.UK); solve(); } catch (Exception e) { e.printStackTrace();//To change body of catch statement use File | Settings | File Templates. } finally { out.close(); } } public static void main(String Args[]) throws IOException { new Solution().run(); } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; long long gcd1(long long a, long long b) { if (a == 0) return b; return gcd1(b % a, a); } long long modx(long long base, long long ex) { long long ans = 1LL, val = base; while (ex > 0LL) { if (ex & 1LL) ans = (ans * val) % 1000000009LL; val = (val * val) % 1000000009LL; ex = ex >> 1LL; } return ans; } int n, maxd; vector<pair<int, int> > adj[200005]; vector<int> days[200005]; bool visit[200005]; void dfs(int start, int d) { visit[start] = true; int nd = 1; for (int i = 0; i < adj[start].size(); i++) { int pt = adj[start][i].first; if (visit[pt]) continue; if (nd == d) nd++; maxd = max(nd, maxd); days[nd].push_back(adj[start][i].second); dfs(pt, nd); nd++; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; int x, y; for (int i = 1; i < n; i++) { cin >> x >> y; adj[x].push_back(make_pair(y, i)); adj[y].push_back(make_pair(x, i)); } dfs(1, 0); cout << maxd << endl; for (int i = 1; i <= maxd; i++) { cout << days[i].size() << " "; for (int j = 0; j < days[i].size(); j++) cout << days[i][j] << " "; cout << endl; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int MAXN = 200000 + 42; struct { int u, v; int to(int from) const { return u + v - from; } } edges[MAXN]; list<int> graph[MAXN]; list<int> roads[MAXN]; bool used[MAXN] = {}; int main() { int n; scanf("%d", &n); for (int i = 1; i < n; ++i) { scanf("%d%d", &edges[i].u, &edges[i].v); graph[edges[i].u].push_back(i); graph[edges[i].v].push_back(i); } int start = rand() % n + 1; queue<pair<int, int> > q; used[start] = true; q.emplace(start, 0); while (!q.empty()) { int vertex = q.front().first; int busy = q.front().second; q.pop(); int day = 1; for (int edge : graph[vertex]) { int to = edges[edge].to(vertex); if (used[to]) continue; if (busy == day) ++day; roads[day].push_back(edge); used[to] = true; q.emplace(to, day); ++day; } } int k; for (k = 1; !roads[k].empty(); ++k) ; --k; printf("%u\n", k); for (int i = 1; i <= k; ++i) { printf("%u", roads[i].size()); for (int road : roads[i]) { printf(" %d", road); } putchar('\n'); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created by roman on 21.03.2016. */ public class Task3 { public BufferedReader bufferedReader; public StringTokenizer stringTokenizer; public PrintWriter printWriter; public void openForIO() throws IOException { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); printWriter = new PrintWriter(System.out); } public String nextElement() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { String line = bufferedReader.readLine(); if (line == null) return null; stringTokenizer = new StringTokenizer(line); } return stringTokenizer.nextToken(); } public int nextInteger() throws NumberFormatException, IOException { return Integer.parseInt(nextElement()); } public void closeIO() { printWriter.flush(); printWriter.close(); } public static void main(String[] args) throws IOException { // Scanner sc = new Scanner(System.in); Task3 sc = new Task3(); sc.openForIO(); int n = sc.nextInteger(); ArrayList<int[]>[] matrix = new ArrayList[n]; for (int i = 0; i<n; i++) { matrix[i] = new ArrayList<>(); } for (int i = 0; i<n-1; i++) { int c1 = sc.nextInteger()-1, c2 = sc.nextInteger()-1; matrix[c1].add(new int[]{c2, i+1}); matrix[c2].add(new int[]{c1, i+1}); } int begin = -1; for (int i = 0; i<n; i++) { if (matrix[i].size()==1) { // it's leaf, at least one exists begin = i; break; } } Map<Integer, ArrayList<Integer>> result = new HashMap<>(); recursiveWalk(matrix, result, begin, -1, 0); // StringBuilder sb = new StringBuilder(); sc.printWriter.println(result.size()); for (int i = 0; i<result.size(); i++) { ArrayList<Integer> curr = result.get(i + 1); sc.printWriter.print(curr.size()); sc.printWriter.print(' '); // sb.append(curr.size()); // sb.append(' '); for (int j = 0; j<curr.size(); j++) { sc.printWriter.print(curr.get(j)); sc.printWriter.print(' '); // sb.append(curr.get(j)); // sb.append(' '); } sc.printWriter.println(); // sb.setLength(0); } sc.closeIO(); } public static void recursiveWalk(ArrayList<int[]>[] matrix, Map<Integer, ArrayList<Integer>> result, int pos, int prev, int prevDay) { ArrayList<int[]> curr = matrix[pos]; int currDay = prevDay==1?prevDay+1:1; for (int i = 0; i<curr.size(); i++) { if (curr.get(i)[0] == prev) continue; ArrayList<Integer> currDayRoads; if (!result.containsKey(currDay)) { result.put(currDay, new ArrayList<Integer>()); } currDayRoads = result.get(currDay); currDayRoads.add(curr.get(i)[1]); recursiveWalk(matrix, result, curr.get(i)[0], pos, currDay); if (++currDay == prevDay) { // if we get to prev day we skip it, beause in this day current team is busy ++currDay; } } } }
JAVA
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; int n; vector<pair<int, int> > g[200000]; int col[200000]; vector<int> plan[200000]; void dfs(int v, int p, int bad) { int cur = 0; for (pair<int, int> to : g[v]) if (to.first != p) { if (cur == bad) ++cur; col[to.second] = cur; dfs(to.first, v, cur); ++cur; } } int main() { scanf("%d", &n); for (int i = 0; i < (int)(n - 1); ++i) { int from, to; scanf("%d%d", &from, &to), --from, --to; g[from].push_back(make_pair(to, i)); g[to].push_back(make_pair(from, i)); } dfs(0, -1, -1); for (int i = 0; i < (int)(n - 1); ++i) plan[col[i]].push_back(i); int mx = 0; for (int i = 0; i < (int)(n - 1); ++i) mx = max(mx, col[i]); printf("%d\n", mx + 1); for (int i = 0; i < (int)(mx + 1); ++i) { printf("%d", (int)plan[i].size()); for (int x : plan[i]) { printf(" %d", x + 1); } printf("\n"); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; typedef struct { int sum, suf, pre, max; } Node; int toint(const string &s) { stringstream ss; ss << s; int x; ss >> x; return x; } const int MAXN = 2e5 + 100; const int UP = 31; const long long int highest = 1e18; const double pi = acos(-1); const double Phi = 1.618033988749894; const int logn = 20; const double root5 = 2.236067977; const int mod = 1e9 + 7; const int ini = -1e9; const int N = 2e5 + 200; std::vector<int> gr[N]; std::vector<int> id[N]; const int rt = 0; std::vector<int> res[N]; int wrst = 0; int n; void dfs(int u, int par = -1, int badt = -1) { wrst = max(wrst, (int)gr[u].size()); int t = 0; if (t == badt) { ++t; } for (int i = 0; i < gr[u].size(); ++i) { int v = gr[u][i]; if (v == par) { continue; } int curday = t; res[t].push_back(id[u][i]); ++t; if (t == badt) { ++t; } dfs(v, u, curday); } } int main() { scanf("%d", &n); for (int i = 0; i < n - 1; ++i) { int u, v; scanf("%d%d", &u, &v); --u, --v; gr[u].push_back(v); gr[v].push_back(u); id[u].push_back(i); id[v].push_back(i); } dfs(rt); cout << wrst << "\n"; for (int i = 0; i < wrst; ++i) { cout << (res[i].size()) << " "; for (int c : res[i]) { cout << (c + 1) << " "; } cout << "\n"; } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; void bfs(vector<vector<uint64_t>>& g, map<tuple<uint64_t, uint64_t>, uint64_t>& i2r) { vector<bool> visit(g.size()); deque<tuple<uint64_t, uint64_t, uint64_t>> ev; unordered_map<int64_t, vector<uint64_t>> roads_by_day; visit[1] = true; int day = 0; for (auto e : g[1]) { day += 1; ev.push_back({1, e, day}); roads_by_day[day].push_back(i2r[{1, e}]); } while (!ev.empty()) { auto crt = ev.front(); uint64_t nv = get<1>(crt); ev.pop_front(); if (!visit[nv]) { visit[nv] = true; int day = 0; int noDay = get<2>(crt); for (auto e : g[nv]) { if (!visit[e]) { day += 1; if (day == noDay) { day += 1; } ev.push_back({nv, e, day}); roads_by_day[day].push_back(i2r[{min(nv, e), max(nv, e)}]); } } } } cout << roads_by_day.size() << endl; for (auto kv : roads_by_day) { cout << kv.second.size() << " "; for (auto ed : kv.second) { cout << ed << " "; } cout << endl; } } int main() { ios::sync_with_stdio(false); uint64_t n; cin >> n; vector<vector<uint64_t>> v(n + 1); map<tuple<uint64_t, uint64_t>, uint64_t> i2r; for (uint64_t i = 0; i < n - 1; i++) { uint64_t x; cin >> x; uint64_t y; cin >> y; v[x].push_back(y); v[y].push_back(x); i2r[{min(x, y), max(x, y)}] = i + 1; } bfs(v, i2r); return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; vector<int> v[222222]; map<pair<int, int>, int> m; bool vis[222222]; const long long INF = 1000000000; vector<int> ans[222222]; int ans1 = 1; void dfs(int k, int last) { int num = 0; for (int i = 0; i < v[k].size(); ++i) if (!vis[v[k][i]]) { if (num == last) num++; ans1 = max(ans1, num + 1); int pos = m[make_pair(k, v[k][i])]; ans[num].push_back(pos); vis[v[k][i]] = true; dfs(v[k][i], num); num++; } } int main() { int n; scanf("%d", &n); for (int i = 1; i <= n - 1; ++i) { int from, to; scanf("%d %d", &from, &to); from--; to--; m[make_pair(from, to)] = i; m[make_pair(to, from)] = i; v[from].push_back(to); v[to].push_back(from); } vis[0] = true; for (int i = 1; i < n; ++i) vis[i] = false; dfs(0, INF); printf("%d\n", ans1); for (int i = 0; i < ans1; ++i) { printf("%d ", ans[i].size()); for (int j = 0; j < ans[i].size(); ++j) printf("%d ", ans[i][j]); printf("\n"); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; int N, maxd; vector<pair<int, int> > adj[200005]; vector<int> days[200005]; bool seen[200005]; void dostuff(int n, int d) { seen[n] = true; int i = 1; for (auto a : adj[n]) { if (!seen[a.first]) { if (i == d) { i++; } days[i].push_back(a.second); dostuff(a.first, i); i++; } } } int main() { scanf("%d", &N); for (int n = 1; n < N; n++) { int A, B; scanf("%d %d", &A, &B); adj[A].push_back({B, n}); adj[B].push_back({A, n}); } for (int n = 1; n <= N; n++) { maxd = max(maxd, (int)adj[n].size()); } printf("%d\n", maxd); dostuff(1, 0); for (int d = 1; d <= maxd; d++) { printf("%d ", days[d].size()); for (auto a : days[d]) { printf("%d ", a); } printf("\n"); } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int mxn = (2e5) + 5; vector<pair<int, int> > tr[mxn]; vector<int> ans[mxn]; int mx; void dfs(int v, int p, int in) { mx = max(mx, in + 1); int c = -1; for (int i = 0; i < tr[v].size(); ++i) { int u = tr[v][i].first; int x = tr[v][i].second; if (u == p) continue; ++c; if (c == in) ++c; ans[c].push_back(x); dfs(u, v, c); } } int main() { int n; scanf("%d", &n); for (int i = 0; i < n - 1; ++i) { int x, y; scanf("%d%d", &x, &y); tr[x].push_back({y, i + 1}); tr[y].push_back({x, i + 1}); } dfs(1, 1, -1); printf("%d\n", mx); for (int i = 0; !ans[i].empty(); ++i) { printf("%d", ans[i].size()); for (int j = 0; j < ans[i].size(); ++j) printf(" %d", ans[i][j]); puts(""); } return 0; }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; const int md = 1e9 + 7; const int INF = 1e9 + 7; const double EPS = 1e-10; int n; const int MAXN = 200010; map<pair<int, int>, int> edge; vector<int> g[MAXN]; bool vis[MAXN]; int cant[MAXN]; vector<int> first_not_used(MAXN, 1); vector<int> day[MAXN]; int ans; void dfs(int v) { vis[v] = true; for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; if (!vis[to]) { if (first_not_used[v] == cant[v]) first_not_used[v]++; day[first_not_used[v]].push_back(edge[make_pair(v, to)]); cant[to] = first_not_used[v]; ans = max(ans, first_not_used[v]); first_not_used[v]++; if (first_not_used[v] == cant[v]) first_not_used[v]++; dfs(to); } } } int main() { cin >> n; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); edge[make_pair(u, v)] = i; edge[make_pair(v, u)] = i; } dfs(1); cout << ans << "\n"; for (int i = 1; i <= ans; i++) { cout << day[i].size() << " "; for (int j = 0; j < day[i].size(); j++) cout << day[i][j] << " "; cout << "\n"; } }
CPP
638_C. Road Improvement
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads. In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day. Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. Input The first line of the input contains a positive integer n (2 ≀ n ≀ 200 000) β€” the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≀ ui, vi ≀ n, ui β‰  vi). Output First print number k β€” the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di β€” the number of roads that should be repaired on the i-th day, and then di space-separated integers β€” the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them. Examples Input 4 1 2 3 4 3 2 Output 2 2 2 1 1 3 Input 6 3 4 5 4 3 2 1 3 4 6 Output 3 1 1 2 2 3 2 4 5 Note In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 β€” on the second day.
2
9
#include <bits/stdc++.h> using namespace std; class graphal { public: int n, mx = 0; vector<pair<int, int> > *ed; vector<int> *ans; graphal(int n) { this->n = n; ed = new vector<pair<int, int> >[n]; ans = new vector<int>[n + 1](); } ~graphal() { delete[] ed; delete[] ans; } void add(int a, int b, int ix) { ed[a].push_back(pair<int, int>(b, ix)); ed[b].push_back(pair<int, int>(a, ix)); } void dfs(int ix, int du, int pix) { int dtu = 0; mx = max(mx, (int)ed[ix].size()); for (auto i : ed[ix]) if (i.first != pix) { if (dtu == du) dtu++; ans[dtu].push_back(i.second); dfs(i.first, dtu, ix); dtu++; } } void doit() { dfs(0, -1, -1); printf("%d\n", mx); for (int i = 0; i < mx; i++) { printf("%lu ", ans[i].size()); for (auto j : ans[i]) printf("%d ", j); printf("\n"); } } }; int main() { int n, a, b; scanf("%d", &n); graphal g(n); for (auto i = 0; i < n - 1; i++) { scanf("%d %d", &a, &b); a--, b--; g.add(a, b, i + 1); } g.doit(); return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; const int N = 10010; long long t2[N], t3[N]; void solve() { string s; cin >> s; int n = s.size(); s += "#####"; long long res = 0; set<string> suffs; t2[n - 2] = 1; t3[n - 3] = 1; for (int i = n - 1; i >= 5; --i) { if (i + 3 < n) { if (s.substr(i, 3) != s.substr(i + 3, 3)) { t3[i] |= t3[i + 3]; } if (t2[i + 3] > 0) { t3[i] |= t2[i + 3]; } } if (i + 2 < n) { if (s.substr(i, 2) != s.substr(i + 2, 2)) { t2[i] |= t2[i + 2]; } if (t3[i + 2] > 0) { t2[i] |= t3[i + 2]; } } if (t2[i] > 0) { suffs.insert(s.substr(i, 2)); } if (t3[i] > 0) { suffs.insert(s.substr(i, 3)); } } cout << suffs.size() << endl; for (string x : suffs) { cout << x << endl; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << setprecision(7) << std::fixed; solve(); return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; template <class T, class U> inline void Max(T &a, U b) { if (a < b) a = b; } template <class T, class U> inline void Min(T &a, U b) { if (a > b) a = b; } inline void add(int &a, int b) { a += b; while (a >= 1000000007) a -= 1000000007; } int pow(int a, int b) { int ans = 1; while (b) { if (b & 1) ans = ans * (long long)a % 1000000007; a = (long long)a * a % 1000000007; b >>= 1; } return ans; } char s[10010]; bool dp[10010][4]; int n; bool can(int i, int j) { if (i >= n) return 1; return dp[i][j]; } bool check(int i, int first, int j, int second) { if (first != second) return 1; if (j + second > n) return 0; for (int k = 0; k < first; k++) if (s[i + k] != s[j + k]) return 1; return 0; } int main() { int i, j, k, m, T; scanf("%s", s); n = strlen(s); memset(dp, 0, sizeof(dp)); set<string> g; for (int i = n - 1 - 1; i >= 5; i--) { for (int j = 2; j < 4; j++) { if (i + j > n) break; string t = ""; for (int k = i; k < i + j; k++) t += s[k]; for (int k = 2; k < 4; k++) { if (can(i + j, k) && check(i, j, i + j, k)) { dp[i][j] = 1; g.insert(t); break; } } } } printf("%d\n", (int)g.size()); for (__typeof(g.begin()) it = g.begin(); it != g.end(); it++) { cout << *it << "\n"; } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; long long int a[1000005][5] = {0}; map<string, long long int> mp, tot; void fn(long long int l, long long int r); string str; int main() { cin >> str; fn(0, str.length() - 1); cout << tot.size() << endl; for (auto t : tot) cout << t.first << endl; return 0; } void fn(long long int l, long long int r) { if (r - l + 1 <= 6) return; string s1 = "aa"; s1[0] = str[r - 1]; s1[1] = str[r]; if (mp[s1] != r + 2) { long long int pre = mp[s1]; mp[s1] = r; tot[s1] = 1; if (!a[r][2]) fn(l, r - 2); a[r][2] = 1; mp[s1] = pre; } if (r - l + 1 <= 7) return; string s2 = "aaa"; s2[0] = str[r - 2]; s2[1] = str[r - 1]; s2[2] = str[r]; if (mp[s2] != r + 3) { long long int pre = mp[s2]; mp[s2] = r; tot[s2] = 1; if (!a[r][3]) fn(l, r - 3); a[r][3] = 1; mp[s2] = pre; } }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; char s[100111]; int n; int F[100111][2]; int sz[2] = {2, 3}; int Can(int k, int tp) { if (F[k][tp] != -1) return F[k][tp]; if (k + sz[tp] - 1 == n) return 1; if (k + sz[tp] - 1 > n) return 0; F[k][tp] = 0; if (tp == 0) { if (s[k] == s[k + 2] && s[k + 1] == s[k + 3]) { if (Can(k + 2, 1)) F[k][tp] = 1; } else { if (Can(k + 2, 0)) F[k][tp] = 1; else if (Can(k + 2, 1)) F[k][tp] = 1; } } else { if (s[k] == s[k + 3] && s[k + 1] == s[k + 4] && s[k + 2] == s[k + 5]) { if (Can(k + 3, 0)) F[k][tp] = 1; } else { if (Can(k + 3, 0)) F[k][tp] = 1; else if (Can(k + 3, 1)) F[k][tp] = 1; } } return F[k][tp]; } set<string> myset; set<string>::iterator myit; string str; int main() { int i, j; memset(F, -1, sizeof(F)); scanf("%s", s + 1); n = strlen(s + 1); s[n + 1] = 'z' + 1; s[n + 2] = 'z' + 1; s[n + 3] = 'z' + 1; for (i = 6; i <= n; i++) { str.clear(); if (i + 1 <= n) { if (Can(i, 0)) { str.push_back(s[i]); str.push_back(s[i + 1]); myset.insert(str); } } str.clear(); if (i + 2 <= n) { if (Can(i, 1)) { str.push_back(s[i]); str.push_back(s[i + 1]); str.push_back(s[i + 2]); myset.insert(str); } } } printf("%d\n", (int)myset.size()); for (myit = myset.begin(); myit != myset.end(); myit++) { str = (*myit); for (j = 0; j < str.length(); j++) { printf("%c", str[j]); } printf("\n"); } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int len = s.length(); bool dp[len + 2][2]; memset(dp, false, sizeof(dp)); dp[len][0] = dp[len][1] = true; set<string> ans; for (int i = len - 2; i > 4; --i) { if ((dp[i + 2][0] && s.substr(i, 2) != s.substr(i + 2, 2)) || dp[i + 2][1]) { ans.insert(s.substr(i, 2)); dp[i][0] = true; } if ((dp[i + 3][1] && s.substr(i, 3) != s.substr(i + 3, 3)) || dp[i + 3][0]) { ans.insert(s.substr(i, 3)); dp[i][1] = true; } } if (ans.empty()) { cout << 0 << endl; return 0; } cout << ans.size() << endl; set<string>::iterator iterator1 = ans.begin(); for (; iterator1 != ans.end(); iterator1++) { cout << *iterator1 << endl; } }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
import java.io.*; import java.lang.reflect.Array; import java.math.*; import java.util.*; public class icpc { static String s = ""; static HashSet<String> h = new HashSet<>(); static HashSet<Integer> h1 = new HashSet<>(); public static void main(String[] args) throws IOException { // Reader in = new Reader(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int n = s.length(); boolean[][] DP = new boolean[2][n]; DP[0][n - 2] = true; DP[1][n - 3] = true; for (int i = n - 4;i>=5;i--) { DP[0][i] = DP[1][i + 2] || (DP[0][i + 2] && !s.substring(i, i + 2).equals(s.substring(i + 2, i + 4))); DP[1][i] = DP[0][i + 3] || (DP[1][i + 3] && !s.substring(i, i + 3).equals(s.substring(i + 3, i + 6))); } TreeSet<String> t = new TreeSet<>(); for (int i=5;i<n;i++) { if (DP[0][i]) t.add(s.substring(i, i + 2)); if (DP[1][i]) t.add(s.substring(i, i + 3)); } ArrayList<String> A = new ArrayList<>(t); System.out.println(A.size()); for (int i=0;i<A.size();i++) System.out.println(A.get(i)); } } class NumberTheory { public boolean isPrime(long n) { if(n < 2) return false; for(long x = 2;x * x <= n;x++) { if(n % x == 0) return false; } return true; } public ArrayList<Long> primeFactorisation(long n) { ArrayList<Long> f = new ArrayList<>(); for(long x=2;x * x <= n;x++) { while(n % x == 0) { f.add(x); n /= x; } } if(n > 1) f.add(n); return f; } public int[] sieveOfEratosthenes(int n) { int[] sieve = new int[n + 1]; for(int x=2;x<=n;x++) { if(sieve[x] != 0) continue; sieve[x] = x; for(int u=2*x;u<=n;u+=x) if(sieve[u] == 0) sieve[u] = x; } return sieve; } public long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } public long phi(long n) { double result = n; for(long p=2;p*p<=n;p++) { if(n % p == 0) { while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double)p)); } } if(n > 1) result *= (1.0 - (1.0 / (double)n)); return (long)result; } public Name extendedEuclid(long a, long b) { if(b == 0) return new Name(a, 1, 0); Name n1 = extendedEuclid(b, a % b); Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y); return n2; } public long modularExponentiation(long a, long b, long n) { long d = 1L; String bString = Long.toBinaryString(b); for(int i=0;i<bString.length();i++) { d = (d * d) % n; if(bString.charAt(i) == '1') d = (d * a) % n; } return d; } } class Name { long d; long x; long y; public Name(long d, long x, long y) { this.d = d; this.x = x; this.y = y; } } class SuffixArray { int ALPHABET_SZ = 256, N; int[] T, lcp, sa, sa2, rank, tmp, c; public SuffixArray(String str) { this(toIntArray(str)); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { T = text; N = text.length; sa = new int[N]; sa2 = new int[N]; rank = new int[N]; c = new int[Math.max(ALPHABET_SZ, N)]; construct(); kasai(); } private void construct() { int i, p, r; for (i = 0; i < N; ++i) c[rank[i] = T[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i; for (p = 1; p < N; p <<= 1) { for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i; for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p; Arrays.fill(c, 0, ALPHABET_SZ, 0); for (i = 0; i < N; ++i) c[rank[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i]; for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i) { if (!(rank[sa[i - 1]] == rank[sa[i]] && sa[i - 1] + p < N && sa[i] + p < N && rank[sa[i - 1] + p] == rank[sa[i] + p])) r++; sa2[sa[i]] = r; } tmp = rank; rank = sa2; sa2 = tmp; if (r == N - 1) break; ALPHABET_SZ = r + 1; } } private void kasai() { lcp = new int[N]; int[] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; for (int i = 0, len = 0; i < N; i++) { if (inv[i] > 0) { int k = sa[inv[i] - 1]; while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++; lcp[inv[i] - 1] = len; if (len > 0) len--; } } } } class ZAlgorithm { public int[] calculateZ(char input[]) { int Z[] = new int[input.length]; int left = 0; int right = 0; for(int k = 1; k < input.length; k++) { if(k > right) { left = right = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } else { //we are operating inside box int k1 = k - left; //if value does not stretches till right bound then just copy it. if(Z[k1] < right - k + 1) { Z[k] = Z[k1]; } else { //otherwise try to see if there are more matches. left = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } } } return Z; } public ArrayList<Integer> matchPattern(char text[], char pattern[]) { char newString[] = new char[text.length + pattern.length + 1]; int i = 0; for(char ch : pattern) { newString[i] = ch; i++; } newString[i] = '$'; i++; for(char ch : text) { newString[i] = ch; i++; } ArrayList<Integer> result = new ArrayList<>(); int Z[] = calculateZ(newString); for(i = 0; i < Z.length ; i++) { if(Z[i] == pattern.length) { result.add(i - pattern.length - 1); } } return result; } } class KMPAlgorithm { public int[] computeTemporalArray(char[] pattern) { int[] lps = new int[pattern.length]; int index = 0; for(int i=1;i<pattern.length;) { if(pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } return lps; } public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern) { int[] lps = computeTemporalArray(pattern); int j = 0; int i = 0; int n = text.length; int m = pattern.length; ArrayList<Integer> indices = new ArrayList<>(); while(i < n) { if(pattern[j] == text[i]) { i++; j++; } if(j == m) { indices.add(i - j); j = lps[j - 1]; } else if(i < n && pattern[j] != text[i]) { if(j != 0) j = lps[j - 1]; else i = i + 1; } } return indices; } } class Hashing { public long[] computePowers(long p, int n, long m) { long[] powers = new long[n]; powers[0] = 1; for(int i=1;i<n;i++) { powers[i] = (powers[i - 1] * p) % m; } return powers; } public long computeHash(String s) { long p = 31; long m = 1_000_000_009; long hashValue = 0L; long[] powers = computePowers(p, s.length(), m); for(int i=0;i<s.length();i++) { char ch = s.charAt(i); hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m; } return hashValue; } } class BasicFunctions { public long min(long[] A) { long min = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min = Math.min(min, A[i]); } return min; } public long max(long[] A) { long max = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { max = Math.max(max, A[i]); } return max; } } class Matrix { long a; long b; long c; long d; public Matrix(long a, long b, long c, long d) { this.a = a; this.b = b; this.c = c; this.d = d; } } class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { int sum; int len; Node(int a, int b) { this.sum = a; this.len = b; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.sum == obj.sum && this.len == obj.len) return true; return false; } @Override public int hashCode() { return (int)this.len; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MIN_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MIN_VALUE; } int mid = (low+high)/2; return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1), rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2)); } } class Trie { private class TrieNode { Map<Character, TrieNode> children; boolean endOfWord; public TrieNode() { children = new HashMap<>(); endOfWord = false; } } private final TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i=0;i<word.length();i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { node = new TrieNode(); current.children.put(ch, node); } current.endOfWord = true; } } public boolean search(String word) { TrieNode current = root; for (int i=0;i<word.length();i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) return false; current = node; } return current.endOfWord; } public void delete(String word) { delete(root, word, 0); } private boolean delete(TrieNode current, String word, int index) { if (index == word.length()) { if (!current.endOfWord) return false; current.endOfWord = false; return current.children.size() == 0; } char ch = word.charAt(index); TrieNode node = current.children.get(ch); if (node == null) return false; boolean shouldDeleteCurrentNode = delete(node, word, index + 1); if (shouldDeleteCurrentNode) { current.children.remove(ch); return current.children.size() == 0; } return false; } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; string s; set<string> vals; int N; vector<bool> seen; map<pair<pair<int, int>, int>, bool> rem; bool cansplit(int current, int prevl, int length) { pair<pair<int, int>, int> key = make_pair(make_pair(current, prevl), length); map<pair<pair<int, int>, int>, bool>::iterator it = rem.find(key); if (it != rem.end()) { return it->second; } if (current == N) { return true; } if (prevl == 0) { if (N - current - length >= 0) { bool ans = cansplit(current + length, length, 2); if (ans == false) { ans = cansplit(current + length, length, 3); } rem[make_pair(make_pair(current, prevl), length)] = ans; return ans; } } if (N - current - length >= 0) { if (length != prevl) { bool ans = cansplit(current + length, length, 2); if (ans == false) { ans = cansplit(current + length, length, 3); } rem[make_pair(make_pair(current, prevl), length)] = ans; return ans; } else { bool ok = false; for (int i = current - length; i < current; i++) { if (s[i] != s[i + length]) { ok = true; } } if (ok == false) { rem[make_pair(make_pair(current, prevl), length)] = false; return false; } else { bool ans = cansplit(current + length, length, 2); if (ans == false) { ans = cansplit(current + length, length, 3); } rem[make_pair(make_pair(current, prevl), length)] = ans; return ans; } } } rem[make_pair(make_pair(current, prevl), length)] = false; return false; } int main() { cin >> s; N = s.size(); seen.resize(N, false); int current = N - 2; while (current > 4) { for (int l = 2; l <= 3; l++) { if (cansplit(current, 0, l)) { string newstr = ""; for (int i = 0; i < l; i++) { newstr += s[current + i]; } vals.insert(newstr); } } --current; } cout << vals.size() << endl; for (set<string>::iterator it = vals.begin(); it != vals.end(); it++) { cout << *it << endl; } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; bool valid[10000 + 100]; set<string> ans; int main() { string s; getline(cin, s); valid[s.length()] = 1; for (int i = s.length() - 1; i > 4; --i) { if (valid[i + 2]) { string t = s.substr(i, 2); if (s.find(t, i + 2) != i + 2 || valid[i + 5]) { valid[i] = 1; ans.insert(t); } } if (valid[i + 3]) { string t = s.substr(i, 3); if (s.find(t, i + 3) != i + 3 || valid[i + 5]) { valid[i] = 1; ans.insert(t); } } } cout << ans.size() << "\n"; for (auto &ite : ans) { cout << ite << "\n"; } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; long long power(long long x, long long y) { if (y == 0) return 1ll; if (y % 2) return (x % 1000000007 * power(x, y - 1) % 1000000007) % 1000000007; else return power((x * x) % 1000000007, y / 2) % 1000000007; } set<string> ans; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); string s; cin >> s; int n = s.length(); bool dp[n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) { dp[i][j] = false; } } if (n - 3 > 4) { dp[n - 3][1] = true; ans.insert(s.substr(n - 3, 3)); } if (n - 2 > 4) { dp[n - 2][0] = true; ans.insert(s.substr(n - 2, 2)); } for (int i = n - 4; i > 4; i--) { if (dp[i + 2][1]) { dp[i][0] = true; ans.insert(s.substr(i, 2)); } else if (dp[i + 2][0]) { if (s.substr(i, 2) != s.substr(i + 2, 2)) { dp[i][0] = true; ans.insert(s.substr(i, 2)); } } if (dp[i + 3][0]) { dp[i][1] = true; ans.insert(s.substr(i, 3)); } else if (dp[i + 3][1]) { if (s.substr(i, 3) != s.substr(i + 3, 3)) { dp[i][1] = true; ans.insert(s.substr(i, 3)); } } } cout << ans.size() << "\n"; for (auto j : ans) cout << j << "\n"; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; const int maxn = 100000; char S[maxn]; set<string> ans; bool f[maxn][3]; int main() { scanf("%s", S); int len = strlen(S); f[len - 2][0] = true; f[len - 3][1] = true; for (int i = len - 2; i >= 5; --i) { if (f[i + 2][0] && (S[i] != S[i + 2] || S[i + 1] != S[i + 3])) f[i][0] = true; if (f[i + 2][1]) f[i][0] = true; if (f[i][0]) { string s = ""; s += S[i]; s += S[i + 1]; ans.insert(s); } if (f[i + 3][1] && (S[i] != S[i + 3] || S[i + 1] != S[i + 4] || S[i + 2] != S[i + 5])) f[i][1] = true; if (f[i + 3][0]) f[i][1] = true; if (f[i][1]) { string s = ""; s += S[i]; s += S[i + 1]; s += S[i + 2]; ans.insert(s); } } printf("%d\n", (int)ans.size()); for (set<string>::iterator it = ans.begin(); it != ans.end(); ++it) { cout << *it << endl; } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
/** * Created by yume on 2016/5/25. */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { public static void main(final String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(in, out); out.close(); } static class TaskA{ public void solve(InputReader in, PrintWriter out) { String s = in.next(); int sLen = s.length(); boolean[][] can = new boolean[sLen + 1][2]; can[sLen - 2][0] = can[sLen - 3][1] = true; for (int pos = sLen - 4; pos >= 5; pos--) { for (int len = 2; len <= 3; len++) { for (int nLen = 2; nLen <= 3 && pos + len + nLen <= sLen; nLen++) { if (can[pos + len][nLen - 2]) { boolean ok = true; if (len == nLen) { ok = false; for (int i = 0; i < len; i++) { if (s.charAt(pos + i) != s.charAt(pos + len + i)) { ok = true; } } } if (ok) { can[pos][len - 2] = true; } } } } } TreeSet<String> suffixes = new TreeSet<>(); for (int pos = sLen; pos >= 5; pos--) { for (int len = 2; len <= 3; len++) { if (can[pos][len - 2]) { suffixes.add(s.substring(pos, pos + len)); } } } out.println(suffixes.size()); suffixes.stream().forEach(suffix -> out.println(suffix)); // for(String suffix : suffixes) { // out.println(suffix); // } } } static class InputReader { private final BufferedReader buffer; private StringTokenizer tok; InputReader(InputStream stream) { buffer = new BufferedReader(new InputStreamReader(stream), 32768); } private boolean haveNext() { while (tok == null || !tok.hasMoreElements()) { try { tok = new StringTokenizer(buffer.readLine()); } catch (final Exception e) { throw new RuntimeException(e); } } return true; } protected String next() { if (haveNext()) { return tok.nextToken(); } return null; } protected String nextLine() { if (haveNext()) { return tok.nextToken("\n"); } return null; } protected int nextInt() { return Integer.parseInt(next()); } protected long nextLong() { return Long.parseLong(next()); } protected double nextDouble() { return Double.parseDouble(next()); } } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; const int MM = 1e4 + 5; int n; bool dp[MM][2]; string s; int main() { cin.tie(0)->sync_with_stdio(0); cin >> s; n = s.size(); if (n == 5) return cout << "0\n", 0; set<string> ss; dp[n - 2][0] = dp[n - 3][1] = 1; for (int i = n - 4; i > 4; i--) { string two = s.substr(i, 2), three = s.substr(i, 3); dp[i][0] |= dp[i + 2][1]; if (two != s.substr(i + 2, 2)) dp[i][0] |= dp[i + 2][0]; dp[i][1] |= dp[i + 3][0]; if (three != s.substr(i + 3, 3)) dp[i][1] |= dp[i + 3][1]; } for (int i = 5; i < n - 1; i++) { if (dp[i][0]) ss.insert(s.substr(i, 2)); if (dp[i][1] && i + 2 < n) ss.insert(s.substr(i, 3)); } cout << ss.size() << "\n"; for (auto& t : ss) cout << t << "\n"; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; int n; bool dp[10001][2]; string str; set<string> s; int main() { cin >> str; n = str.length(); for (register int i = n - 2; i >= 5; --i) { if (i + 2 == n) dp[i][0] = 1; if (i + 3 == n) dp[i][1] = 1; if (dp[i + 3][0]) dp[i][1] = 1; if (dp[i + 2][1]) dp[i][0] = 1; if (i + 4 <= n && dp[i + 2][0] && str.substr(i, 2) != str.substr(i + 2, 2)) dp[i][0] = 1; if (i + 6 <= n && dp[i + 3][1] && str.substr(i, 3) != str.substr(i + 3, 3)) dp[i][1] = 1; if (dp[i][0]) s.insert(str.substr(i, 2)); if (dp[i][1]) s.insert(str.substr(i, 3)); } cout << s.size() << endl; for (register set<string>::iterator it = s.begin(); it != s.end(); ++it) cout << *it << endl; return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
import java.util.Scanner; import java.util.TreeSet; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); TreeSet<String> suffixes = new TreeSet<>(); String word = sc.nextLine(); sc.close(); String tempSubstring; boolean doubleStepIsPossible[] = new boolean[word.length()]; boolean tripleStepIsPossible[] = new boolean[word.length()]; if(word.length() <= 6){ System.out.println("0"); return; } int wordLength = word.length(); doubleStepIsPossible[wordLength - 2] = true; suffixes.add(word.substring(wordLength - 2, wordLength)); if(wordLength > 7){ tripleStepIsPossible[wordLength - 3] = true; suffixes.add(word.substring(wordLength - 3, wordLength)); } for(int i = wordLength - 4; i >= 5; i--) { tempSubstring = word.substring(i, i + 2); doubleStepIsPossible[i] = tripleStepIsPossible[i + 2] || (doubleStepIsPossible[i + 2] && (!tempSubstring.equals(word.substring(i + 2, i + 4)))); if(doubleStepIsPossible[i]) { suffixes.add(tempSubstring); } tempSubstring = word.substring(i, i + 3); tripleStepIsPossible[i] = doubleStepIsPossible[i + 3] || (tripleStepIsPossible[i + 3] && (!tempSubstring.equals(word.substring(i + 3, i + 6)))); if(tripleStepIsPossible[i]) { suffixes.add(tempSubstring); } } System.out.println(suffixes.size()); suffixes.forEach(System.out::println); } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.StringTokenizer; /** * * @author is2ac */ public class C_CF { static HashSet<String> set; public static void main(String[] args) { FastScanner57 fs = new FastScanner57(); PrintWriter pw = new PrintWriter(System.out); //int t = fs.ni(); int t = 1; for (int tc = 0; tc < t; tc++) { set = new HashSet(); String s = fs.next(); int n = s.length(); Integer[][] dp = new Integer[n][2]; for (int i = 5; i < n; i++) { if (good(i+2,0,s,dp)) set.add(s.substring(i,i+2)); if (good(i+3,1,s,dp)) set.add(s.substring(i,i+3)); } List<String> list = new ArrayList(); for (String val : set) list.add(val); Collections.sort(list); pw.println(list.size()); for (int i = 0; i < list.size(); i++) { pw.println(list.get(i)); } } pw.close(); } public static boolean good(int i, int l, String s, Integer[][] dp) { if (i==s.length()) return true; if (i>s.length()) return false; if (dp[i][l]!=null) { if (dp[i][l]==0) { return true; } else { return false; } } boolean b = false; if (i+2<=s.length() && (l==1 || !s.substring(i-2,i).equals(s.substring(i,i+2)))) { if (good(i+2,0,s,dp)) { b = true; set.add(s.substring(i,i+2)); } } if (i+3<=s.length() && (l==0 || !s.substring(i-3,i).equals(s.substring(i,i+3)))) { if (good(i+3,1,s,dp)) { b = true; set.add(s.substring(i,i+3)); } } if (b) { dp[i][l]=0; } else { dp[i][l]=1; } return b; } public static int gcd(int n1, int n2) { if (n2 == 0) { return n1; } return gcd(n2, n1 % n2); } } class UnionFind16 { int[] id; public UnionFind16(int size) { id = new int[size]; for (int i = 0; i < size; i++) { id[i] = i; } } public int find(int p) { int root = p; while (root != id[root]) { root = id[root]; } while (p != root) { int next = id[p]; id[p] = root; p = next; } return root; } public void union(int p, int q) { int a = find(p), b = find(q); if (a == b) { return; } id[b] = a; } } class FastScanner57 { BufferedReader br; StringTokenizer st; public FastScanner57() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) { ret[i] = ni(); } return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) { ret[i] = nl(); } return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#!/usr/bin/python2 # -*- coding: utf-8 -*- import sys import os def build_must(s): s = "".join(reversed(s)) r = [None, None, s[:2], s[:3]] c3 = s[:3] c2 = s[1:3] for c in s[3:]: c3 = c3[-2] + c3[-1] + c c2 = c2[-1] + c t2 = t3 = None if r[-3] is not None: if c3 != r[-3]: t3 = c3 if r[-2] is not None: if c2 != r[-2]: t2 = c2 if t2 is not None and t3 is not None: r.append("") elif t2 is not None: r.append(t2) else: r.append(t3) return r def solve(s): if len(s) < 2: return [] if len(s) < 3: return [s] must = build_must(s) r = set() r.add(s[-2:]) r.add(s[-3:]) for i in xrange(0, len(s) - 2): q = must[len(s) - i - 2] if q is not None and s[i:i+2] != q: r.add(s[i:i+2]) for i in xrange(0, len(s) - 3): q = must[len(s) - i - 3] if q is not None and s[i:i+3] != q: r.add(s[i:i+3]) return r def main(): s = sys.stdin.readline().strip()[5:] r = list(solve(s)) r.sort() print len(r) for x in r: print x if __name__ == '__main__': main()
PYTHON
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; const int oo = (int)1e9; const double PI = 2 * acos(0.0); const double eps = 1e-9; set<string> seen[10009], ret; string s; int n; void dfs(int ind, string next) { if (!seen[ind].insert(next).second) return; if (ind - 2 > 4) { string x = ""; x += s[ind - 2]; x += s[ind - 1]; if (x != next) { ret.insert(x); dfs(ind - 2, x); } } if (ind - 3 > 4) { string x = ""; x += s[ind - 3]; x += s[ind - 2]; x += s[ind - 1]; if (x != next) { ret.insert(x); dfs(ind - 3, x); } } } int main() { cin >> s; dfs(((int)s.size()), ""); printf("%d\n", ((int)ret.size())); for (__typeof(ret.begin()) it = ret.begin(); it != ret.end(); ++it) printf("%s\n", it->c_str()); return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; const double eps = 0.000000000000001; string convertstring(long long n) { stringstream ss; ss << n; return ss.str(); } int len, dp[10005][4]; string s; int solve(int ind, int last) { if (ind == len) return dp[ind][last] = 1; int &ans = dp[ind][last]; if (ans != -1) return ans; ans = 0; if (last == 0) { if (ind + 2 <= len) ans |= solve(ind + 2, 2); if (ind + 3 <= len) ans |= solve(ind + 3, 3); } else if (last == 3 && ind + 2 <= len) { ans |= solve(ind + 2, 2); if (ind + 3 <= len) { int i; for (i = ind - 3; i < ind; ++i) if (s[i] != s[i + 3]) break; if (i != ind) ans |= solve(ind + 3, 3); } } else if (last == 2 && ind + 2 <= len) { if (ind + 3 <= len) ans |= solve(ind + 3, 3); int i; for (i = ind - 2; i < ind; ++i) if (s[i] != s[i + 2]) break; if (i != ind) ans |= solve(ind + 2, 2); } return ans; } vector<string> v; int main() { memset(dp, -1, sizeof(dp)); ; cin >> s; len = s.size(); int i; for (i = 5; i < len; ++i) { solve(i, 0); if (dp[i][2] == 1) v.push_back(s.substr(i - 2, 2)); if (dp[i][3] == 1) v.push_back(s.substr(i - 3, 3)); } if (dp[i][2] == 1) v.push_back(s.substr(i - 2, 2)); if (dp[i][3] == 1) v.push_back(s.substr(i - 3, 3)); sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); cout << v.size() << endl; for (i = 0; i < v.size(); ++i) cout << v[i] << endl; return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; string s; set<string> tmp; bool dp[10010][5]; void go(int i, int prv) { if (dp[i][prv]) return; dp[i][prv] = 1; if (s.substr(i, 2) != s.substr(i - prv, prv) && i + 6 < s.size()) { string t = s.substr(i, 2); reverse(t.begin(), t.end()); tmp.insert(t); go(i + 2, 2); } if (s.substr(i, 3) != s.substr(i - prv, prv) && i + 7 < s.size()) { string t = s.substr(i, 3); reverse(t.begin(), t.end()); tmp.insert(t); go(i + 3, 3); } } int main() { while (cin >> s) { reverse(s.begin(), s.end()); memset(dp, 0, sizeof dp); tmp.clear(); go(0, 0); cout << tmp.size() << endl; for (set<string>::iterator it = tmp.begin(); it != tmp.end(); it++) { cout << *it << endl; } } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; string s; unordered_set<string> suffixes; bool checked[2][10001]; void solve(int end, const string& prev) { bool& c = checked[prev.length() - 2][end]; if (c) return; c = true; for (int i = 2; i < 4; ++i) { if (end - i < 5) continue; string suffix = s.substr(end - i, i); if (prev == suffix) continue; suffixes.insert(suffix); solve(end - i, suffix); } } int main() { cin >> s; solve(s.length(), " "); vector<string> vec{suffixes.begin(), suffixes.end()}; sort(vec.begin(), vec.end()); cout << vec.size() << endl; for (auto& ss : vec) cout << ss << endl; return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
from sys import * setrecursionlimit(200000) d = {} t = set() s = input() + ' ' def gen(l, ll): if (l, ll) in t: return t.add((l, ll)) if l > 6: d[s[l - 2 : l]] = 1 if s[l - 2 : l] != s[l : ll]: gen(l - 2, l) if l > 7: d[s[l - 3 : l]] = 1 if s[l - 3 : l] != s[l : ll]: gen(l - 3, l) gen(len(s) - 1,len(s)) print(len(d)) for k in sorted(d): print(k)
PYTHON3
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class Main { private static StringTokenizer st; private static BufferedReader br; public static long MOD = 1000000007; public static void print(Object x) { System.out.println(x + ""); } public static void printArr(long[] x) { StringBuilder s = new StringBuilder(); for (int i = 0; i < x.length; i++) { s.append(x[i] + " "); } print(s); } public static void printArr(int[] x) { StringBuilder s = new StringBuilder(); for (int i = 0; i < x.length; i++) { s.append(x[i] + " "); } print(s); } public static void printArr(char[] x) { StringBuilder s = new StringBuilder(); for (int i = 0; i < x.length; i++) { s.append(x[i] + ""); } print(s); } public static String join(Collection<?> x, String space) { if (x.size() == 0) return ""; StringBuilder sb = new StringBuilder(); boolean first = true; for (Object elt : x) { if (first) first = false; else sb.append(space); sb.append(elt); } return sb.toString(); } public static String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String line = br.readLine(); st = new StringTokenizer(line.trim()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static class Pair { int index; boolean two; public Pair(int index, boolean two) { this.index = index; this.two = two; } public String substring(String s) { int length = two ? 2 : 3; if (index >= s.length()) return ""; return s.substring(index, index + length); } @Override public int hashCode() { return (index + " " + two).hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof Pair) { Pair p = (Pair) obj; return index == p.index && two == p.two; } return false; } } public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new FileReader("input.txt")); String s = nextToken(); Set<Pair> seen = new HashSet<>(); List<Pair> todo = new ArrayList<>(); todo.add(new Pair(s.length(), true)); while (todo.size() > 0) { Pair p = todo.remove(todo.size() - 1); if (seen.contains(p)) continue; seen.add(p); Pair p2 = new Pair(p.index - 2, true); if (p2.index < 5) continue; if (!p2.substring(s).equals(p.substring(s))) todo.add(p2); p2 = new Pair(p.index - 3, false); if (p2.index < 5) continue; if (!p2.substring(s).equals(p.substring(s))) todo.add(p2); } Set<String> suffixes = new HashSet<>(); for (Pair p : seen) suffixes.add(p.substring(s)); List<String> ordered = new ArrayList<>(suffixes); Collections.sort(ordered); print(ordered.size() - 1); for (String suffix : ordered) if (suffix.length() > 0) print(suffix); } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; template <typename T> void read(T &x) { x = 0; char ch = getchar(); int fh = 1; while (ch < '0' || ch > '9') { if (ch == '-') fh = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); x *= fh; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } string s; set<string> st; bool mem[10005][4]; signed main() { cin >> s; queue<pair<int, int>> q; q.push(make_pair(s.size(), 0)); while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); if (mem[p.first][p.second]) continue; mem[p.first][p.second] = 1; if (p.first - 5 >= 2) { string pre = s.substr(p.first, p.second); string suf = s.substr(p.first - 2, 2); if (suf != pre) { st.insert(suf); q.push(make_pair(p.first - 2, 2)); } } if (p.first - 5 >= 3) { string pre = s.substr(p.first, p.second); string suf = s.substr(p.first - 3, 3); if (suf != pre) { st.insert(suf); q.push(make_pair(p.first - 3, 3)); } } } writeln(st.size()); for (register set<string>::iterator it = st.begin(); it != st.end(); ++it) cout << *it << endl; return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; template <typename T, typename U> inline void smin(T &a, U b) { if (a > b) a = b; } template <typename T, typename U> inline void smax(T &a, U b) { if (a < b) a = b; } int power(int a, int b, int m, int ans = 1) { for (; b; b >>= 1, a = 1LL * a * a % m) if (b & 1) ans = 1LL * ans * a % m; return ans; } char s[100010]; int dp[100010][5], vst[100010]; vector<string> ans; string ss; int main() { scanf("%s", s + 1); int n = strlen(s + 1); for (int i = n; i >= 1; i--) { if (i == n) { dp[i][2] = 0; dp[i][3] = 0; continue; } if (i == n - 1) { dp[i][2] = 1; dp[i][3] = 0; continue; } if (i == n - 2) { dp[i][2] = 0; dp[i][3] = 1; continue; } if (dp[i + 2][3] == 1) dp[i][2] = 1; else if (dp[i + 2][2] == 1 && (s[i] != s[i + 2] || s[i + 1] != s[i + 3])) dp[i][2] = 1; else dp[i][2] = 0; if (dp[i + 3][2] == 1) dp[i][3] = 1; else if (dp[i + 3][3] == 1 && (s[i] != s[i + 3] || s[i + 1] != s[i + 4] || s[i + 2] != s[i + 5])) dp[i][3] = 1; else dp[i][3] = 0; } int k = 0; for (int i = 6; i <= n; i++) { if (dp[i][2] == 1) { ss.clear(); ss += s[i]; ss += s[i + 1]; ans.push_back(ss); } if (dp[i][3] == 1) { ss.clear(); ss += s[i]; ss += s[i + 1]; ss += s[i + 2]; ans.push_back(ss); } } sort(ans.begin(), ans.end()); ans.resize(unique(ans.begin(), ans.end()) - ans.begin()); printf("%d\n", ans.size()); for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl; return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; int dp[2][10005]; char s[10005]; int main() { cin >> s; int n = strlen(s); dp[0][n - 2] = 1; dp[1][n - 3] = 1; for (int i = n - 4; i >= 0; i--) { if (dp[1][i + 2] == 1 || (dp[0][i + 2] == 1 && (s[i] != s[i + 2] || s[i + 1] != s[i + 3]))) dp[0][i] = 1; if (dp[0][i + 3] == 1 || (dp[1][i + 3] == 1 && (s[i] != s[i + 3] || s[i + 1] != s[i + 4] || s[i + 2] != s[i + 5]))) dp[1][i] = 1; } set<string> ans; for (int i = 5; i < n; i++) { if (dp[0][i]) { string ss; ss += s[i]; ss += s[i + 1]; ans.insert(ss); } if (dp[1][i]) { string ss; ss += s[i]; ss += s[i + 1]; ss += s[i + 2]; ans.insert(ss); } } cout << ans.size(); cout << endl; for (auto s : ans) { cout << s << endl; } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> #pragma GCC optimize("-O3") using namespace std; using lli = long long int; using llu = long long unsigned; using pii = tuple<lli, lli>; using piii = tuple<lli, lli, lli>; using piiii = tuple<lli, lli, lli, lli>; using vi = vector<lli>; using vii = vector<pii>; using viii = vector<piii>; using vvi = vector<vi>; using vvii = vector<vii>; using vviii = vector<viii>; template <class T> using min_queue = priority_queue<T, vector<T>, greater<T>>; template <class T> using max_queue = priority_queue<T>; template <int... I> struct my_index_sequence { using type = my_index_sequence; static constexpr array<int, sizeof...(I)> value = {I...}; }; namespace my_index_sequence_detail { template <typename I, typename J> struct concat; template <int... I, int... J> struct concat<my_index_sequence<I...>, my_index_sequence<J...>> : my_index_sequence<I..., (sizeof...(I) + J)...> {}; template <int N> struct make_index_sequence : concat<typename make_index_sequence<N / 2>::type, typename make_index_sequence<N - N / 2>::type>::type {}; template <> struct make_index_sequence<0> : my_index_sequence<> {}; template <> struct make_index_sequence<1> : my_index_sequence<0> {}; } // namespace my_index_sequence_detail template <class... A> using my_index_sequence_for = typename my_index_sequence_detail::make_index_sequence<sizeof...(A)>::type; template <class T, int... I> void print_tuple(ostream& s, T const& a, my_index_sequence<I...>) { using swallow = int[]; (void)swallow{0, (void(s << (I == 0 ? "" : ", ") << get<I>(a)), 0)...}; } template <class T> ostream& print_collection(ostream& s, T const& a) { s << '['; for (auto it = begin(a); it != end(a); ++it) { s << *it; if (it != prev(end(a))) s << " "; } return s << ']'; } template <class... A> ostream& operator<<(ostream& s, tuple<A...> const& a) { s << '('; print_tuple(s, a, my_index_sequence_for<A...>{}); return s << ')'; } template <class A, class B> ostream& operator<<(ostream& s, pair<A, B> const& a) { return s << "(" << get<0>(a) << ", " << get<1>(a) << ")"; } template <class T, int I> ostream& operator<<(ostream& s, array<T, I> const& a) { return print_collection(s, a); } template <class T> ostream& operator<<(ostream& s, vector<T> const& a) { return print_collection(s, a); } template <class T, class U> ostream& operator<<(ostream& s, multimap<T, U> const& a) { return print_collection(s, a); } template <class T> ostream& operator<<(ostream& s, multiset<T> const& a) { return print_collection(s, a); } template <class T, class U> ostream& operator<<(ostream& s, map<T, U> const& a) { return print_collection(s, a); } template <class T> ostream& operator<<(ostream& s, set<T> const& a) { return print_collection(s, a); } namespace std { namespace { template <class T> inline void hash_combine(size_t& seed, T const& v) { seed ^= hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } template <class Tuple, size_t Index = tuple_size<Tuple>::value - 1> struct HashValueImpl { static void apply(size_t& seed, Tuple const& tuple) { HashValueImpl<Tuple, Index - 1>::apply(seed, tuple); hash_combine(seed, get<Index>(tuple)); } }; template <class Tuple> struct HashValueImpl<Tuple, 0> { static void apply(size_t& seed, Tuple const& tuple) { hash_combine(seed, get<0>(tuple)); } }; } // namespace template <typename... TT> struct hash<tuple<TT...>> { size_t operator()(tuple<TT...> const& tt) const { size_t seed = 0; HashValueImpl<tuple<TT...>>::apply(seed, tt); return seed; } }; } // namespace std bool DP[2][100000]; int main(int, char**) { ios::sync_with_stdio(0); string s; cin >> s; int n = s.size(); set<string> r; DP[0][n - 2] = 1; DP[1][n - 3] = 1; for (lli i = (n - 4); i >= (lli)(0); --i) { if (DP[0][i + 2] && (s[i] != s[i + 2] || s[i + 1] != s[i + 3])) DP[0][i] = 1; if (DP[1][i + 2]) DP[0][i] = 1; if (DP[0][i + 3]) DP[1][i] = 1; if (DP[1][i + 3] && (s[i] != s[i + 3] || s[i + 1] != s[i + 4] || s[i + 2] != s[i + 5])) DP[1][i] = 1; } for (lli i = (5); i <= (lli)(n - 1); ++i) { if (DP[0][i]) { cerr << 2 << " " << i << endl; r.insert(string{s[i], s[i + 1]}); } if (DP[1][i]) { cerr << 3 << " " << i << endl; r.insert(string{s[i], s[i + 1], s[i + 2]}); } } cout << r.size() << endl; for (auto s : r) cout << s << "\n"; cout << flush; return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; int n; string s; set<string> a; int dp[10010][2]; bool ok(int i, int x) { if (i + x > n) return 0; if (i + x == n) return 1; if (i + x == n - 1) return 0; if (dp[i][x - 2] != -1) return dp[i][x - 2]; int &ref = dp[i][x - 2]; if (ok(i + x, 5 - x)) ref = 1; else if (i + x < n && s.substr(i, x) == s.substr(i + x, x)) ref = 0; else ref = ok(i + x, x); return ref; } int main() { memset(dp, -1, sizeof(dp)); cin >> s; n = s.size(); for (int i = 5; i < n; i++) { if (i + 2 <= n && i + 2 != n - 1 && ok(i, 2)) { a.insert(s.substr(i, 2)); } if (i + 3 <= n && i + 3 != n - 1 && ok(i, 3)) { a.insert(s.substr(i, 3)); } } cout << a.size() << '\n'; for (string t : a) { cout << t << '\n'; } }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
import java.util.*; import java.io.*; public class a { public static int[][] memo; public static String s; public static void main(String[] args){ Scanner br = new Scanner(System.in); s = br.next(); memo = new int[4][s.length()]; for(int i = 0;i<4;i++){ Arrays.fill(memo[i], -1); } TreeSet<String> suffs = new TreeSet<String>(); for(int i = 5;i<s.length()-1;i++){ if(go(2, i+2) == 1){ suffs.add(s.substring(i, i+2)); } if(go(3, i+3) == 1){ suffs.add(s.substring(i, i+3)); } } PrintWriter out = new PrintWriter(System.out); out.println(suffs.size()); for(String i : suffs){ out.println(i); } out.close(); } public static int go(int last, int pos){ if(pos == s.length()){ return 1; } if(pos > s.length()){ return 0; } if(pos == s.length()-1){ return 0; } if(memo[last][pos] != -1){ return memo[last][pos]; } String ls = s.substring(pos-last, pos); int ans = 0; for(int i = 2;i<=3;i++){ if(i+pos > s.length()){ continue; } if(i != last){ ans = Math.max(ans, go(i, pos+i)); } else{ if(ls.equals(s.substring(pos, pos+i))){ continue; } ans = Math.max(ans, go(i, pos+i)); } } return memo[last][pos] = ans; } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; void __print(int x) { cerr << x; } void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } void solve() { string s; cin >> s; long long n = s.size(); long long dp[n + 6][2]; s += "?????????"; memset(dp, 0, sizeof dp); if (n == 5) { cout << 0 << '\n'; return; } set<string> ans; dp[n - 2][0] = true; dp[n - 3][1] = true; for (long long i = n - 4; i >= 5; --i) { string sub = s.substr(i, 2); dp[i][0] = dp[i + 2][1] | (dp[i + 2][0] && sub + sub != s.substr(i, 4) && sub.back() != '?'); sub = s.substr(i, 3); dp[i][1] = dp[i + 3][0] | (dp[i + 3][1] && sub + sub != s.substr(i, 6) && sub.back() != '?'); } for (long long i = 5; i < n; ++i) { if (dp[i][0]) ans.insert(s.substr(i, 2)); if (dp[i][1]) ans.insert(s.substr(i, 3)); } cout << ans.size() << '\n'; for (auto x : ans) cout << x << " "; cout << '\n'; } signed main() { ios::sync_with_stdio(false); cin.tie(NULL); ; long long t = 1; while (t--) solve(); }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; public class MO { public static void main(String[] args) throws NumberFormatException, IOException { Scanner in = new Scanner(System.in); char[] word = in.nextLine().toCharArray(); int n = word.length; boolean[] dp2 = new boolean[word.length+1]; boolean[] dp3 = new boolean[word.length+1]; dp2[n-2] = true; dp3[n-3] = true; for(int i=n-4; i>=0; i--) { // check if we can start a 2 suffix here dp2[i] = dp3[i+2] || ((dp2[i+2] && !eq(i, 2, word))); dp3[i] = dp2[i+3] || ((dp3[i+3] && !eq(i, 3, word))); } Set<String> hash = new HashSet<>(); List<String> ans = new ArrayList<>(); for(int i=5; i<n; i++) { if(dp2[i]) { String s = new String(word).substring(i, i+2); if(!hash.contains(s)) { hash.add(s); ans.add(s); } } if(dp3[i]) { String s = new String(word).substring(i, i+3); if(!hash.contains(s)) { hash.add(s); ans.add(s); } } } Collections.sort(ans); System.out.println(ans.size()); for(String s : ans) { System.out.println(s); } } private static boolean eq(int i, int j, char[] word) { for(int m=0; m<j; m++) { if(word[i+m] != word[i+m+j]) { return false; } } return true; } }
JAVA
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
import sys sys.setrecursionlimit(10000) s = input() s = s[5:] + " " res = set() aux = set() def getWords(x,y): if (x,y) in aux: return aux.add((x,y)) if x > 1 and s[x:y] != s[x-2:x]: res.add(s[x-2:x]) getWords(x-2,x) if x > 2 and s[x:y] != s[x-3:x]: res.add(s[x-3:x]) getWords(x-3,x) getWords(len(s)-1,len(s)) print(len(res)) for word in sorted(list(res)): print(word)
PYTHON3
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
s = raw_input().strip() l = len(s) a = [[] for i in xrange(l + 2)] a[l-1] = a[l+1] = None for i in xrange(l - 2, 4, -1): t = s[i:i+2] if a[i+2] is not None and a[i+2] != [t]: a[i].append(t) t = s[i:i+3] if a[i+3] is not None and a[i+3] != [t]: a[i].append(t) if not a[i]: a[i] = None ans = set() for l in a: if l is not None: ans.update(l) ans = list(ans) ans.sort() print len(ans) for s in ans: print s
PYTHON
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; const int N = 1e4 + 5; int dp[N][4]; set<string> st[26]; set<string>::iterator it; string s; int n; void solve(int idx, int last) { if (idx <= 5) { return; } if (last != 0 && dp[idx][last - idx] != 0) { return; } string t, u; t.push_back(s[idx]); t.push_back(s[idx - 1]); reverse(t.begin(), t.end()); st[s[idx - 1] - 'a'].insert(t); if (idx == n - 1) { solve(idx - 2, idx); if (idx - 2 > 4) { reverse(t.begin(), t.end()); t.push_back(s[idx - 2]); reverse(t.begin(), t.end()); st[s[idx - 2] - 'a'].insert(t); solve(idx - 3, idx); } } else { int temp = last; while (temp > idx) { u.push_back(s[temp]); temp--; } reverse(u.begin(), u.end()); if (t != u) { solve(idx - 2, idx); } if (idx - 2 > 4) { reverse(t.begin(), t.end()); t.push_back(s[idx - 2]); reverse(t.begin(), t.end()); if (t != u) { st[s[idx - 2] - 'a'].insert(t); solve(idx - 3, idx); } } } if (last != 0) dp[idx][last - idx] = 1; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> s; n = s.length(); if (n <= 6) { cout << 0; return 0; } solve(n - 1, 0); int ans = 0; for (int i = 0; i < 26; i++) { if (!st[i].empty()) { ans += st[i].size(); } } cout << ans << "\n"; for (int i = 0; i < 26; i++) { if (!st[i].empty()) { for (it = st[i].begin(); it != st[i].end(); it++) { cout << *it << "\n"; } } } return 0; }
CPP
666_A. Reberland Linguistics
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. Input The only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters. Output On the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. Examples Input abacabaca Output 3 aca ba ca Input abaca Output 0 Note The first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
2
7
#include <bits/stdc++.h> using namespace std; template <typename Tp> inline void read(Tp &x) { static char c; static bool neg; x = 0, c = getchar(), neg = false; for (; !isdigit(c); c = getchar()) { if (c == '-') { neg = true; } } for (; isdigit(c); c = getchar()) { x = x * 10 + c - '0'; } if (neg) { x = -x; } } const int N = 1e4 + 5; string str, temp; int n; bool vis[N]; vector<string> vec; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); cin >> str; if (str.length() == 5UL) { puts("0"); return 0; } str = str.substr(5); n = (int)str.length(); vis[n] = true; for (int i = n - 1; i >= 0; --i) { for (int len = 2; len <= 3; ++len) { if (i + len <= n) { temp = str.substr(i, len); if ((str.find(temp, i + len) == str.npos || vis[i + 5]) && vis[i + len]) { vec.emplace_back(temp); vis[i] = true; } } } } sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); cout << vec.size() << "\n"; for (const auto &s : vec) { cout << s << "\n"; } }
CPP