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
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; public class Main implements Runnable { private class Query { private int id; private int l; private int r; private int q; Query(int l,int r,int q,int id) { this.l=l; this.r=r; this.q=q; this.id=id; } } public static void main(String args[]) { new Main().run(); } public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } out.flush(); } private void solve() throws IOException { int n=in.nextInt(); int m=in.nextInt(); Query q[]=new Query[m]; for(int i=0;i<m;i++) q[i]=new Query(in.nextInt()-1, in.nextInt()-1, in.nextInt(), i); int arr[]=new int[n]; Arrays.fill(arr, 0); int inc[]=new int[n+1]; for(int i=0;i<30;i++) { Arrays.fill(inc, 0); for(int j=0;j<m;j++) { if(testbit(q[j].q,i)) { inc[q[j].l]++; inc[q[j].r+1]--; } } int val=0; for(int j=0;j<n;j++) { val+=inc[j]; if(val!=0) arr[j]|=(1<<i); } } int ds=getds(n); int v[]=new int[2*ds]; boolean ok=true; Arrays.fill(v, 0); for(int i=0;i<n;i++) v[i+ds]=arr[i]; for(int i=ds-1;i>0;i--) v[i]=v[2*i]&v[2*i+1]; for(int i=0;i<m;i++) ok&=(accumulate(q[i].l,q[i].r,v,ds)==q[i].q); if(ok) { out.println("YES"); for(int i:arr) { out.print(i); out.print(' '); } out.println(); } else out.println("NO"); } private int accumulate(int l, int r, int[] v, int ds) { l+=ds; r+=ds; int res=(1<<30)-1; while(l<=r) { if((l&1)==1) res=res&v[l++]; if((r&1)==0) res=res&v[r--]; l>>=1; r>>=1; } return res; } private int getds(int n) { n--; n|=n>>1; n|=n>>2; n|=n>>4; n|=n>>8; n|=n>>16; return n+1; } private boolean testbit(int q, int i) { return ((q>>i)&1)==1; } class Scanner { BufferedReader in; StringTokenizer token; String delim; Scanner(Reader reader) { in=new BufferedReader(reader); token=new StringTokenizer(""); this.delim=" \n"; } Scanner(Reader reader, String delimeters) { in=new BufferedReader(reader); token=new StringTokenizer(""); this.delim=delimeters; } public boolean hasNext() throws IOException { while(!token.hasMoreTokens()) { String line=in.readLine(); if(line==null) return false; token=new StringTokenizer(line,delim); } return true; } String next() throws IOException { return hasNext()?token.nextToken():null; } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int[] nextInts(int n) throws IOException { int[] res=new int[n]; for(int i=0;i<n;i++) res[i]=nextInt(); return res; } } private Scanner in=new Scanner(new InputStreamReader(System.in),"\n\r\t "); private PrintWriter out=new PrintWriter(new BufferedWriter( new OutputStreamWriter(System.out))); }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int N = 1e5; const int M = 1e5; const int LG = 30; bool checkbit(int x, int i) { return (x >> i) & 1; } struct SEGTREE { bool tree[4 * N + 7]; bool lazy[4 * N + 7]; void flex(int ss, int se, int si) { if (lazy[si] == 1) { if (ss != se) { lazy[si * 2] = lazy[si * 2 + 1] = 1; } tree[si] = 1; lazy[si] = 0; } } void upd(int ss, int se, int si, int qs, int qe) { flex(ss, se, si); if (tree[si] == 1) { return; } if (qs > se || ss > qe) { return; } if (qs <= ss && se <= qe) { lazy[si] = 1; flex(ss, se, si); return; } upd(ss, ((ss + se) >> 1), si * 2, qs, qe); upd(((ss + se) >> 1) + 1, se, si * 2 + 1, qs, qe); tree[si] = tree[si * 2] & tree[si * 2 + 1]; } bool qry(int ss, int se, int si, int qs, int qe) { flex(ss, se, si); if (qs > se || ss > qe) { return 1; } if (qs <= ss && se <= qe) { return tree[si]; } return qry(ss, ((ss + se) >> 1), si * 2, qs, qe) & qry(((ss + se) >> 1) + 1, se, si * 2 + 1, qs, qe); } } seg[LG + 3]; int l[M + 7]; int r[M + 7]; int q[M + 7]; int ans[N + 7]; int main() { int n, m; cin >> n >> m; for (int i = 1; i <= m; i++) { scanf("%d %d %d", &l[i], &r[i], &q[i]); } for (int k = 0; k < LG; k++) { for (int i = 1; i <= m; i++) { if (checkbit(q[i], k) == 1) { seg[k].upd(1, n, 1, l[i], r[i]); } } for (int i = 1; i <= m; i++) { if (checkbit(q[i], k) == 0) { if (seg[k].qry(1, n, 1, l[i], r[i]) == 1) { cout << "NO" << endl; return 0; } } } } cout << "YES" << endl; for (int i = 1; i <= n; i++) { for (int k = 0; k < LG; k++) { ans[i] += seg[k].qry(1, n, 1, i, i) << k; } printf("%d ", ans[i]); } cout << endl; return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int queries[100005][3]; vector<pair<int, int> > ones; vector<pair<int, int> > zeros; int arr[100005]; int tree[2000000]; int lazy[2000000]; void init(int node, int l, int r) { lazy[node] = 0; tree[node] = 0; if (l != r) { int mid = (l + r) / 2; init(2 * node + 1, l, mid); init(2 * node + 2, mid + 1, r); } } void lazy_update(int node, int l, int r) { if (!lazy[node]) { return; } tree[node] = tree[node] | lazy[node]; if (l != r) { lazy[2 * node + 1] |= lazy[node]; lazy[2 * node + 2] |= lazy[node]; } lazy[node] = 0; return; } void update(int node, int l, int r, int a, int b, int val) { lazy_update(node, l, r); if (a > r || b < l) { return; } if (a <= l && b >= r) { lazy[node] |= val; lazy_update(node, l, r); return; } int mid = (l + r) / 2; update(2 * node + 1, l, mid, a, b, val); update(2 * node + 2, mid + 1, r, a, b, val); tree[node] = tree[2 * node + 1] & tree[2 * node + 2]; } int query(int node, int l, int r, int a, int b) { lazy_update(node, l, r); if (a > r || b < l) { return (1 << 30) - 1; } if (a <= l && b >= r) { return tree[node]; } int mid = (l + r) / 2; return query(2 * node + 1, l, mid, a, b) & query(2 * node + 2, mid + 1, r, a, b); } void print(int node, int l, int r) { lazy_update(node, l, r); cout << l << " " << r << ": " << tree[node] << endl; ; if (l != r) { int mid = (l + r) / 2; print(2 * node + 1, l, mid); print(2 * node + 2, mid + 1, r); } } int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d%d%d", &queries[i][0], &queries[i][1], &queries[i][2]); } init(0, 1, n); for (int i = 0; i < m; i++) { int a = queries[i][0]; int b = queries[i][1]; int c = queries[i][2]; update(0, 1, n, a, b, c); } for (int i = 0; i < m; i++) { int a = queries[i][0]; int b = queries[i][1]; int c = queries[i][2]; if (c != query(0, 1, n, a, b)) { cout << "NO" << endl; return 0; } } for (int i = 1; i <= n; i++) { arr[i] = query(0, 1, n, i, i); } cout << "YES" << endl; for (int i = 1; i <= n; i++) { cout << arr[i] << " "; } }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int n, m; const int len = 1e5 + 9; int a[len]; int b[len]; int c[len]; int freq[len]; int res[len]; int pt[31]; int last = (1 << 17); struct segmentTree { struct node { int value = 0; bool lazy = 0; }; node tree[1 << 18]; bool insert_(int l, int r, int now = 1, int st = 1, int ed = last) { if (st == ed) { tree[now].value = 1; return tree[now].value; } if (st >= l && ed <= r) { tree[now].lazy = 1; tree[now].value = 1; return tree[now].value; } int mid = (st + ed) / 2; if (tree[now].lazy != 0) { tree[now * 2].value = 1; tree[now * 2].lazy = 1; tree[now * 2 + 1].value = 1; tree[now * 2 + 1].lazy = 1; tree[now].lazy = 0; } if (l <= mid) { insert_(l, r, 2 * now, st, mid); } if (r > mid) { insert_(l, r, 2 * now + 1, mid + 1, ed); } tree[now].value = tree[now * 2].value && tree[now * 2 + 1].value; return tree[now].value; } int get_(int l, int r, int now = 1, int st = 1, int ed = last) { if (st == ed) { return tree[now].value; } if (st >= l && ed <= r) { return tree[now].value; } int mid = (st + ed) / 2; if (tree[now].lazy != 0) { tree[now * 2].value = 1; tree[now * 2].lazy = 1; tree[now * 2 + 1].value = 1; tree[now * 2 + 1].lazy = 1; tree[now].lazy = 0; } int res = 2147483647; if (l <= mid) { res = get_(l, r, 2 * now, st, mid) & res; } if (r > mid) { res = get_(l, r, 2 * now + 1, mid + 1, ed) & res; } return res; } void build() { for (int i = last; i < last * 2; i++) { tree[i].value = res[i - last + 1]; } for (int i = last - 1; i > 0; i--) { tree[i].value = tree[i * 2].value & tree[i * 2 + 1].value; } } }; segmentTree s; int main() { scanf("%d%d", &n, &m); pt[0] = 1; for (int i = 1; i < 31; i++) { pt[i] = (pt[i - 1] << 1); } for (int i = 0; i < m; i++) { scanf("%d%d%d", &a[i], &b[i], &c[i]); } for (int i = 0; i < 31; i++) { memset(freq, 0, sizeof freq); for (int j = 0; j < m; j++) { freq[a[j]] += (c[j] & pt[30 - i]) > 0; freq[b[j] + 1] -= (c[j] & pt[30 - i]) > 0; } int cou = 0; for (int j = 0; j < len; j++) { cou += freq[j]; res[j] += min(cou, 1) * pt[30 - i]; } } s.build(); for (int i = 0; i < m; i++) { if (s.get_(a[i], b[i]) != c[i]) { printf("NO\n"); return 0; } } printf("YES\n"); for (int i = 1; i <= n; i++) { printf("%d ", s.get_(i, i)); } }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; vector<pair<long long, pair<long long, long long> > > t; long long cnt[100002][32]; long long left_zero[100002][32]; vector<pair<long long, pair<long long, long long> > > ans; int main() { memset(cnt, 0, sizeof(cnt)); long long n, m; cin >> n >> m; for (long long i = 0; i < m; i++) { long long a, b, c; cin >> a >> b >> c; ans.push_back(make_pair(a, make_pair(b, c))); for (long long j = 0; j < 30; j++) { if (((c >> j) & 1) != 0) { cnt[a][j]++; cnt[b + 1][j]--; } } } for (long long i = 1; i <= n; i++) { for (long long j = 0; j < 30; j++) { cnt[i][j] += cnt[i - 1][j]; } } for (long long j = 0; j < 30; j++) { left_zero[0][j] = -1; } for (long long i = 1; i <= n; i++) { for (long long j = 0; j < 30; j++) { left_zero[i][j] = left_zero[i - 1][j]; if (cnt[i][j] == 0) { left_zero[i][j] = i; } } } long long valid = 1; for (long long i = 0; i < m; i++) { long long l = ans[i].first; long long r = ans[i].second.first; long long val = ans[i].second.second; for (long long j = 0; j < 30; j++) { if (((val >> j) & 1LL) == 0) { if (left_zero[r][j] == -1) { valid = 0; } else if (left_zero[r][j] < l) { valid = 0; } } else { if (left_zero[r][j] == -1) { continue; } else if (left_zero[r][j] >= l) { valid = 0; } } } } if (valid == 0) { cout << "NO\n"; } else { vector<long long> h; h.clear(); for (long long i = 1; i <= n; i++) { long long num = 0; for (long long j = 29; j >= 0; j--) { num = num * 2 + (cnt[i][j] > 0 ? 1 : 0); } if (num < (1LL << 30)) { h.push_back(num); } else { cout << "NO\n"; return 0; } } cout << "YES\n"; for (long long i = 0; i < h.size(); i++) { cout << h[i] << " "; } cout << "\n"; } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; import java.lang.*; import java.math.BigInteger; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; public class Main { static StringTokenizer st=new StringTokenizer(""); static BufferedReader br; static int n,m; /////////////////////////////////////////////////////////////////////////////////// public static void main(String args[]) throws FileNotFoundException, IOException, Exception { //Scanner in =new Scanner(new FileReader("input.txt")); //PrintWriter out = new PrintWriter(new FileWriter("output.txt")); //Scanner in=new Scanner(System.in); br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); //StringTokenizer st;//=new StringTokenizer(br.readLine()); ////////////////////////////////////////////////////////////////////////////////////// n=ni();m=ni(); int dat[][]=new int[n+1][30]; int l[]=new int[m]; int r[]=new int[m]; int q[]=new int[m]; for(int i=0;i<m;i++) { l[i]=ni()-1; r[i]=ni()-1; q[i]=ni(); for(int j=0;j<30;j++) { if(((1<<j)&q[i]) >0) { dat[l[i]][j]++; dat[r[i]+1][j]--; } } } int a[]=new int[n]; for(int i=0;i<30;i++) { for(int j=0;j<n;j++) { if(j>0)dat[j][i]+=dat[j-1][i]; if(dat[j][i]>0) a[j]+=1<<i; } } RMQ rmq=new RMQ(n); for(int i=0;i<n;i++) rmq.insert(i,a[i]); int n1; for(n1=1;n1<n;n1*=2); for(int i=0;i<m;i++) { if(q[i]!=(rmq.and(l[i], r[i]+1, 0, 0, n1))) { out.print("NO"); out.close(); return ; } } out.println("YES"); for(int i=0;i<n;i++) out.print(a[i]+" "); ////////////////////////////////////////////////////////////////////////////////////// out.close(); } static class RMQ { int INF=(1<<30)-1; int bit[]; int n1; RMQ(int n) { n1=1; for(;n1<n;n1*=2); bit=new int[2*n1-1]; for(int i=0;i<2*n1-1;i++) bit[i]=INF; } void insert(int i,int val) { i+=n1-1; bit[i]=val; while(i>0) { i=(i-1)/2; bit[i]=bit[2*i+1]&bit[2*i+2]; } } int and(int a,int b,int k,int l,int r) { if(r<=a || l>=b) return INF; if(l>=a && r<=b) return bit[k]; int v1=and(a,b,2*k+1,l,(l+r)/2); int v2=and(a,b,2*k+2,(l+r)/2,r); return v1&v2; } } static class BIT { private int c[]; BIT(int n){c=new int[n+1];} public int lowbit(int i) { return i&(i^(i-1)); } public int sum(int k) { int res=0; while(k>0) { res+=c[k]; k-=lowbit(k); } return res; } public void insert(int i,int v) { while(i<c.length) { c[i]+=v; i+=lowbit(i); } } } /////////////////////////////////////////////////////////////////////////////// private static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } private static class pair implements Comparable<pair> { int first; int second; pair() { first=0; second=0; } pair(int f,int s) { first=f; second=s; } public int compareTo(pair o) { if(first+second > o.first+o.second) return 1; else if(first+second < o.first+o.second) return -1; else return 0; } } public static Integer ni() throws Exception { if(!st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public static BigInteger nb()throws Exception { if(!st.hasMoreElements()) st=new StringTokenizer(br.readLine()); return BigInteger.valueOf(Long.parseLong(st.nextToken())); } public static Long nl() throws Exception { if(!st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public static Double nd()throws Exception { if(!st.hasMoreElements()) st=new StringTokenizer(br.readLine()); return Double.parseDouble(st.nextToken()); } public static String ns()throws Exception { if(!st.hasMoreElements()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Solution { static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //FastScanner s = new FastScanner(new File("input.txt")); copy inside void solve //PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); static FastScanner s = new FastScanner(); static PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String args[])throws IOException{ //Main ob=new Main(); Solution ob=new Solution(); ob.solve(); ww.close(); } ///////////////////////////////////////////// int tree[]; int dp[]; int arr[]; /* void build(int l,int r,int node){ if(l+1==r){ tree[node]=arr[l]; return; } int mid = (l+r)/2; build(l,mid,node*2); build(mid,r,node*2+1); tree[node]=tree[node*2]&tree[node*2+1]; } int query(int i,int j,int node,int l,int h){ if (i == l && j == h) { return tree[node]; } int mid = (l + h) >> 1; int ans = (1 << 30) - 1; if (l < mid) ans &= query(i, Math.min(j, mid),node*2, l, mid); if (mid < h) ans &= query(Math.max(i, mid),j, node*2+1, mid, h); return ans; } */ void build(int v, int l, int r) { if (l + 1 == r) { tree[v] = arr[l]; return; } int mid = (l + r) >> 1; build(v * 2, l, mid); build(v * 2 + 1, mid, r); tree[v] = tree[v * 2] & tree[v * 2 + 1]; } int query(int v, int l, int r, int L, int R) { if (l == L && r == R) { return tree[v]; } int mid = (L + R) >> 1; int ans = (1<< 30) - 1; if (l < mid) ans &= query(v * 2, l, Math.min(r, mid), L, mid); if (mid < r) ans &= query(v * 2 + 1, Math.max(l, mid), r, mid, R); return ans; } ///////////////////////////////////////////// void solve() throws IOException { int n = s.nextInt(); int m = s.nextInt(); int N=1000000; int l[] = new int[N]; int r[] = new int[N]; int q[] = new int[N]; for(int i = 0;i < m;i++){ l[i] = s.nextInt()-1; r[i] = s.nextInt(); q[i] = s.nextInt(); } dp = new int[N]; arr = new int[N]; int power = (int) Math.floor(Math.log(N) / Math.log(2)) + 1; power = (int) ((int) 2 * Math.pow(2, power)); tree = new int[power]; for(int bit = 0;bit <= 30;bit++){ for(int i=0;i<n;i++) dp[i]=0; for(int i=0;i<m;i++){ if (((q[i] >> bit) & 1)==1) { dp[l[i]]++; dp[r[i]]--; } } for(int i=0;i<n;i++){ if(i>0) dp[i]+= dp[i-1]; if(dp[i]>0) arr[i]|=(1<<bit); } } build(1,0,n); //for(int i=0;i<n;i++) //System.out.println(arr[i]+" "); for(int i=0;i<m;i++){ if (query(1, l[i], r[i], 0, n) != q[i]){ ww.println("NO"); return; } } ww.println("YES"); for(int i=0;i<n;i++) ww.print(arr[i]+" "); }//solve }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int maxn = 100000 + 10; int node[maxn * 4] = {}, ql, qr, qv, fg[maxn * 4] = {}; void update(int o, int l, int r) { if (l >= ql && r <= qr) { fg[o] |= qv; return; } int m = (l + r) >> 1; if (ql <= m) update(o << 1, l, m); if (qr > m) update((o << 1) + 1, m + 1, r); } int query(int o, int l, int r) { if (l >= ql && r <= qr) return fg[o]; else { fg[o << 1] |= fg[o]; fg[(o << 1) + 1] |= fg[o]; int m = (l + r) >> 1; int a = 2147483647; if (ql <= m) a &= query(o << 1, l, m); if (qr > m) a &= query((o << 1) + 1, m + 1, r); return a; } } void print(int o, int l, int r) { if (l > r) return; if (l == r) { printf("%d ", fg[o]); return; } fg[o << 1] |= fg[o]; fg[(o << 1) + 1] |= fg[o]; int m = (l + r) >> 1; print(o << 1, l, m); print((o << 1) + 1, m + 1, r); } int a[maxn][3], n, m; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { scanf("%d%d%d", &a[i][0], &a[i][1], &a[i][2]); ql = a[i][0], qr = a[i][1], qv = a[i][2]; update(1, 1, n); } for (int i = 0; i < m; ++i) { ql = a[i][0], qr = a[i][1]; if (query(1, 1, n) != a[i][2]) { puts("NO"); return 0; } } puts("YES"); print(1, 1, n); puts(""); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> int n, m, seg[300005], lazy[300005], d[200005], l[200005], r[200005], q[200005]; bool b = 1; void update(int root, int lo, int hi, int l, int r, int val) { if (lazy[root]) { seg[root] |= lazy[root]; if (lo ^ hi) { lazy[root * 2 + 1] |= lazy[root]; lazy[root * 2 + 2] |= lazy[root]; } lazy[root] = 0; } if (lo >= l && hi <= r) { seg[root] |= val; if (lo ^ hi) { lazy[root * 2 + 1] |= val; lazy[root * 2 + 2] |= val; } } else if (lo > r || hi < l) return; else { update(root * 2 + 1, lo, (lo + hi) / 2, l, r, val); update(root * 2 + 2, (lo + hi) / 2 + 1, hi, l, r, val); } } int query(int root, int lo, int hi, int l, int r) { if (lazy[root]) { seg[root] |= lazy[root]; if (lo ^ hi) { lazy[root * 2 + 1] |= lazy[root]; lazy[root * 2 + 2] |= lazy[root]; } lazy[root] = 0; } if (lo >= l && hi <= r) { if (lo == hi) d[lo] = seg[root]; return seg[root]; } else if (lo > r || l > hi) return -1; else return query(root * 2 + 1, lo, (lo + hi) / 2, l, r) & query(root * 2 + 2, (lo + hi) / 2 + 1, hi, l, r); } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d%d%d", l + i, r + i, q + i); update(0, 0, n - 1, l[i] - 1, r[i] - 1, q[i]); } for (int i = 0; i < m && b; i++) b = query(0, 0, n - 1, l[i] - 1, r[i] - 1) == q[i]; if (b) { printf("YES\n"); for (int i = 0; i < n; i++) printf("%d%c", d[i] ? d[i] : query(0, 0, n - 1, i, i), i + 1 < n ? 32 : 10); } else printf("NO\n"); }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) dp = [[0]*30 for _ in range(n+2)] op = [] for _ in range(m): op.append(tuple(map(int,input().split()))) l,r,q = op[-1] mask,cou = 1,29 while mask <= q: if mask&q: dp[l][cou] += 1 dp[r+1][cou] -= 1 cou -= 1 mask <<= 1 ans = [[0]*30 for _ in range(n)] for i in range(30): a = 0 for j in range(n): a += dp[j+1][i] dp[j+1][i] = dp[j][i] if a: ans[j][i] = 1 dp[j+1][i] += 1 for i in op: l,r,q = i mask = 1 for cou in range(29,-1,-1): if not mask&q and dp[r][cou]-dp[l-1][cou] == r-l+1: print('NO') return mask <<= 1 for i in range(n): ans[i] = int(''.join(map(str,ans[i])),2) print('YES') print(*ans) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
PYTHON3
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public final class interesting_array { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int[][] arr; static int[] a,tree,sum; static void build(int node,int s,int e) { if(s>e) { return; } if(s==e) { tree[node]=a[s]; } else { int mid=(s+e)>>1; build(node<<1,s,mid);build(node<<1|1,mid+1,e); tree[node]=tree[node<<1]&tree[node<<1|1]; } } static int query(int node,int s,int e,int l,int r) { if(s>e || l>e || r<s) { return -1; } if(l<=s && r>=e) { return tree[node]; } else { int mid=(s+e)>>1; int val1=query(node<<1,s,mid,l,r),val2=query(node<<1|1,mid+1,e,l,r); if(val1==-1 && val2==-1) { return 0; } if(val1==-1 || val2==-1) { return Math.max(val1,val2); } return (val1&val2); } } public static void main(String args[]) throws Exception { int n=sc.nextInt(),m=sc.nextInt();arr=new int[n+1][31];Query[] q=new Query[m]; for(int i=0;i<m;i++) { int l=sc.nextInt()-1,r=sc.nextInt()-1,val=sc.nextInt();q[i]=new Query(l,r,val); for(int j=0;j<=30;j++) { if((val&(1<<j))!=0) { arr[l][j]++;arr[r+1][j]--; } } } a=new int[n];sum=new int[31]; for(int i=0;i<n;i++) { for(int j=0;j<=30;j++) { sum[j]+=arr[i][j]; } for(int j=0;j<=30;j++) { if(sum[j]>0) { a[i]|=(1<<j); } } } tree=new int[4*n];boolean ans=true;build(1,0,n-1); for(int i=0;i<m;i++) { int now=query(1,0,n-1,q[i].l,q[i].r); if(now!=q[i].val) { ans=false;break; } } if(ans) { out.println("YES"); for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(""); } else { out.println("NO"); } out.close(); } } class Query { int l,r,val; public Query(int l,int r,int val) { this.l=l;this.r=r;this.val=val; } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; ifstream fin("in.in"); ofstream fout("out.out"); const int N = 1e5 + 10; long long n, m, a[N], bit[N][40], pw[40], node[N << 2], s[40], l[N], r[N], x[N]; void buildTree(int s, int e, int tag) { if (s + 1 == e) { node[tag] = a[s]; return; } int mid = (s + e) >> 1; buildTree(s, mid, tag * 2); buildTree(mid, e, tag * 2 + 1); node[tag] = (node[tag * 2] & node[tag * 2 + 1]); } long long getAnd(int s, int e, int tag, int l, int r) { if (s >= r || e <= l) return pw[30] - 1; if (s >= l && e <= r) return node[tag]; int mid = (s + e) >> 1; return (getAnd(s, mid, tag * 2, l, r) & getAnd(mid, e, tag * 2 + 1, l, r)); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); pw[0] = 1; for (int i = 1; i <= 30; i++) pw[i] = pw[i - 1] << 1; cin >> n >> m; for (int i = 0; i < m; i++) { cin >> l[i] >> r[i] >> x[i]; l[i]--; for (int j = 0; j < 30; j++) { bit[l[i]][j] += (x[i] & pw[j]); bit[r[i]][j] -= (x[i] & pw[j]); } } for (int i = 0; i < n; i++) for (int j = 0; j < 30; j++) { s[j] += bit[i][j]; if (s[j]) a[i] |= pw[j]; } buildTree(0, n, 1); for (int i = 0; i < m; i++) if (getAnd(0, n, 1, l[i], r[i]) != x[i]) return (cout << "NO"), 0; cout << "YES" << endl; for (int i = 0; i < n; i++) cout << a[i] << ' '; return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; class Fenwick { public: Fenwick(int size) { storage.resize(size + 1); n = size; } void update(int i, int val) { for (; i <= n; i += i & -i) storage[i] += val; } int sum(int i) { int result = 0; for (; i > 0; i -= i & -i) result += storage[i]; return result; } private: vector<int> storage; int n; }; void update(vector<int> &count, int val, int type, int &curr) { for (int i = 0; i < 30; i++) { bool bit = (val >> i) & 1; if (bit == 0) continue; if (type == 0) { if (count[i] == 0) curr |= 1 << i; count[i]++; } else { if (count[i] == 1) curr ^= 1 << i; count[i]--; } } } int main() { int n, m; cin >> n >> m; vector<vector<int>> segments; vector<vector<int>> info; vector<int> count(30); vector<int> a(n + 1); for (int i = 0; i < m; i++) { int l, r, val; scanf("%d %d %d", &l, &r, &val); segments.push_back(vector<int>{l, val, 0}); segments.push_back(vector<int>{r + 1, val, 1}); info.push_back(vector<int>{l, r, val}); } sort(segments.begin(), segments.end()); deque<vector<int>> Q(segments.begin(), segments.end()); sort(info.begin(), info.end()); int curr = 0; for (int i = 1; i <= n; i++) { while (!Q.empty() and (Q.front())[0] == i) { vector<int> temp = Q.front(); Q.pop_front(); update(count, temp[1], temp[2], curr); } a[i] = curr; } vector<Fenwick> F(30, Fenwick(n)); for (int i = 1; i <= n; i++) { for (int j = 0; j < 30; j++) F[j].update(i, (a[i] >> j) & 1); } Q.clear(); Q.assign(info.begin(), info.end()); for (int i = 1; i <= n; i++) { while (!Q.empty() and (Q.front())[0] == i) { int val = 0; vector<int> temp = Q.front(); Q.pop_front(); for (int j = 0; j < 30; j++) { int valid = F[j].sum(temp[1]); if (valid == temp[1] - temp[0] + 1) val |= 1 << j; } if (val != temp[2]) { cout << "NO" << endl; return 0; } } for (int j = 0; j < 30; j++) F[j].update(i, ((a[i] >> j) & 1) == 1 ? -1 : 0); } cout << "YES" << endl; for (int i = 1; i <= n; i++) { printf("%d", a[i]); printf(i != n ? " " : "\n"); } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; public class Solution { static class FastScanner{ BufferedReader s; StringTokenizer st; public FastScanner(){ st = new StringTokenizer(""); s = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(File f) throws FileNotFoundException{ st = new StringTokenizer(""); s = new BufferedReader (new FileReader(f)); } public int nextInt() throws IOException{ if(st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextInt(); } } public double nextDouble() throws IOException{ if(st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextDouble(); } } public long nextLong() throws IOException{ if(st.hasMoreTokens()) return Long.parseLong(st.nextToken()); else{ st = new StringTokenizer(s.readLine()); return nextLong(); } } public String nextString() throws IOException{ if(st.hasMoreTokens()) return st.nextToken(); else{ st = new StringTokenizer(s.readLine()); return nextString(); } } public String readLine() throws IOException{ return s.readLine(); } public void close() throws IOException{ s.close(); } } //FastScanner s = new FastScanner(new File("input.txt")); copy inside void solve //PrintWriter ww = new PrintWriter(new FileWriter("output.txt")); static FastScanner s = new FastScanner(); static PrintWriter ww = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String args[])throws IOException{ //Main ob=new Main(); Solution ob=new Solution(); ob.solve(); ww.close(); } ///////////////////////////////////////////// int tree[]; int dp[]; int arr[]; void build(int node,int l,int r){ if(l == r){ tree[node]=arr[l]; return; } int mid = (l+r)/2; build(node*2,l,mid); build(node*2+1,mid+1,r); tree[node]=tree[node*2]&tree[node*2+1]; } int query(int node,int l,int r,int L,int R){ if (L >= l && R <= r) { return tree[node]; } else if(r < L || l > R) return (1 << 30) - 1; int mid = (L + R) >> 1; int ans = (1 << 30) - 1; ans &= query(node*2,l, r, L, mid); ans &= query(node*2+1,l,r, mid+1, R); return ans; } ///////////////////////////////////////////// void solve() throws IOException { int n = s.nextInt(); int m = s.nextInt(); int N=1000000; int l[] = new int[N]; int r[] = new int[N]; int q[] = new int[N]; for(int i = 0;i < m;i++){ l[i] = s.nextInt()-1; r[i] = s.nextInt(); q[i] = s.nextInt(); } dp = new int[N]; arr = new int[N]; int power = (int) Math.floor(Math.log(N) / Math.log(2)) + 1; power = (int) ((int) 2 * Math.pow(2, power)); tree = new int[power]; for(int bit = 0;bit <= 30;bit++){ for(int i=0;i<n;i++) dp[i]=0; for(int i=0;i<m;i++){ if (((q[i] >> bit) & 1)==1) { dp[l[i]]++; dp[r[i]]--; } } for(int i=0;i<n;i++){ if(i>0) dp[i]+= dp[i-1]; if(dp[i]>0) arr[i]|=(1<<bit); } } build(1,0,n-1); for(int i=0;i<m;i++){ if (query(1, l[i], r[i]-1, 0, n-1) != q[i]){ ww.println("NO"); return; } } ww.println("YES"); for(int i=0;i<n;i++) ww.print(arr[i]+" "); }//solve }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(in, out); out.close(); } } class Solver { int n; int m; int[] l; int[] r; int[] need; int[] answer; int[] minEndZero; int[] add; int[] value; public void solve(InputReader in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); l = new int[m]; r = new int[m]; need = new int[m]; for (int i = 0; i < m; i++) { l[i] = in.nextInt() - 1; r[i] = in.nextInt() - 1; need[i] = in.nextInt(); } answer = new int[n]; minEndZero = new int[n]; add = new int[n + 1]; value = new int[n]; for (int lvl = 0; lvl < 30; lvl++) { Arrays.fill(add, 0); Arrays.fill(minEndZero, Integer.MAX_VALUE); Arrays.fill(value, 0); for (int i = 0; i < m; i++) { int L = l[i]; int R = r[i]; int bit = (need[i] >> lvl) & 1; if (bit == 1) { add[L]++; add[R + 1]--; } else { minEndZero[L] = Math.min(minEndZero[L], R); } } int cur = 0; boolean needZero = false; int mini = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { cur += add[i]; if (minEndZero[i] != Integer.MAX_VALUE) { needZero = true; mini = Math.min(mini, minEndZero[i]); } if (cur > 0) { value[i] = 1; } else if (needZero) { needZero = false; mini = Integer.MAX_VALUE; } if (needZero && mini <= i) { out.println("NO"); return; } } for (int i = 0; i < n; i++) { answer[i] |= (value[i] << lvl); } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(answer[i] + " "); } out.println(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; // this is not good for reading double values. public class Problem482B { static long m = 100000007; static long[] a; public static void main(String[] args) throws IOException { Reader r = new Reader(); PrintWriter o = new PrintWriter(System.out, false); int n = r.nextInt(); int m = r.nextInt(); int[] L, R; long[] q; L = new int[m]; R = new int[m]; q = new long[m]; for (int i = 0; i < m; i++) { L[i] = r.nextInt() - 1; R[i] = r.nextInt(); q[i] = r.nextInt(); } a = new long[n]; for (int bit = 0; bit <= 30; bit++) { long[] sum = new long[n + 1]; for (int i = 0; i < m; i++) { if ((q[i] & (1 << bit)) != 0) { sum[L[i]]++; sum[R[i]]--; } } for (int i = 0; i < n; i++) { if (i > 0) { sum[i] += sum[i - 1]; } if (sum[i] > 0) { a[i] |= (1 << bit); } } } segmentTree st = new segmentTree(0, n - 1); for (int i = 0; i < m; i++) { if (st.query(L[i], R[i] - 1) != q[i]) { o.println("NO"); // System.out.println(L[i]+" "+(R[i]-1)+" "+st.query(L[i], R[i]-1) + " " + q[i]); o.close(); return; } } o.println("YES"); for (int i = 0; i < n; i++) { o.print(a[i] + " "); } o.close(); } static class segmentTree { segmentTree left, right; long data, and; int from, to; public segmentTree(int from, int to) { this.from = from; this.to = to; if (from == to) { and = a[from]; // System.out.println(from + " " + to + " " + and); } else { int mid = (from + to) / 2; left = new segmentTree(from, mid); right = new segmentTree(mid + 1, to); and = left.and & right.and; // System.out.println(from + " " + to + " " + and); } } long query(int L, int R) { if (L <= from && to <= R) { return and; } else if (to < L || R < from) { return Integer.MAX_VALUE; } else { long sumL = left.query(L, R); long sumR = right.query(L, R); // System.out.println(sumL+" "+sumR); return (sumL & sumR); } } } static 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 final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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; } public int[] readIntArray(int size) throws IOException { int[] arr = new int[size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } public long[] readLongArray(int size) throws IOException { long[] arr = new long[size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } 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(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class B_Round_275_Div1 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int m = in.nextInt(); End[] data = new End[m]; P[] ps = new P[2 * m]; int index = 0; for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; int v = in.nextInt(); data[i] = new End(a, b, v); ps[index++] = new P(a, b, v, true); ps[index++] = new P(b, a, v, false); } Arrays.sort(ps, new Comparator<P>() { @Override public int compare(P o1, P o2) { if (o1.p != o2.p) { return o1.p - o2.p; } else { if (o1.open && !o2.open) { return -1; } else if (o2.open && !o1.open) { return 1; } return 0; } } }); int[] result = new int[n]; End[] tmp = new End[m]; boolean ok = true; for (int i = 0; i < 31 && ok; i++) { int count = 0; int last = -1; int end = -1; int prev = -1; for (P p : ps) { if (p.open) { if (((1 << i) & p.v) != 0) { count++; if (last == -1) { last = p.p; } } } else { if (((1 << i) & p.v) != 0) { count--; if (count == 0) { for(int j = last; j <= p.p; j++){ result[j] |= (1<<i); } prev = last; end = p.p; last = -1; } }else{ //System.out.println(count + " "+ p.p + " -- " + last + " " + prev + " " + end + " " + i); if(count > 0 || end == p.p){ if(last != -1 && last <= p.o){ ok = false; break; }else if(end ==p.p && prev <= p.o){ ok = false; break; } } } } } } if (ok) { out.println("YES"); for (int i : result) { out.print(i + " "); } } else { out.println("NO"); } out.close(); } static class P { int p, o, v; boolean open; public P(int p, int o, int v, boolean open) { this.p = p; this.o = o; this.v = v; this.open = open; } } static class End { int s, e, v; public End(int s, int e, int v) { this.s = s; this.e = e; this.v = v; } } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; public class Main { public static void main(String[] args){ new CF482B().solve() ; } } class CF482B{ InputReader in = new InputReader(System.in) ; PrintWriter out = new PrintWriter(System.out) ; void solve(){ int n = in.nextInt() ; int m = in.nextInt() ; build(1 , 1 , n) ; for(int i = 1 ; i <= m ; i++){ l[i] = in.nextInt() ; r[i] = in.nextInt() ; q[i] = in.nextInt() ; update(l[i] , r[i] , q[i] , 1 , 1, n) ; } boolean can = true ; for(int i = 1 ; i <= m ; i++){ if(query(l[i] , r[i] , 1 , 1 , n) != q[i]){ can = false ; break ; } } if(can){ out.println("YES") ; for(int i = 1 ; i <= n ; i++){ if(i > 1) out.print(" ") ; out.print(query(i , i , 1 , 1 , n)) ; } out.println() ; } else out.println("NO") ; out.flush() ; } final int N = 100008 ; int[] sum = new int[N<<2] ; int[] add = new int[N<<2] ; int[] l = new int[N] ; int[] r = new int[N] ; int[] q = new int[N] ; void build(int t , int l , int r){ sum[t] = add[t] = 0 ; if(l == r) return ; int mid = (l + r) >> 1 ; build(t<<1 , l , mid) ; build(t<<1|1 , mid+1 , r) ; up(t) ; } void up(int t){ sum[t] = sum[t<<1] & sum[t<<1|1] ; } void down(int t){ if(add[t] != 0){ sum[t<<1] |= add[t] ; sum[t<<1|1] |= add[t] ; add[t<<1] |= add[t] ; add[t<<1|1] |= add[t] ; add[t] = 0 ; } } void update(int L , int R , int v , int t , int l , int r){ if(L <= l && r <= R){ add[t] |= v ; sum[t] |= v ; return ; } down(t) ; int mid = (l + r) >> 1 ; if(L <= mid) update(L, R, v , t<<1 , l , mid) ; if(R > mid) update(L , R , v , t<<1|1 , mid+1 , r) ; up(t) ; } int query(int L , int R , int t , int l , int r){ if(L <= l && r <= R) return sum[t] ; int res = (1<<30) - 1 ; down(t) ; int mid = (l + r) >> 1 ; if(L <= mid) res &= query(L, R, t<<1 , l , mid) ; if(R > mid) res &= query(L, R, t<<1|1 , mid+1 , r) ; up(t) ; return res ; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = new StringTokenizer(""); } private void eat(String s) { tokenizer = new StringTokenizer(s); } public String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String s = nextLine(); if (s == null) return false; eat(s); } return true; } public String next() { hasNext(); 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 BigInteger nextBigInteger() { return new BigInteger(next()); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class D { class IntervalTree { int[] d; int neutral; boolean and; int cnt = 0; int n; public IntervalTree(int n, boolean and) { this.and = and; neutral = and ? Integer.MAX_VALUE : 0; d = new int[n * 4]; this.n = n; Arrays.fill(d, neutral); } void add(int x) { set(x, cnt++, 0, n, 0); } void remove(int id) { set(neutral, id, 0, n, 0); } int set(int x, int ind, int L, int R, int i) { if (ind < L || R <= ind) return d[i]; if (L == R - 1) { d[i] = x; return d[i]; } int M = (R + L) / 2; int res = set(x, ind, L, M, 2 * i + 1); if (and) res &= set(x, ind, M, R, 2 * i + 2); else res |= set(x, ind, M, R, 2 * i + 2); d[i] = res; return d[i]; } int get(int l, int r, int L, int R, int i) { if (R <= l || r <= L) return neutral; if (l <= L && R <= r) return d[i]; int M = (R + L) / 2; if (and) return get(l, r, L, M, 2 * i + 1) & get(l, r, M, R, 2 * i + 2); else return get(l, r, L, M, 2 * i + 1) | get(l, r, M, R, 2 * i + 2); } } class Interval { int l, r, q; Interval(int l, int r, int q) { this.l = l; this.r = r; this.q = q; } } class Event implements Comparable<Event> { int coord, q, itid; Event pair; Event(int coord, int id, boolean begin, int q) { this.coord = coord; this.id = id; this.begin = begin; this.q = q; } int id; boolean begin; @Override public int compareTo(Event o) { if (this.coord != o.coord) return this.coord - o.coord; if (!this.begin && o.begin) return 1; if (begin && !o.begin) return -1; if (this.id != o.id) return id - o.id; return 0; } } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new D().run(); } public void solve() throws IOException { int n = nextInt(); int m = nextInt(); Event[] events = new Event[m << 1]; Interval[] intervals = new Interval[m]; for (int i = 0; i < m; ++i) { int l = nextInt() - 1; int r = nextInt() - 1; int q = nextInt(); intervals[i] = new Interval(l, r, q); events[i * 2] = new Event(l, i, true, q); events[(i * 2) + 1] = new Event(r, i, false, q); events[i * 2].pair = events[(i * 2) + 1]; events[(i * 2) + 1].pair = events[i * 2]; } Arrays.sort(events); int[] a = new int[n]; int cnt = 0; IntervalTree it = new IntervalTree(m, false); TreeSet<Event> ts = new TreeSet<Event>(new Comparator<Event>() { @Override public int compare(Event o1, Event o2) { if (o1.q != o2.q) return o1.q - o2.q; return o1.id - o2.id; } }); for (int i = 0; i < n; ++i) { while (cnt < (m * 2) && events[cnt].coord == i && events[cnt].begin) { it.add(events[cnt].q); ts.add(events[cnt]); events[cnt].itid = it.cnt - 1; ++cnt; } a[i] = ts.size() == 0 ? 239 : it.get(0, m, 0, m, 0); while (cnt < (m * 2) && events[cnt].coord == i) { it.remove(events[cnt].pair.itid); ts.remove(events[cnt].pair); ++cnt; } } IntervalTree it1 = new IntervalTree(n, true); for (int i = 0; i < n; ++i) it1.add(a[i]); for (int i = 0; i < m; ++i) if (intervals[i].q != it1.get(intervals[i].l, intervals[i].r + 1, 0, n, 0)) { out.print("NO"); return; } out.println("YES"); for (int i : a) { out.print(i + " "); } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ while (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } BIT []bit; SegmentTree tree; public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(), q = nextInt(); bit = new BIT[30]; for(int i = 0; i < 30; ++i) bit[i] = new BIT(n + 1); int []l = new int[q]; int []r = new int[q]; int []v = new int[q]; for(int i = 0;i < q; ++i) { l[i] = nextInt(); r[i] = nextInt(); v[i] = nextInt(); for(int j = 0; j < 30; ++j){ if ((v[i] & (1 << j)) > 0){ bit[j].update(l[i], 1); bit[j].update(r[i]+1, -1); } } } int []a = new int[n]; for(int i = 1; i <= n; ++i){ for(int j = 0; j < 30; ++j){ int b = bit[j].sum(i); if (b > 0) a[i-1]|=1<<j; } } //System.out.println(Arrays.toString(a)); tree = new SegmentTree(a); for(int i = 0; i < q; ++i){ int tv = tree.get(1, 0, n-1, l[i]-1, r[i]-1); if (tv != v[i]){ out.println("NO"); out.close(); return; } } out.println("YES"); for(int i = 0; i < n; ++i){ out.print(a[i] + " "); } out.println(); out.close(); } class BIT{ int []tree; public BIT(int n){ tree = new int[n+1]; } public void update(int x, int d){ while(x < tree.length){ tree[x]+=d; x+=x&-x; } } public int sum(int x){ int r = 0; while(x > 0){ r+=tree[x]; x-=x&-x; } return r; } } final static int ONES = (1 << 31) - 1; class SegmentTree{ int []tree; int n; public SegmentTree(int []a){ n = a.length; int N = Integer.highestOneBit(n) << 2; tree = new int[N]; build(1, 0, n-1, a); } private void build(int v, int tl, int tr, int a[]){ if (tl == tr){ tree[v] = a[tl]; return; } int tm = (tl + tr) / 2; build(2 * v, tl ,tm, a); build(2 * v + 1, tm + 1, tr, a); tree[v] = tree[2*v] & tree[2*v+1]; } public int get(int v, int tl, int tr, int l, int r){ if (l > r) return ONES; if (tl == l && tr == r){ return tree[v]; } int tm = (tl + tr) / 2; int left = get(2*v, tl, tm, l, Math.min(tm, r)); int right = get(2*v+1, tm+1, tr, Math.max(l, tm+1), r); return left & right; } } public static void main(String args[]) throws Exception{ new Main().run(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; vector<int> sTree; void build(int left, int right, int ind, vector<int> &arr) { if (left == right) { sTree[ind] = arr[left]; return; } int lTree = ind * 2, rTree = lTree + 1; int mid = (left + right) / 2; build(left, mid, lTree, arr); build(mid + 1, right, rTree, arr); sTree[ind] = sTree[lTree] & sTree[rTree]; } long long int query(int left, int right, int L, int R, int ind, vector<int> &arr) { if (L >= left && R <= right) return (long long int)sTree[ind]; if (R < left || L > right) return ((1ll << 31) - 1); int mid = (L + R) / 2; long long int lVal = query(left, right, L, mid, ind * 2, arr), rVal = query(left, right, mid + 1, R, ind * 2 + 1, arr); long long int ans = lVal & rVal; return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n, m, i, j; cin >> n >> m; sTree.resize(4 * n); vector<int> l(m), r(m), q(m); for (i = 0; i < m; i++) { cin >> l[i] >> r[i] >> q[i]; l[i]--; } vector<int> sum(n + 1), a(n); for (i = 0; i < n; i++) { a[i] = 0; } for (int bit = 0; bit <= 30; bit++) { for (i = 0; i <= n; i++) { sum[i] = 0; } for (i = 0; i < m; i++) { if ((q[i] >> bit) % 2) { sum[l[i]]++; sum[r[i]]--; } } for (i = 1; i <= n; i++) { sum[i] += sum[i - 1]; } for (i = 0; i < n; i++) { if (sum[i] > 0) { a[i] |= 1 << bit; } } } build(0, n - 1, 1, a); for (i = 0; i < m; i++) { if (query(l[i], r[i] - 1, 0, n - 1, 1, a) != q[i]) { cout << "NO" << endl; return 0; } } cout << "YES" << endl; for (i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.StringTokenizer; import java.util.stream.Stream; public class CP implements Runnable { static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new CP(), "persefone", 1 << 28).start(); } @Override public void run() { solve(); printf(); close(); } void solve() { int n = in.nextInt(); int m = in.nextInt(); int[][] f = new int[n + 2][31]; Query[] queries = new Query[m]; for (int k = 0; k < m; k++) { int l = in.nextInt(); int r = in.nextInt(); int q = in.nextInt(); int[] bit = new int[31]; for (int i = 0; i < 31; i++) { if ((q & (1 << i)) > 0) { f[l][i]++; f[r + 1][i]--; bit[i] = 1; } } queries[k] = new Query(l, r, bit); } for (int i = 1; i <= n; i++) for (int j = 0; j < 31; j++) f[i][j] += f[i - 1][j]; for (int i = 1; i <= n; i++) for (int j = 0; j < 31; j++) if (f[i][j] > 0) f[i][j] = 1; for (int i = 1; i <= n; i++) for (int j = 0; j < 31; j++) f[i][j] += f[i - 1][j]; for (int k = 0; k < m; k++) { int l = queries[k].left; int r = queries[k].right; int[] bit = queries[k].bit; int mi = r - l + 1; for (int i = 0; i < 31; i++) { int ma = f[r][i] - f[l - 1][i]; if (bit[i] == 1 && mi != ma || (bit[i] == 0 && mi == ma)) { printf("NO"); return; } } } printf("YES"); for (int i = 1; i <= n; i++) { int x = 0; for (int j = 0; j < 31; j++) x += f[i][j] - f[i - 1][j] << j; add(x, ' '); } } static class Query { private int left, right; private int[] bit = new int[30]; public Query(int left, int right, int[] bit) { this.left = left; this.right = right; this.bit = bit; } } void printf() { out.print(answer); } void close() { out.close(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int n, q, l[1010000], r[1010000], a[1010000], ans, L, R, A; struct node { int f, w; } tree[1010000 * 4]; template <typename T> void read(T &x) { x = 0; char c = getchar(); int f = 1; for (; !isdigit(c); c = getchar()) if (c == '-') f = -1; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } void pushdown(int k) { tree[k * 2].f |= tree[k].f; tree[k * 2 + 1].f |= tree[k].f; tree[k * 2].w |= tree[k].f; tree[k * 2 + 1].w |= tree[k].f; tree[k].f = 0; } void add(int k, int t, int w) { if (L <= t && w <= R) { tree[k].f |= A; tree[k].w |= A; return; } int mid = (t + w) >> 1; if (tree[k].f) pushdown(k); if (L <= mid) add(k * 2, t, mid); if (R > mid) add(k * 2 + 1, mid + 1, w); tree[k].w = tree[k * 2].w & tree[k * 2 + 1].w; } void ask(int k, int t, int w) { if (L <= t & w <= R) { ans &= tree[k].w; return; } int mid = (t + w) >> 1; if (tree[k].f) pushdown(k); if (L <= mid) ask(k * 2, t, mid); if (R > mid) ask(k * 2 + 1, mid + 1, w); } int main() { read(n), read(q); for (int i = 1; i <= q; i++) { read(l[i]), read(r[i]), read(a[i]); L = l[i], R = r[i], A = a[i]; add(1, 1, n); } int Flag = 1; for (int i = 1; i <= q; i++) { ans = (1 >> 31) - 1; L = l[i], R = r[i]; ask(1, 1, n); if (ans != a[i]) Flag = 0; } if (Flag) { printf("YES\n"); for (int i = 1; i <= n; i++) { ans = (1 >> 31) - 1; L = i, R = i; ask(1, 1, n); printf("%d ", ans); } } else printf("NO\n"); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; public class D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.readInt(); int m = in.readInt(); int[] E = new int[n]; int[] L = new int[m]; int[] R = new int[m]; int[] Q = new int[m]; int[][] A = new int[n][32]; int[][] D = new int[n][32]; for (int i = 0; i < m; i++) { L[i] = in.readInt() - 1; R[i] = in.readInt() - 1; Q[i] = in.readInt(); for (int j = 0; j < 32; j++) if ((Q[i] & (1 << j)) != 0) { A[L[i]][j]++; D[R[i]][j]++; } } int[] c = new int[32]; for (int i = 0; i < n; i++) { for (int j = 0; j < 32; j++) { c[j] += A[i][j]; if (c[j] > 0) E[i] |= 1 << j; } for (int j = 0; j < 32; j++) c[j] -= D[i][j]; } int size = 0; while ((1 << size) <= n) size++; int[][] W = new int[n][size]; for (int i = 0; i < n; i++) W[i][0] = E[i]; for (int i = 1; i < size; i++) for (int j = 0; j < n; j++) { int next = j + (1 << (i - 1)); W[j][i] = W[j][i - 1]; if (next < n) W[j][i] &= W[next][i - 1]; } boolean valid = true; for (int i = 0; i < m && valid; i++) { int diff = R[i] - L[i] + 1; int ans = -1; for (int j = 0; j < 32; j++) if ((diff & (1 << j)) != 0) { ans &= W[L[i]][j]; L[i] += 1 << j; } valid &= ans == Q[i]; } if (valid) { out.println("YES"); for (int i = 0; i < n; i++) out.print(E[i] + " "); out.println(); } else out.println("NO"); out.flush(); out.close(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1000]; private int curChar, numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; template <class TValue, class TDelta> struct SegmentTree { public: int sz; TValue *t; TDelta *d; const bool rangeUpdates; const TValue neutralValue; const TDelta neutralDelta; const function<TValue(TValue const &, TValue const &)> combineValues; const function<TDelta(TDelta const &, TDelta const &, int)> combineDeltas; const function<TValue(TValue const &, TDelta const &, int)> combineValueAndDelta; void Push(int v, int len) { d[v * 2 + 1] = combineDeltas(d[v * 2 + 1], d[v], len); d[v * 2 + 2] = combineDeltas(d[v * 2 + 2], d[v], len); d[v] = neutralDelta; } SegmentTree( int sz, function<TValue(TValue const &, TValue const &)> combineValues, bool rangeUpdates = false, TValue neutralValue = TValue(), TDelta neutralDelta = TDelta(), TValue *source = nullptr, function<TValue(TValue const &, TDelta const &, int)> combineValueAndDelta = function<TValue(TValue const &, TDelta const &, int)>(), function<TDelta(TDelta const &, TDelta const &, int)> combineDeltas = function<TDelta(TDelta const &, TDelta const &, int)>()) : sz(sz), t(new TValue[sz * 4]), d(nullptr), rangeUpdates(rangeUpdates), neutralValue(neutralValue), neutralDelta(neutralDelta), combineValues(combineValues), combineDeltas(combineDeltas), combineValueAndDelta(combineValueAndDelta) { if (rangeUpdates && !combineValueAndDelta) { exit(123); } if (rangeUpdates && !combineDeltas) { exit(123); } if (!combineValues) { exit(123); } if (rangeUpdates) { d = new TDelta[sz * 4]; for (int i = 0; i < sz * 4; i++) { d[i] = neutralDelta; } } if (source) { Build(0, 0, sz, source); } else { for (int i = 0; i < sz * 4; i++) { t[i] = neutralValue; } } } template <class L> void Build(int v, int tl, int tr, L src) { if (tr == tl + 1) { t[v] = src[tl]; if (rangeUpdates) { d[v] = neutralDelta; } return; } int tm = (tl + tr) / 2; Build(v * 2 + 1, tl, tm, src); Build(v * 2 + 2, tm, tr, src); t[v] = combineValues(t[v * 2 + 1], t[v * 2 + 2]); } TValue Get(int l, int r) { return GetImpl(0, 0, sz, l, r); } void Update(int l, int r, int val) { if (!rangeUpdates) { exit(123); } Update(0, 0, sz, l, r, val); } private: TValue GetImpl(int v, int tl, int tr, int l, int r) { if (l >= r) { return neutralValue; } if (l == tl && r == tr) { if (rangeUpdates) { return combineValueAndDelta(t[v], d[v], 0); } else { return t[v]; } } Push(v, r - l); int tm = (tl + tr) / 2; TValue ret = combineValues(GetImpl(v * 2 + 1, tl, tm, l, std::min(r, tm)), GetImpl(v * 2 + 2, tm, tr, std::max(l, tm), r)); if (rangeUpdates) { TValue a = combineValueAndDelta(t[v * 2 + 1], d[v * 2 + 1], tm - tl); TValue b = combineValueAndDelta(t[v * 2 + 2], d[v * 2 + 2], tr - tm); t[v] = combineValues(a, b); } else { t[v] = combineValues(t[v * 2 + 1], t[v * 2 + 2]); } return ret; } void Update(int v, int tl, int tr, int l, int r, TDelta const &delta) { if (l >= r) { return; } if (l == tl && r == tr) { d[v] = combineDeltas(d[v], delta, r - l); return; } Push(v, r - l); int tm = (tl + tr) / 2; Update(v * 2 + 1, tl, tm, l, std::min(r, tm), delta); Update(v * 2 + 2, tm, tr, std::max(l, tm), r, delta); TValue a = combineValueAndDelta(t[v * 2 + 1], d[v * 2 + 1], tm - tl); TValue b = combineValueAndDelta(t[v * 2 + 2], d[v * 2 + 2], tr - tm); t[v] = combineValues(a, b); } }; class Solution { public: void solve(std::istream &in, std::ostream &out) { int n, m; in >> n >> m; auto intAnd = [](int a, int b, int l = 0) { return a & b; }; auto intOr = [](int a, int b, int l) { return a | b; }; int *ar = new int[n]; memset(ar, 0, sizeof(int) * n); SegmentTree<int, int> st(n, intAnd, true, (1 << 30) - 1, 0, ar, intOr, intOr); vector<tuple<int, int, int>> queries; for (int i = 0; i < m; i++) { int l, r, v; in >> l >> r >> v; l--; queries.emplace_back(l, r, v); st.Update(l, r, v); } bool ok = true; for (auto &q : queries) { int l, r, v; tie(l, r, v) = q; int x = st.Get(l, r); if (v != x) { ok = false; break; } } if (ok) { cout << "YES" << "\n"; for (int i = 0; i < n; i++) { int x = st.Get(i, i + 1); cout << x << " "; } cout << "\n"; } else { cout << "NO" << "\n"; } } }; void solve(std::istream &in, std::ostream &out) { out << std::setprecision(12); Solution solution; solution.solve(in, out); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); istream &in = cin; ostream &out = cout; solve(in, out); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; struct Query { int l, r, q; } q[100005], q0[100005], q1[100005]; int a[100005], ev1_l[100005], ev1_r[100005], cont[100005], resp[100005]; pair<int, int> ev0_l[100005], ev0_r[100005]; int main() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { scanf("%d%d%d", &q[i].l, &q[i].r, &q[i].q); } bool valid = true; for (int k = 0; k < 30; k++) { int nq0 = 0, nq1 = 0; for (int i = 0; i < m; i++) { if (q[i].q & (1 << k)) q1[nq1].q = 1, q1[nq1].l = q[i].l, q1[nq1].r = q[i].r, nq1++; else q0[nq0].q = 0, q0[nq0].l = q[i].l, q0[nq0].r = q[i].r, nq0++; ; } memset(a, 0, sizeof(int) * (n + 1)); for (int i = 0; i < nq1; i++) ev1_l[i] = q1[i].l, ev1_r[i] = q1[i].r; sort(ev1_l, ev1_l + nq1); sort(ev1_r, ev1_r + nq1); int ct = 0, pos1 = 0, pos2 = 0; for (int i = 1; i <= n; i++) { while (pos1 < nq1 && ev1_l[pos1] == i) pos1++, ct++; if (ct > 0) a[i] = 1; while (pos2 < nq1 && ev1_r[pos2] == i) pos2++, ct--; } for (int i = 0; i < nq0; i++) ev0_l[i].first = q0[i].l, ev0_l[i].second = i, ev0_r[i].first = q0[i].r, ev0_r[i].second = i; sort(ev0_l, ev0_l + nq0); sort(ev0_r, ev0_r + nq0); memset(cont, 0, sizeof(int) * (n + 1)); pos1 = 0, pos2 = 0, ct = 0; for (int i = 1; i <= n; i++) { while (pos1 < nq0 && ev0_l[pos1].first == i) cont[ev0_l[pos1].second] = ct, pos1++; if (a[i] == 0) ct++; while (pos2 < nq0 && ev0_r[pos2].first == i) cont[ev0_r[pos2].second] = ct - cont[ev0_r[pos2].second], pos2++; } for (int i = 0; i < nq0; i++) if (cont[i] == 0) { valid = false; break; } if (!valid) break; for (int i = 1; i <= n; i++) if (a[i]) resp[i] |= (1 << k); } if (!valid) cout << "NO" << endl; else { cout << "YES" << endl; for (int i = 1; i <= n; i++) { if (i > 1) cout << " "; cout << resp[i]; } cout << endl; } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class B { static StringTokenizer st; static BufferedReader br; static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); int m = nextInt(); int []L = new int[m+1], R = new int[m+1], q = new int[m+1]; int[][]ans = new int[n+2][30]; for (int i = 1; i <= m; i++) { L[i] = nextInt(); R[i] = nextInt(); q[i] = nextInt(); for (int j = 0; j < 30; j++) { if ((q[i] & (1 << j)) != 0) { ans[L[i]][j]++; ans[R[i]+1][j]--; } } } int[][]sum = new int[n+1][30]; for (int i = 1; i <= n; i++) { for (int j = 0; j < 30; j++) { ans[i][j] += ans[i-1][j]; } } for (int i = 1; i <= n; i++) { for (int j = 0; j < 30; j++) { if (ans[i][j] > 1) ans[i][j] = 1; sum[i][j] = sum[i-1][j]; if (ans[i][j]==0) sum[i][j]++; } } for (int i = 1; i <= m; i++) { for (int j = 0; j < 30; j++) { if ((q[i] & (1 << j))==0) { if (sum[R[i]][j]==sum[L[i]-1][j]) { System.out.println("NO"); return; } } } } pw.println("YES"); for (int i = 1; i <= n; i++) { int res = 0; for (int j = 0; j < 30; j++) { if (ans[i][j]==1) res += (1 << j); } pw.print(res+" "); } pw.close(); } private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class CF_483_D_INTERESTING_ARRAY { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); SegmentTree st = new SegmentTree(n + 1); Triple[] queries = new Triple[m]; for (int i = 0; i < m; i++) { int l = sc.nextInt(); int r = sc.nextInt(); int q = sc.nextInt(); st.updateRange(l, r, q); queries[i] = new Triple(l, r, q); } boolean isInteresting = true; for(int i = 1 ; i <=n ; i++) st.query(i, i); for (int i = 0; i < m; i++) { Triple t = queries[i]; int q = st.query(t.l, t.r); isInteresting &= q == t.q; } StringBuilder sb = new StringBuilder(); if (!isInteresting) sb.append("NO").append("\n"); else { sb.append("YES").append("\n"); for (int i = 1; i <= n; i++) sb.append(st.query(i, i)).append(" "); sb.append("\n"); } System.out.print(sb); } static class Triple { int l, r, q; Triple(int l, int r, int q) { this.l = l; this.r = r; this.q = q; } } static class SegmentTree { int[] lazy, sTree; int n; SegmentTree(int in) { n = 1; while (n < in - 1) n <<= 1; sTree = new int[n << 1]; lazy = new int[n << 1]; } void propagate(int node) { lazy[node << 1] |= lazy[node]; lazy[node << 1 | 1] |= lazy[node]; sTree[node << 1] |= lazy[node]; sTree[node << 1 | 1] |= lazy[node]; lazy[node] = 0; } void updateRange(int i, int j, int val) { updateRange(1, 1, n, i, j, val); } void updateRange(int node, int b, int e, int i, int j, int val) { if (b > j || e < i) return; if (i <= b && e <= j) { sTree[node] |= val; lazy[node] |= val; return; } int mid = (b + e) >> 1; propagate(node); updateRange(node << 1, b, mid, i, j, val); updateRange(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; // System.out.println(Arrays.toString(sTree)); } int query(int i, int j) { return query(1, 1, n, i, j); } int query(int node, int b, int e, int i, int j) { if (b > j || e < i) return -1; if (i <= b && e <= j) return sTree[node]; propagate(node); int mid = (b + e) >> 1; int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 & q2; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class D { class IntervalTree { int[] d; int neutral; boolean and; int cnt = 0; int n; public IntervalTree(int n, boolean and) { this.and = and; neutral = and ? Integer.MAX_VALUE : 0; d = new int[n * 4]; this.n = n; Arrays.fill(d, neutral); } void add(int x) { set(x, cnt++, 0, n, 0); } void remove(int id) { set(neutral, id, 0, n, 0); } int set(int x, int ind, int L, int R, int i) { if (ind < L || R <= ind) return d[i]; if (L == R - 1) { d[i] = x; return d[i]; } int M = (R + L) / 2; int res = set(x, ind, L, M, 2 * i + 1); if (and) res &= set(x, ind, M, R, 2 * i + 2); else res |= set(x, ind, M, R, 2 * i + 2); d[i] = res; return d[i]; } int get(int l, int r, int L, int R, int i) { if (R <= l || r <= L) return neutral; if (l <= L && R <= r) return d[i]; int M = (R + L) / 2; if (and) return get(l, r, L, M, 2 * i + 1) & get(l, r, M, R, 2 * i + 2); else return get(l, r, L, M, 2 * i + 1) | get(l, r, M, R, 2 * i + 2); } } class Interval { int l, r, q; Interval(int l, int r, int q) { this.l = l; this.r = r; this.q = q; } } class Event implements Comparable<Event> { int coord, q, itid; Event pair; Event(int coord, int id, boolean begin, int q) { this.coord = coord; this.id = id; this.begin = begin; this.q = q; } int id; boolean begin; @Override public int compareTo(Event o) { if (this.coord != o.coord) return this.coord - o.coord; if (!this.begin && o.begin) return 1; if (begin && !o.begin) return -1; if (this.id != o.id) return id - o.id; return 0; } } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new D().run(); } public void solve() throws IOException { int n = nextInt(); int m = nextInt(); Event[] events = new Event[m << 1]; Interval[] intervals = new Interval[m]; for (int i = 0; i < m; ++i) { int l = nextInt() - 1; int r = nextInt() - 1; int q = nextInt(); intervals[i] = new Interval(l, r, q); events[i * 2] = new Event(l, i, true, q); events[(i * 2) + 1] = new Event(r, i, false, q); events[i * 2].pair = events[(i * 2) + 1]; events[(i * 2) + 1].pair = events[i * 2]; } Random rnd = new Random(); for (int i = 0; i < 2 * m; i++) { int j = rnd.nextInt(i + 1); Event t = events[i]; events[i] = events[j]; events[j] = t; } Arrays.sort(events); int[] a = new int[n]; int cnt = 0; IntervalTree it = new IntervalTree(m, false); for (int i = 0; i < n; ++i) { while (cnt < (m * 2) && events[cnt].coord == i && events[cnt].begin) { it.add(events[cnt].q); events[cnt].itid = it.cnt - 1; ++cnt; } a[i] = it.get(0, m, 0, m, 0); while (cnt < (m * 2) && events[cnt].coord == i) { it.remove(events[cnt].pair.itid); ++cnt; } } IntervalTree it1 = new IntervalTree(n, true); for (int i = 0; i < n; ++i) it1.add(a[i]); for (int i = 0; i < m; ++i) if (intervals[i].q != it1.get(intervals[i].l, intervals[i].r + 1, 0, n, 0)) { out.print("NO"); return; } out.println("YES"); for (int i : a) { out.print(i + " "); } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> const int MAXN = 1e5 + 5; struct SegmentTree { int sm[MAXN << 2], tag[MAXN << 2]; inline void cover(int x, int l, int r, int d) { sm[x] |= d; tag[x] |= d; } inline void pushdown(int x, int l, int r) { if (tag[x]) { int mid = (l + r) >> 1; cover(((x) << 1), l, mid, tag[x]); cover(((x) << 1 | 1), mid + 1, r, tag[x]); tag[x] = 0; } } inline void modify(int x, int l, int r, int L, int R, int d) { if (l == L && r == R) { cover(x, l, r, d); return; } int mid = (l + r) >> 1; pushdown(x, l, r); if (R <= mid) modify(((x) << 1), l, mid, L, R, d); else if (L > mid) modify(((x) << 1 | 1), mid + 1, r, L, R, d); else modify(((x) << 1), l, mid, L, mid, d), modify(((x) << 1 | 1), mid + 1, r, mid + 1, R, d); } inline int calc(int x, int l, int r, int p) { if (l == r) return sm[x]; int mid = (l + r) >> 1; pushdown(x, l, r); return p <= mid ? calc(((x) << 1), l, mid, p) : calc(((x) << 1 | 1), mid + 1, r, p); } } seg; int n, m; int ans[MAXN]; int ad[MAXN << 2]; inline void build(int x, int l, int r) { if (l == r) { ad[x] = ans[l]; return; } int mid = (l + r) >> 1; build(((x) << 1), l, mid); build(((x) << 1 | 1), mid + 1, r); ad[x] = ad[((x) << 1)] & ad[((x) << 1 | 1)]; } inline int query(int x, int l, int r, int L, int R) { if (l == L && r == R) return ad[x]; int mid = (l + r) >> 1; if (R <= mid) return query(((x) << 1), l, mid, L, R); else if (L > mid) return query(((x) << 1 | 1), mid + 1, r, L, R); else return query(((x) << 1), l, mid, L, mid) & query(((x) << 1 | 1), mid + 1, r, mid + 1, R); } int ll[MAXN], rr[MAXN], xx[MAXN]; int main() { scanf("%d%d", &n, &m); for (register int i = 1; i <= m; ++i) { int l, r, x; scanf("%d%d%d", &l, &r, &x); ll[i] = l; rr[i] = r; xx[i] = x; seg.modify(1, 1, n, l, r, x); } for (register int i = 1; i <= n; ++i) { int t = seg.calc(1, 1, n, i); ans[i] = t; } build(1, 1, n); for (register int i = 1; i <= m; ++i) { if (query(1, 1, n, ll[i], rr[i]) != xx[i]) { puts("NO"); return 0; } } puts("YES"); for (register int i = 1; i <= n; ++i) printf("%d ", ans[i]); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.IOException; import java.io.InputStreamReader; import java.io.FileReader; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Agostinho Junior */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { OutputWriter out; InputReader in; public void solve(int testNumber, InputReader in, OutputWriter out) { this.in = in; this.out = out; final int n = in.readInt(); final int m = in.readInt(); Segment[] segments = new Segment[m]; for (int i = 0; i < m; i++) { segments[i] = new Segment(in); } Arrays.sort(segments); int MAX_BIT = 30; int[][] sum = new int[n + 1][MAX_BIT + 1]; int[] pos = new int[MAX_BIT + 1]; for (Segment now: segments) for (int j = 0; j <= MAX_BIT; j++) if ((now.q & (1 << j)) > 0) { pos[j] = Math.max(pos[j], 1); while (pos[j] < now.l) { sum[ pos[j] ][j] = sum[ pos[j] - 1 ][j]; pos[j]++; } while (pos[j] <= now.r) { sum[ pos[j] ][j] = 1; sum[ pos[j] ][j] += sum[ pos[j] - 1 ][j]; pos[j]++; } } for (int i = 0; i <= MAX_BIT; i++) { pos[i] = Math.max(pos[i], 1); while (pos[i] <= n) { sum[ pos[i] ][i] = sum[ pos[i] - 1 ][i]; pos[i]++; } } for (Segment now: segments) for (int j = 0; j <= MAX_BIT; j++) { if ((now.q & (1 << j)) > 0 != (sum[now.r][j] - sum[now.l - 1][j] == now.r - now.l + 1)) { out.println("NO"); return; } } out.println("YES"); for (int i = 1; i <= n; i++) { long value = 0; for (int j = 0; j <= MAX_BIT; j++) { value |= (sum[i][j] - sum[i - 1][j]) << j; } out.print(value + " "); } out.println(); } } class Segment implements Comparable<Segment> { final int l; final int r; final int q; public Segment(InputReader in) { l = in.readInt(); r = in.readInt(); q = in.readInt(); } public int compareTo(Segment other) { return l == other.l ? r - other.r : l - other.l; } } class OutputWriter { private PrintWriter output; public OutputWriter(OutputStream out) { output = new PrintWriter(out); } public void print(Object o) { output.print(o); } public void println(Object o) { output.println(o); } public void println() { output.println(); } public void close() { output.close(); } } class InputReader { private BufferedReader input; private StringTokenizer line = new StringTokenizer(""); public InputReader(InputStream in) { input = new BufferedReader(new InputStreamReader(in)); } public void fill() { try { if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine()); } catch(IOException io) { io.printStackTrace(); System.exit(0);} } public int readInt() { fill(); return Integer.parseInt(line.nextToken()); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> namespace chtholly { inline int read() { int x = 0, f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) f ^= c == '-'; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + (c ^ '0'); return f ? x : -x; } inline bool read(long long &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c) && c ^ -1; c = getchar()) f ^= c == '-'; if (!~c) return 0; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + (c ^ '0'); return x = f ? x : -x, 1; } template <typename mitsuha> inline int write(mitsuha x) { if (!x) return putchar(48); if (x < 0) x = -x, putchar('-'); int bit[20], i, p = 0; for (; x; x /= 10) bit[++p] = x % 10; for (i = p; i; --i) putchar(bit[i] + 48); } inline char fuhao() { char c = getchar(); for (; isspace(c); c = getchar()) ; return c; } } // namespace chtholly using namespace chtholly; using namespace std; const int yuzu = 1e5; typedef int fuko[yuzu | 10]; fuko ans, l, r, q, c, s; int nico, n = read(), m = read(); int judge(int now) { int i; memset(c, 0, sizeof c); for (i = 1; i <= m; ++i) { if (q[i] & now) c[l[i]]++, c[r[i] + 1]--; } for (i = 1; i <= n; ++i) { c[i] += c[i - 1]; s[i] = s[i - 1] + (c[i] < 1); if (c[i]) ans[i] |= now; } for (i = 1; i <= m; ++i) { if (!(q[i] & now) && s[r[i]] - s[l[i] - 1] < 1) return 1; } return 0; } int main() { int i, k = 0; for (i = 1; i <= m; ++i) { l[i] = read(), r[i] = read(), q[i] = read(); } for (; !nico && k < 30; ++k) nico |= judge(1 << k); if (nico) puts("NO"); else { puts("YES"); for (i = 1; i <= n; ++i) write(ans[i]), putchar(' '); } }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; struct pt { int p; int value; bool nd; }; int l[100005], r[100005], q[100005], n, m, p; int a[500005] = {0}; pt v[200005]; int bits[32] = {0}; int build_tree(int n) { int j = 1; while (j < n) j *= 2; for (int i = 0; i <= 2 * j; ++i) a[i] = (1 << 30) - 1; return j - 1; } bool cmp(pt a, pt b) { return a.p < b.p || (a.p == b.p && a.nd < b.nd); } void add(int value) { for (int i = 0; i < 30; ++i) if ((value | (1 << i)) == value) bits[i]++; } void sub(int value) { for (int i = 0; i < 30; ++i) if ((value | (1 << i)) == value) bits[i]--; } int getValue() { int ans = 0; for (int i = 0; i < 30; ++i) if (bits[i] > 0) ans ^= (1 << i); return ans; } void renew(int v) { while ((v >>= 1) > 0) a[v] = a[2 * v] & a[2 * v + 1]; } int find(int l, int r) { int ans = (1 << 30) - 1; while (l <= r) { if ((l & 1) == 1) ans &= a[l++]; if ((r & 1) == 0) ans &= a[r--]; l >>= 1; r >>= 1; } return ans; } int main(int argc, const char* argv[]) { scanf("%d %d", &n, &m); p = build_tree(n); for (int i = 0; i < m; ++i) { scanf("%d %d %d", &l[i], &r[i], &q[i]); v[2 * i].p = l[i]; v[2 * i].value = q[i]; v[2 * i].nd = false; v[2 * i + 1].p = r[i]; v[2 * i + 1].value = q[i]; v[2 * i + 1].nd = true; } sort(v, v + 2 * m, cmp); int j = 0; for (int i = 1; i <= n; ++i) { if (j < 2 * m) { while (v[j].p == i && !v[j].nd) { add(v[j].value); ++j; } } a[p + i] = getValue(); renew(p + i); if (j < 2 * m) { while (v[j].p == i && v[j].nd) { sub(v[j].value); ++j; } } } bool ok = true; for (int i = 0; i < m && ok; ++i) ok = ok && (find(p + l[i], p + r[i]) == q[i]); if (!ok) printf("NO\n"); else { printf("YES\n"); for (int i = 1; i <= n; ++i) printf("%d ", a[p + i]); } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class A { static public class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); sTree[node] = sTree[node<<1]&sTree[node<<1|1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = sTree[node<<1] & sTree[node<<1|1]; } } void propagate(int node, int b, int mid, int e) { lazy[node<<1] |= lazy[node]; lazy[node<<1|1] |= lazy[node]; sTree[node<<1] |= lazy[node]; sTree[node<<1|1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1,1,N,i,j); } int query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return (1 << 31) - 1; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node<<1,b,mid,i,j); int q2 = query(node<<1|1,mid+1,e,i,j); return q1 & q2; } } public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int N = 1; while(N < n) N <<= 1; //padding int[] in = new int[N + 1]; for (int i = n + 1; i <= N; i++) { in[i] = (1 << 31) - 1; } SegmentTree st = new SegmentTree(in); int[] l = new int[m]; int[] r = new int[m]; int[] val = new int[m]; for (int i = 0; i < m; i++) { l[i] = sc.nextInt(); r[i] = sc.nextInt(); val[i] = sc.nextInt(); st.update_range(l[i], r[i], val[i]); } for (int i = 0; i < m; i++) { if(st.query(l[i], r[i]) != val[i]) { System.out.println("NO"); return; } } out.println("YES"); for (int i = 1; i <= n; i++) { out.print(st.query(i, i) + " "); } out.println(); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System){ br = new BufferedReader(new InputStreamReader(System));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.StringTokenizer; public class D483 { public static BufferedReader in; public static PrintWriter out; public static StringTokenizer tokenizer; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; in = new BufferedReader(new InputStreamReader(inputStream), 32768); out = new PrintWriter(outputStream); solve(); out.close(); } public static final int MAXBIT = 30; public static int[] t = new int[1000 * 1000]; public static int[] a; public static void solve() { int n = nextInt(); int m = nextInt(); int[] l = new int[m]; int[] r = new int[m]; int[] q = new int[m]; a = new int[n]; for (int i = 0; i < m; i++) { l[i] = nextInt() - 1; r[i] = nextInt(); q[i] = nextInt(); } int[] sum = new int[n + 1]; for (int bit = 0; bit <= MAXBIT; bit++) { for (int i = 0; i < n; i++) { sum[i] = 0; } for (int i = 0; i < m; i++) { int k = q[i] >> bit; if ((k & 1) == 1) { sum[l[i]]++; sum[r[i]]--; } } for (int i = 0; i < n; i++) { if (i > 0) { sum[i] += sum[i - 1]; } if (sum[i] > 0) { a[i] |= (1 << bit); } } } build(1, 0, n); // for (int i = 0 ; i < n ; i++) // out.println(a[i]); // out.println(query(0 , n , 1 , 0 , n)); // out.println(q[0]); for (int i = 0; i < m; i++) { if (query(1, l[i], r[i], 0, n) != q[i]) { out.println("NO"); return; } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(a[i] + " "); } } public static void build(int id, int l, int r) { if (l + 1 == r) { t[id] = a[l]; return; } int mid = (l + r) / 2; build(2 * id, l, mid); build(2 * id + 1, mid, r); t[id] = t[id * 2] & t[id * 2 + 1]; } public static long query(int id, int l, int r, int L, int R) { if (l == L && r == R) { return t[id]; } int mid = (L + R) / 2; long ans = (1L << MAXBIT) - 1; if (l < mid) { ans &= query(id * 2, l, Math.min(r, mid), L, mid); } if (mid < r) { ans &= query(id * 2 + 1, Math.max(l, mid), r, mid, R); } return ans; } public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static long nextLong() { return Long.parseLong(next()); } public static double nextDouble() { return Double.parseDouble(next()); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws Exception { new B().solve(); } void solve() throws IOException { FastScanner in = new FastScanner(System.in); n = in.nextInt(); int m = in.nextInt(); int[][] d = new int[n + 1][32]; int[] l = new int[m]; int[] r = new int[m]; int[] q = new int[m]; for (int mi = 0; mi < m; mi++) { l[mi] = in.nextInt() - 1; r[mi] = in.nextInt() - 1; q[mi] = in.nextInt(); for (int b = 0; (q[mi] >> b) > 0; b++) { if ((q[mi] >> b & 1) == 1) { d[l[mi]][b]++; d[r[mi] + 1][b]--; } } } for (int i = 1; i < d.length; i++) { for (int b = 0; b < d[0].length; b++) { d[i][b] += d[i - 1][b]; } } seg = new int[n * 4]; int[] v = new int[n]; for (int i = 0; i < n; i++) { for (int b = 0; b < d[0].length; b++) { if (d[i][b] > 0) { v[i] |= 1 << b; } } set(i, v[i]); } for (int mi = 0; mi < m; mi++) { if (get(l[mi], r[mi]) != q[mi]) { // NG System.out.println("NO"); return; } } System.out.println("YES"); StringBuilder sb = new StringBuilder(); sb.append(v[0]); for (int i = 1; i < v.length; i++) { sb.append(" " + v[i]); } System.out.print(sb); } int n; int[] seg; void set(int ai, int v) { set(ai, v, 0, 0, n); } void set(int ai, int v, int si, int sl, int len) { int sr = sl + len - 1; if (len == 1 && ai == sl) { seg[si] = v; } else if (sl <= ai && ai <= sr) { int c1 = si * 2 + 1; int c2 = si * 2 + 2; set(ai, v, c1, sl, len / 2); set(ai, v, c2, sl + len / 2, len - len / 2); seg[si] = seg[c1] & seg[c2]; } } int get(int al, int ar) { return get(al, ar, 0, 0, n); } int get(int al, int ar, int si, int sl, int len) { int sr = sl + len - 1; if (al <= sl && sr <= ar) { return seg[si]; } else if (ar < sl || sr < al) { return -1; } else { return get(al, ar, si * 2 + 1, sl, len / 2) & get(al, ar, si * 2 + 2, sl + len / 2, len - len / 2); } } class FastScanner { private InputStream _stream; private byte[] _buf = new byte[1024]; private int _curChar; private int _numChars; private StringBuilder _sb = new StringBuilder(); FastScanner(InputStream stream) { this._stream = stream; } public int read() { if (_numChars == -1) throw new InputMismatchException(); if (_curChar >= _numChars) { _curChar = 0; try { _numChars = _stream.read(_buf); } catch (IOException e) { throw new InputMismatchException(); } if (_numChars <= 0) return -1; } return _buf[_curChar++]; } public String next() { int c = read(); while (isWhitespace(c)) { c = read(); } _sb.setLength(0); do { _sb.appendCodePoint(c); c = read(); } while (!isWhitespace(c)); return _sb.toString(); } public int nextInt() { return (int) nextLong(); } public long nextLong() { int c = read(); while (isWhitespace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } public boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } } // // // // // // // // // // // // // // // // // // // // // // // // // //
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Stack; public class Main { static final int SIZE = (int) Math.pow(2, 17); static final int MAX_VAL_LOG = 32; static int[] l = new int[SIZE]; static int[] r = new int[SIZE]; static int[] q = new int[SIZE]; static int[][] seq = new int[MAX_VAL_LOG][SIZE]; static int[] t = new int[SIZE*2]; public static void insert(int val, int index, int l, int r, int pos) { if (l == r) { t[index] = val; // System.out.println("inserted: " + pos + " on position " + index + " begin: " + l + " end: " + r); // System.out.println(Arrays.toString(t)); return; } // System.out.println("next call: " + l + " " + r + " index: "+ index); int mid = (l+r)/2; if (mid >= pos) insert(val, index*2, l, mid, pos); else insert(val, index*2+1, mid+1, r, pos); t[index] = t[index*2] & t[index*2+1]; // if (t[index] != 0) System.out.println("& " + index + " " + index*2 + " " + (index*2+1) + " begin: " + l + " " + " end:" + r); } public static int query(int index, int L, int R, int l, int r) { if (l==L && R==r) { return t[index]; } int mid = (l+r)/2; int result = (1<<31) - 1; // System.out.println("result before: " + result); if (mid >= L) { int a = query(index*2, L, Math.min(mid, R), l, mid); // System.out.println("left query result: " + a); result &= a; // System.out.println("result & left query: " + result); } if (R > mid) { int a = query(index*2+1, Math.max(mid+1, L), R, mid+1,r); // System.out.println("right query result: " + a); result &= a; // System.out.println("result & right query: " + result); } return result; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); String[] values = line.split(" "); int n = Integer.parseInt(values[0]); int m = Integer.parseInt(values[1]); for (int i = 0; i < m; i++) { line = br.readLine(); values = line.split(" "); l[i] = Integer.parseInt(values[0]); r[i] = Integer.parseInt(values[1]); q[i] = Integer.parseInt(values[2]); for (int j = 0; j < MAX_VAL_LOG; j++) { if ((q[i] >> j & 1) == 1) { seq[j][l[i]]++; seq[j][r[i]+1]--; } } } int[] sum = new int[MAX_VAL_LOG]; for (int j = 0; j < SIZE; j++) { int val = 0; for (int i = MAX_VAL_LOG-1; i >= 0; i--) { val <<= 1; sum[i] += seq[i][j]; val += (sum[i] > 0) ? 1 : 0; } if (val > 0) {//System.out.println(j); insert(val, 1, 1, SIZE,j);} } // System.out.println("___________________________________________________________"); for (int i = 0; i < m; i++) { if (query(1, l[i], r[i], 1, SIZE) != q[i]) { System.out.println("NO"); return; } } System.out.println("YES"); int index = SIZE; for (int i = 0; i < n; i++) { System.out.print(t[index] + " "); index++; } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const long long N = 1e5 + 10, mod = 1e9 + 7; long long tree[4 * N], lazy[4 * N], n, m, l[N], r[N], q[N]; void updateRange(int node, int start, int end, int l, int r, int val) { if (lazy[node] != 0) { tree[node] |= lazy[node]; if (start != end) { lazy[node * 2] |= lazy[node]; lazy[node * 2 + 1] |= lazy[node]; } lazy[node] = 0; } if (start > r || end < l) return; if (start >= l and end <= r) { tree[node] |= val; if (start != end) { lazy[node * 2] |= val; lazy[node * 2 + 1] |= val; } return; } int mid = (start + end) / 2; updateRange(node * 2, start, mid, l, r, val); updateRange(node * 2 + 1, mid + 1, end, l, r, val); tree[node] = (tree[node * 2] & tree[node * 2 + 1]); } long long queryRange(int node, int start, int end, int l, int r) { if (start > r || end < l) return (1 << 30) - 1; if (lazy[node] != 0) { tree[node] |= lazy[node]; if (start != end) { lazy[node * 2] |= lazy[node]; lazy[node * 2 + 1] |= lazy[node]; } lazy[node] = 0; } if (start >= l and end <= r) { return tree[node]; } int mid = (start + end) / 2; long long p1 = queryRange(node * 2, start, mid, l, r); long long p2 = queryRange(node * 2 + 1, mid + 1, end, l, r); return (p1 & p2); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i = 0; i < m; i++) { cin >> l[i] >> r[i] >> q[i]; updateRange(1, 1, N, l[i], r[i], q[i]); } for (int i = 0; i < m; i++) { if (queryRange(1, 1, N, l[i], r[i]) != q[i]) { return cout << "NO\n", 0; } } cout << "YES\n"; for (int i = 0; i < n; i++) { cout << queryRange(1, 1, N, i + 1, i + 1) << ' '; } }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> #pragma optimization_level 3 using namespace std; using ll = long long; using ld = long double; const ll MOD = 1e+9 + 7; const ll INF = LLONG_MAX; const int N = (int)2e+5 + 8; ll n, m, a[N], l[N], r[N], x[N]; ll pre[50][N]; void MAIN(int tc) { cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> l[i] >> r[i] >> x[i]; for (int j = 0; j < 30; j++) { if ((1LL << j) & x[i]) { pre[j][l[i]]++; pre[j][r[i] + 1]--; } } } for (int i = 0; i < 30; i++) { for (int j = 1; j <= n; j++) { pre[i][j] += pre[i][j - 1]; } } for (int i = 0; i < 30; i++) { for (int j = 1; j <= n; j++) { pre[i][j] = (pre[i][j] > 0); } } for (int i = 0; i < 30; i++) { for (int j = 1; j <= n; j++) { pre[i][j] += pre[i][j - 1]; } } for (int i = 1; i <= m; i++) { ll ans = 0; for (int j = 0; j < 30; j++) { ll v = pre[j][r[i]] - pre[j][l[i] - 1]; if (v == r[i] - l[i] + 1) ans |= (1LL << j); } if (x[i] != ans) { cout << "NO" << "\n"; ; return; } } cout << "YES" << "\n"; ; for (int i = 1; i <= n; i++) { ll ans = 0; for (int j = 0; j < 30; j++) { ll v = pre[j][i] - pre[j][i - 1]; if (v == 1) ans |= (1LL << j); } cout << ans << " "; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout << fixed; cout << setprecision(10); int test_cases = 1; for (int i = 1; i <= test_cases; i++) { MAIN(i); } }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BInterestingArray solver = new BInterestingArray(); solver.solve(1, in, out); out.close(); } static class BInterestingArray { public void solve(int testNumber, FastReader s, PrintWriter out) { int n = s.nextInt(); int m = s.nextInt(); int[][] sum = new int[30][n + 1]; BInterestingArray.query[] q = new BInterestingArray.query[m]; for (int i = 0; i < m; i++) { q[i] = new BInterestingArray.query(s.nextInt() - 1, s.nextInt() - 1, s.nextInt()); } for (int i = 0; i <= 30; i++) { for (int j = 0; j < m; j++) { if (((1 << i) & q[j].andVal) != 0) { int from = q[j].from; int to = q[j].to; sum[i][from]++; sum[i][to + 1]--; } } } int[][] arr1 = new int[30][n]; for (int i = 0; i < 30; i++) { arr1[i][0] = sum[i][0]; } for (int i = 0; i < 30; i++) { for (int j = 1; j < n; j++) { arr1[i][j] = arr1[i][j - 1] + sum[i][j]; } } int[] ans = new int[n]; for (int i = 0; i < 30; i++) { for (int j = 0; j < n; j++) { if (arr1[i][j] > 0) { ans[j] += (1 << i); } } } // out.println(arrays.printArr(ans)); boolean ok = true; if (n == 1) { for (int i = 0; i < m; i++) { if (q[i].andVal != q[0].andVal) { ok = false; } } if (!ok) { out.println("NO"); } else { out.println("YES"); out.println(q[0].andVal); } return; } BInterestingArray.SegTree st = new BInterestingArray.SegTree(ans); for (int i = 0; i < m; i++) { int a = st.Query(q[i].from, q[i].to); if (a != q[i].andVal) { ok = false; break; } } if (!ok) { out.println("NO"); } else { out.println("YES"); out.println(BInterestingArray.arrays.printArr(ans)); } // out.println(arrays.printArr(arr)); } private static class query { int from; int to; int andVal; public query(int from, int to, int andVal) { this.from = from; this.to = to; this.andVal = andVal; } } private static class arrays { static String formatString(String str) { str = str.replace(",", "").replace("[", "").replace("]", ""); return str; } static StringBuilder printArr(Object arr) { String str = null; if (arr instanceof int[]) { str = Arrays.toString((int[]) arr); } if (arr instanceof long[]) { str = Arrays.toString((long[]) arr); } if (arr instanceof char[]) { str = Arrays.toString((char[]) arr); } if (arr instanceof boolean[]) { str = Arrays.toString((boolean[]) arr); } if (arr instanceof byte[]) { str = Arrays.toString((byte[]) arr); } if (arr instanceof double[]) { str = Arrays.toString((double[]) arr); } if (arr instanceof float[]) { str = Arrays.toString((float[]) arr); } if (arr instanceof short[]) { str = Arrays.toString((short[]) arr); } if (str != null) { return new StringBuilder(formatString(str)); } return null; } } private static class SegTree { int[] st; int[] arr; public SegTree(int[] arr) { this.arr = arr; int size = (int) Math.ceil(Math.log(arr.length) / Math.log(2)); st = new int[(int) ((2 * Math.pow(2, size)) - 1)]; buildSegmentTree(1, 0, arr.length - 1); } private void buildSegmentTree(int index, int L, int R) { if (L == R) { st[index] = arr[L]; return; } buildSegmentTree(index * 2, L, (L + R) / 2); buildSegmentTree(index * 2 + 1, (L + R) / 2 + 1, R); // Replace this line if you want to change the function of the Segment tree. st[index] = st[index * 2] & st[index * 2 + 1]; } private int Query(int queL, int queR) { return Query1(1, 0, arr.length - 1, queL, queR); } private int Query1(int index, int segL, int segR, int queL, int queR) { if (queL > segR || queR < segL) { return -1; } if (queL <= segL && queR >= segR) { return st[index]; } int ans1 = Query1(index * 2, segL, (segL + segR) / 2, queL, queR); int ans2 = Query1(index * 2 + 1, (segL + segR) / 2 + 1, segR, queL, queR); if (ans1 == -1) { return ans2; } if (ans2 == -1) { return ans1; } // Segment tree implemented for range minimum query. Change the below line to change the function. return ans1 & ans2; } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
/** * ******* Created on 27/4/20 1:53 PM******* */ import java.io.*; import java.util.*; public class B482 implements Runnable { private static final int MAX = (int) (1E5 + 5); private static final int MOD = (int) (1E9 + 7); private static final long Inf = (long) (1E14 + 10); private static final double eps = (double) (1E-9); private static final int Maxm = 31; private void solve() throws IOException { int n = reader.nextInt(); int m = reader.nextInt(); int[][]delta = new int[n+10][Maxm]; int[] a = new int[m]; int[] li = new int[m]; int[] ri = new int[m]; for(int i=0;i<m;i++){ int l = reader.nextInt(); int r = reader.nextInt(); li[i] = l; ri[i] =r; a[i] = reader.nextInt(); for(int j=0;j<Maxm;j++) if(((a[i]>>j)&1) ==1){ delta[r+1][j]--; delta[l][j]++; } } int[][] rcum= new int[n+10][Maxm]; int[] cur = new int[Maxm]; int[] res = new int[n+10]; for(int i=1;i <= n ;i++){ for(int j=0;j<Maxm;j++){ rcum[i][j] = rcum[i-1][j]; cur[j]+= delta[i][j]; if(cur[j]>0){ res[i] |=(1<<j); rcum[i][j]++; } } } for(int i=0;i<m;i++){ for(int j=0;j<Maxm;j++){ if( (((a[i]>>j)&1)==1 && rcum[ri[i]][j] -rcum[li[i]-1][j] != (ri[i]-li[i]+1) )){ writer.println("NO"); return; } if( (((a[i]>>j)&1)==0 && rcum[ri[i]][j] - rcum[li[i]-1][j] == (ri[i]-li[i]+1) )){ writer.println("NO"); return; } } } writer.println("YES"); for(int i=1;i<=n;i++) writer.print(res[i] +" "); } public static void main(String[] args) throws IOException { try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { new B482().run(); } } StandardInput reader; PrintWriter writer; @Override public void run() { try { reader = new StandardInput(); writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } interface Input extends Closeable { String next() throws IOException; String nextLine() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } default double nextDouble() throws IOException { return Double.parseDouble(next()); } default int[] readIntArray() throws IOException { return readIntArray(nextInt()); } default int[] readIntArray(int size) throws IOException { int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = nextInt(); } return array; } default long[] readLongArray(int size) throws IOException { long[] array = new long[size]; for (int i = 0; i < array.length; i++) { array[i] = nextLong(); } return array; } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } @Override public String nextLine() throws IOException { return reader.readLine(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class Main { // main public static void main(String [] args) throws IOException { // makes the reader and writer BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // read in StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] queries = new int[m][3]; for (int i=0;i<m;i++) { st = new StringTokenizer(f.readLine()); queries[i] = new int[]{Integer.parseInt(st.nextToken())-1,Integer.parseInt(st.nextToken())-1, Integer.parseInt(st.nextToken())}; } // sort by starting point Arrays.sort(queries,new Comparator<int[]>() { public int compare(int[] a, int[] b) { return (new Integer(a[0])).compareTo(b[0]); } }); // for each bit set settings and check int[] arr = new int[n]; for (int i=0;i<30;i++) { ArrayList<int[]> queriesY = new ArrayList<int[]>(); ArrayList<int[]> queriesN = new ArrayList<int[]>(); for (int j=0;j<m;j++) { if ((queries[j][2]&(1<<i))!=0) queriesY.add(new int[]{queries[j][0],queries[j][1]}); else queriesN.add(new int[]{queries[j][0],queries[j][1]}); } // make intervals disjoint and add ones int prev = 0; int[] nums = new int[n]; for (int[] span: queriesY) { if (span[0]<prev) { if (span[1]<prev) continue; else for (int j=prev;j<=span[1];j++) nums[j] = 1; } else for (int j=span[0];j<=span[1];j++) nums[j] = 1; prev = span[1]+1; } // prefix sums int[] ones = new int[n+1]; for (int j=1;j<=n;j++) ones[j] = ones[j-1]+nums[j-1]; // check whether at least one 0 for each 0 interval for (int[] span: queriesN) { if (ones[span[1]+1]-ones[span[0]]==span[1]-span[0]+1) { out.println("NO"); out.close(); System.exit(0); } } // add to arr for (int j=0;j<n;j++) arr[j]+=nums[j]*(1<<i); } // write to out out.println("YES"); for (int i=0;i<n;i++) { out.print(arr[i]); out.print(" "); } out.println(); // cleanup out.close(); f.close(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; template <class T> void debug(T a, T b) { ; } template <class T> void chmin(T& a, const T& b) { if (a > b) a = b; } template <class T> void chmax(T& a, const T& b) { if (a < b) a = b; } namespace std { template <class S, class T> ostream& operator<<(ostream& out, const pair<S, T>& a) { out << '(' << a.first << ',' << a.second << ')'; return out; } } // namespace std long long int readL() { long long int res; scanf("%I64d", &res); return res; } void printL(long long int res) { printf("%I64d", res); } int n, m; int sum[33][100005]; pair<pair<int, int>, int> must[100005]; int on_length[33][100005]; int main() { cin >> n >> m; for (int i = 0; i < (m); ++i) { int l, r, q; scanf("%d%d%d", &l, &r, &q); --l; must[i] = make_pair(make_pair(l, r), q); for (int j = 0; j < (30); ++j) if (q >> j & 1) ++sum[j][l], --sum[j][r]; } for (int j = 0; j < (30); ++j) for (int i = 0; i < (n); ++i) sum[j][i + 1] += sum[j][i]; for (int j = 0; j < (30); ++j) { for (int i = n - 1; i >= 0; --i) { if (sum[j][i] == 0) on_length[j][i] = 0; else on_length[j][i] = 1 + on_length[j][i + 1]; } } for (int i = 0; i < (m); ++i) { int l = must[i].first.first, r = must[i].first.second, q = must[i].second; int fail = 0; for (int j = 0; j < (30); ++j) if (!(q >> j & 1)) { if (on_length[j][l] >= r - l) fail = 1; } if (fail) { puts("NO"); return 0; } } puts("YES"); for (int i = 0; i < (n); ++i) { int tmp = 0; for (int j = 0; j < (30); ++j) if (sum[j][i] > 0) tmp |= (1 << j); printf("%d\n", tmp); } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int main() { vector<int> ors[32], lastZero[32], a, l, r, q; int n, m; cin >> n >> m; a.resize(n + 1); for (__typeof(32) i = 0; i < 32; ++i) ors[i].resize(n + 2), lastZero[i].resize(n + 1); l.resize(m), r.resize(m), q.resize(m); for (__typeof(m) p = 0; p < m; ++p) { cin >> l[p] >> r[p] >> q[p]; for (__typeof(32) i = 0; i < 32; ++i) if ((q[p] >> i) & 1) ors[i][l[p]]++, ors[i][r[p] + 1]--; } for (__typeof(32) i = 0; i < 32; ++i) { int cur = 0, zero = 0; for (__typeof(n) p = 1; p <= n; ++p) { cur += ors[i][p]; if (cur == 0) zero = p; else a[p] |= 1 << i; lastZero[i][p] = zero; } } for (__typeof(m) p = 0; p < m; ++p) { for (__typeof(32) i = 0; i < 32; ++i) { if ((q[p] >> i) & 1) continue; if (lastZero[i][r[p]] < l[p]) { cout << "NO"; return 0; } } } cout << "YES" << endl; for (__typeof(n) p = 1; p <= n; ++p) cout << a[p] << " "; return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class CF_275D { public static class RangeTree { int N; long[] tree; long[] lazy; // Stores the values to be pushed-down the tree only when needed long[] IDENTITY = {0,Long.MAX_VALUE}; //Identities of binary operations f(IDENTITY,x)=x, e.g. 0 for sum, +INF for min, -INF for max, and 0 for gcd // Associative binary operation used in the tree private long operation(long first, long sec, int type) { switch (type) { // The case 0 has to be used for the type of operation of the queries //case 0: return first + sec; // Addition case 0: return first |= sec; // OR case 1: return first &= sec; // AND //case 0: return Math.max(first,sec); // Maximum // Add cases as needed default: return sec; // -1 -> Assignment } } // Accumulate the operation zero (0) to be done to the sub-tree without actually pushing it down private long integrate(long act, long val, int nodeFrom, int nodeTo, int type) { switch (type) { //case 0: return act + val*(nodeTo-nodeFrom+1); // Addition case 0: return act |= val; // OR case 1: return act &= val; // AND default: return val; // -1 -> Assignment } } // Constructor for the tree with the maximum expected value public RangeTree(int maxExpected, int type) { maxExpected++; int len = Integer.bitCount(maxExpected)>1 ? Integer.highestOneBit(maxExpected)<<2 : Integer.highestOneBit(maxExpected)<<1; N = len/2; tree = new long[len]; lazy = new long[len]; if(tree[0]!=IDENTITY[type]){ Arrays.fill(tree,IDENTITY[type]); Arrays.fill(lazy,IDENTITY[type]); } } // Propagate the lazily accumulated values down the tree with query operator public void propagate(int node, int leftChild, int rightChild, int nodeFrom, int mid, int nodeTo, int type){ tree[leftChild] = integrate(tree[leftChild],lazy[node],nodeFrom,mid, type); tree[rightChild] = integrate(tree[rightChild],lazy[node],mid+1,nodeTo, type); lazy[leftChild] = operation(lazy[leftChild],lazy[node],type); lazy[rightChild] = operation(lazy[rightChild],lazy[node],type); lazy[node] = IDENTITY[type]; } // Update the values from the position i to j. Time complexity O(lg n) public void update(int i, int j, long newValue, int type) { update(1, 0, N-1, i, j,newValue, type); } private void update(int node, int nodeFrom, int nodeTo, int i, int j, long v, int type) { if (i <= nodeFrom && j >= nodeTo) { // Whole range needs to be updated tree[node] = integrate(tree[node], v, nodeFrom, nodeTo, type); lazy[node] = operation(lazy[node], v, type); } else if (j < nodeFrom || i > nodeTo) // No part of the range needs to be updated return; else { // Some part of the range needs to be updated int leftChild = 2 * node; int rightChild = leftChild+1; int mid = (nodeFrom + nodeTo) / 2; if(lazy[node]!=IDENTITY[type]) propagate(node, leftChild, rightChild, nodeFrom, mid, nodeTo, type); update(leftChild, nodeFrom, mid, i, j, v, type); // Search left child update(rightChild, mid+1, nodeTo, i, j, v, type); // Search right child tree[node] = operation(tree[leftChild], tree[rightChild],type); // Merge with the query operation } } // Query the range from i to j. Time complexity O(lg n) public long query(int i, int j, int type) { return query(1, 0, N-1, i, j, type); } private long query(int node, int nodeFrom, int nodeTo, int i, int j, int type) { if (i <= nodeFrom && j >= nodeTo) // The whole range is part of the query return tree[node]; else if (j < nodeFrom || i > nodeTo) // No part of the range belongs to the query return IDENTITY[type]; else { // Partially within the range int leftChild = 2*node; int rightChild = leftChild+1; int mid = (nodeFrom+nodeTo)/2; // Propagate lazy operations if necessary if(lazy[node]!=IDENTITY[type]) propagate(node, leftChild, rightChild, nodeFrom, mid, nodeTo, type); long a = query(leftChild, nodeFrom, mid, i, j, type); // Search left child long b = query(rightChild, mid+1, nodeTo, i, j, type); // Search right child return operation(a, b, type); } } } public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] a = new int[m]; int[] b = new int[m]; int[] q = new int[m]; for(int i = 0; i < m; i++){ a[i] = sc.nextInt()-1; b[i] = sc.nextInt()-1; q[i] = sc.nextInt(); } RangeTree or = new RangeTree(n,0); // OR tree for(int i = 0; i < m; i++) or.update(a[i],b[i], q[i],0); RangeTree and = new RangeTree(n,1); for(int i = 0; i < n; i++) and.update(i, i, or.query(i,i,0), 1); boolean fail = false; for(int i = 0; i < m; i++){ long aux = and.query(a[i],b[i],1); if(aux!=q[i]){ fail = true; break; } } PrintWriter out = new PrintWriter(System.out); if(!fail){ out.println("YES"); out.print(or.query(0,0,0)); for(int i=1; i<n; i++){ out.print(" "+or.query(i,i,0)); } out.println(); } else { out.println("NO"); } out.flush(); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.util.Scanner; public class D { private Scanner scanner = new Scanner(System.in); private final int N = 100000 + 4; private final int MAXBIT = 30; private int[] l = new int[N], r = new int[N], q = new int[N], a = new int[N], t = new int[N << 2]; private int n, m; public void readData() { n = scanner.nextInt(); m = scanner.nextInt(); for (int i = 0; i < m; i++) { l[i] = scanner.nextInt() - 1; r[i] = scanner.nextInt(); q[i] = scanner.nextInt(); } int[] sum = new int[N]; for (int i = 0; i < MAXBIT; i++) { for (int j = 0; j < n; j++) sum[j] = 0; for (int j = 0; j < m; j++) { if ((q[j] & (1 << i)) != 0 ) { sum[l[j]]++; sum[r[j]]--; } } for (int j = 0; j < n; j++) { if (j > 0) sum[j] += sum[j - 1]; if (sum[j] > 0) a[j] |= 1 << i; } } buildTree(0, 0, n); } private void buildTree(int node, int left, int right) { if (left + 1 == right) { t[node] = a[left]; return; } int mid = ((left + right) >> 1); buildTree(node * 2 + 1, left, mid); buildTree(node * 2 + 2, mid, right); t[node] = t[node * 2 + 1] & t[node * 2 + 2]; } private int query(int node, int l, int r, int L, int R) { if (l == L && r == R) return t[node]; int mid = ((L + R) >> 1); int ans = (1 << MAXBIT) - 1; if (l < mid) ans &= query(node * 2 + 1, l, Math.min(mid, r), L, mid); if (r > mid) ans &= query(node * 2 + 2, Math.max(mid, l), r, mid, R); return ans; } public boolean check() { for (int i = 0; i < m; i++) { if (query(0, l[i], r[i], 0, n) != q[i]) return false; } return true; } public void print() { System.out.print(a[0]); for (int i = 1; i < n; i++) System.out.print(" " + a[i]); System.out.println(); } public static void main(String[] args) { D tree = new D(); tree.readData(); if(tree.check()) { System.out.println("YES"); tree.print(); } else System.out.println("NO"); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int bit[100005][32]; int sifirsayisi[100005][32]; int sonuc[32]; int cvp[100005]; pair<pair<int, int>, int> girdi[100005]; int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { int l, r, q; scanf("%d%d%d", &l, &r, &q); for (int s = 0; s < 32; s++) if ((1 << s) & q) { bit[l][s]++; bit[r + 1][s]--; } girdi[i] = make_pair(make_pair(l, r), q); } for (int i = 1; i <= n; i++) { int sayi = 0; for (int s = 0; s < 32; s++) { if (bit[i][s] > 0) sonuc[s] += bit[i][s]; else if (bit[i][s] <= -1) sonuc[s] += bit[i][s]; int sbit = (sonuc[s] > 0 ? 1 : 0); sayi = sayi | (sbit << s); sifirsayisi[i][s] = sifirsayisi[i - 1][s] + !sbit; } cvp[i] = sayi; } for (int i = 1; i <= m; i++) { int l = girdi[i].first.first; int r = girdi[i].first.second; int q = girdi[i].second; for (int s = 0; s < 32; s++) { if (!(q & (1 << s))) { if (sifirsayisi[r][s] - sifirsayisi[l - 1][s] == 0) { printf("NO"); getchar(); getchar(); getchar(); getchar(); getchar(); getchar(); return 0; } } } } printf("YES"); printf("\n"); for (int i = 1; i <= n; i++) { printf("%d ", cvp[i]); } getchar(); getchar(); getchar(); getchar(); getchar(); getchar(); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class C{ static int []ans; public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(),q=sc.nextInt(); ans=new int [n]; int []l=new int [q],r=new int [q],x=new int [q]; for(int i=0;i<q;i++) { l[i]=sc.nextInt()-1; r[i]=sc.nextInt()-1; x[i]=sc.nextInt(); } boolean ok=true; for(int j=0;j<30;j++) { int []segments=new int [n+1]; for(int i=0;i<q;i++) { if((1<<j & x[i])==0) continue; segments[l[i]]++; segments[r[i]+1]--; } int one=0; for(int i=0;i<n;i++) { one+=segments[i]; if(one>0) ans[i]|=1<<j; } } SegmentTree tree=new SegmentTree(); for(int i=0;i<q;i++) { if(tree.query(l[i], r[i])!=x[i]) { ok=false; break; } } if(ok) { pw.println("YES"); for(int y:ans) pw.print(y+" "); } else pw.println("NO"); pw.close(); } static class SegmentTree { int []sum; SegmentTree() { int n=ans.length; sum=new int [4*n]; build(1,0,n-1); } void build(int node,int tl,int tr) { if(tl==tr) sum[node]=ans[tl]; else { int mid=tl+tr>>1; build(node*2,tl,mid); build(node*2+1,mid+1,tr); merge(node); } } void merge(int node) { sum[node]=sum[node*2] & sum[node*2+1]; } int query(int l,int r) { return query(1,0,ans.length-1,l,r); } int query(int node,int tl,int tr,int l,int r) { if(tr < l || r<tl) return (1<<30)-1; if(tl>=l && tr<=r) return sum[node]; int mid=tl+tr>>1; return query(node*2,tl,mid,l,r) & query(node*2+1,mid+1,tr,l,r); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class Main{ public static void main(String[] args) throws IOException { PrintWriter pw = new PrintWriter(System.out); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int N = 1; while(N < n) N <<= 1; //padding int k = sc.nextInt(); SegmentTree sgt = new SegmentTree(N+1); int[] l = new int[k+1]; int[] r = new int[k+1]; int[] q = new int[k+1]; for (int o = 1; o <= k; o++) { l[o] = sc.nextInt(); r[o] = sc.nextInt(); q[o] = sc.nextInt(); sgt.update_range(l[o], r[o], q[o]); } for (int i = 1; i < (sgt.sTree.length - 1) / 2; i++) { sgt.propagate(i, 0); } for (int m = 1; m <= k; m++) { if (sgt.query(l[m], r[m]) != q[m]) { System.out.println("NO"); return; } } StringBuilder sb = new StringBuilder(); for(int i = 1; i <= n; ++i) sb.append(sgt.sTree[sgt.N + i - 1] + " "); System.out.println("YES"); System.out.println(sb); } static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int l) { N = l-1; sTree = new int[N << 1]; lazy = new int[N << 1]; } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { int mid = b + e >> 1; propagate(node, mid); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void propagate(int node, int mid) { lazy[node << 1] |= lazy[node]; lazy[node << 1 | 1] |= lazy[node]; sTree[node << 1] |= lazy[node]; sTree[node << 1 | 1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return -1; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node,mid); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 & q2; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { int MAXBITS = 30; int[] create(int n, int[] ls, int[] rs, int[] qs) { int[] res = new int[n]; ArrayList<Constraint> al = new ArrayList<>(); for(int i = 0; i < ls.length; i++) { int l = ls[i], r = rs[i], q = qs[i]; al.add(new Constraint(l, 1, q)); al.add(new Constraint(r + 1, -1, q)); } Collections.sort(al); int cp = 0; int[] count = new int[MAXBITS]; for(int i = 0; i < n; i++) { while(cp < al.size() && al.get(cp).index == i) { Constraint c = al.get(cp); for(int bit = 0; bit < MAXBITS; bit++) { if(((c.val >> bit) & 1) == 1) { count[bit] += c.kind; } } cp++; } for(int bit = 0; bit < MAXBITS; bit++) { if(count[bit] > 0) { res[i] |= (1 << bit); } } } return res; } boolean check(int[] res, int[] ls, int[] rs, int[] qs) { int[][] count = new int[res.length + 1][MAXBITS]; for(int i = 1; i < count.length; i++) { for(int bit = 0; bit < MAXBITS; bit++) { count[i][bit] = count[i - 1][bit] + (((res[i - 1] >> bit) & 1) == 1 ? 1 : 0); } } for(int query = 0; query < ls.length; query++) { int l = ls[query], r = rs[query], q = qs[query]; for(int bit = 0; bit < MAXBITS; bit++) { int here = count[r + 1][bit] - count[l][bit]; if(((q >> bit) & 1) == 1) { if(here != r - l + 1) return false; } else { if(here >= r - l + 1) return false; } } } return true; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(), constraints = in.readInt(); int[] ls = new int[constraints], rs = new int[constraints], qs = new int[constraints]; IOUtils.readIntArrays(in, ls, rs, qs); MiscUtils.decreaseByOne(ls, rs); int[] res = create(n, ls, rs, qs); boolean ok = check(res, ls, rs, qs); if(ok) { out.printLine("YES"); out.printLine(res); } else { out.printLine("NO"); } } class Constraint implements Comparable<Constraint> { int index; int kind; int val; public Constraint(int index, int kind, int val) { this.index = index; this.kind = kind; this.val = val; } public int compareTo(Constraint o) { if(index != o.index) return Integer.compare(index, o.index); if(kind != o.kind) return -Integer.compare(kind, o.kind); return 0; } } } static class MiscUtils { public static void decreaseByOne(int[]... arrays) { for(int[] array : arrays) { for(int i = 0; i < array.length; i++) array[i]--; } } } static class IOUtils { public static void readIntArrays(InputReader in, int[]... arrays) { for(int i = 0; i < arrays[0].length; i++) { for(int j = 0; j < arrays.length; j++) arrays[j][i] = in.readInt(); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if(numChars == -1) throw new InputMismatchException(); if(curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch(IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if(c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while(!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if(filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for(int i = 0; i < objects.length; i++) { if(i != 0) writer.print(' '); writer.print(objects[i]); } } public void print(int[] array) { for(int i = 0; i < array.length; i++) { if(i != 0) writer.print(' '); writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int x[100005], y[100005], q[100005], ans[100005]; struct segtree { private: bool tree[100005 << 2]; public: void Clear(int l, int r, int rt) { tree[rt] = false; if (l == r) return; int m = (l + r) >> 1; Clear(l, m, rt << 1); Clear(m + 1, r, rt << 1 | 1); } void Pushdown(int rt) { if (tree[rt]) tree[rt << 1 | 1] = tree[rt << 1] = true; } void Pushup(int rt) { if (tree[rt << 1 | 1] && tree[rt << 1]) tree[rt] = true; } void Updata(int L, int R, int l, int r, int rt) { if (L <= l && r <= R) { tree[rt] = true; return; } Pushdown(rt); int m = (l + r) >> 1; if (L <= m) Updata(L, R, l, m, rt << 1); if (R > m) Updata(L, R, m + 1, r, rt << 1 | 1); Pushup(rt); } void Query(int L, int R, bool &ok, int l, int r, int rt) { if (ok || tree[rt]) return; if (L <= l && r <= R) { if (!tree[rt]) ok = true; return; } Pushdown(rt); int m = (l + r) >> 1; if (L <= m) Query(L, R, ok, l, m, rt << 1); if (R > m) Query(L, R, ok, m + 1, r, rt << 1 | 1); } void solve(int w, int l, int r, int rt) { if (l == r) { if (tree[rt]) ans[l] += (1 << w); return; } Pushdown(rt); int m = (l + r) >> 1; solve(w, l, m, rt << 1); solve(w, m + 1, r, rt << 1 | 1); } void debug(int l, int r, int rt) { printf("[%d %d]:%d\n", l, r, (tree[rt] ? 1 : 0)); if (l == r) return; int m = (l + r) >> 1; debug(l, m, rt << 1); debug(m + 1, r, rt << 1 | 1); } } T[32]; int main() { int n, m, i, j, k, w, value; bool ok, f; scanf("%d%d", &n, &m); for (i = 0; i < 32; i++) T[i].Clear(1, n, 1); for (i = 1; i <= m; i++) { scanf("%d%d%d", &x[i], &y[i], &q[i]); for (j = 0; j < 31; j++) if (q[i] & (1 << j)) T[j].Updata(x[i], y[i], 1, n, 1); } for (i = 1; i <= m; i++) { for (j = 0; j < 31; j++) { if (!(q[i] & (1 << j))) { ok = false; T[j].Query(x[i], y[i], ok, 1, n, 1); if (!ok) { printf("NO\n"); return 0; } } } } printf("YES\n"); for (i = 0; i < 31; i++) T[i].solve(i, 1, n, 1); for (i = 1; i <= n; i++) printf("%d ", ans[i]); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int inf = 1e9; const int N = 1e6 + 9; int n, m, mask = 30; int l[N], r[N], q[N], a[N]; int bit[30][N], t[4 * N]; void build(int v, int tl, int tr) { if (tl == tr) { t[v] = a[tl]; } else { int md = (tl + tr) / 2; build(v * 2, tl, md); build(v * 2 + 1, md + 1, tr); t[v] = t[v * 2] & t[v * 2 + 1]; } } int tap(int v, int tl, int tr, int l, int r) { if (l > r || r < tl || tr < l) return (1 << 30) - 1; if (l <= tl && tr <= r) return t[v]; int md = (tl + tr) / 2; return tap(v * 2, tl, md, l, r) & tap(v * 2 + 1, md + 1, tr, l, r); } int main() { ios_base ::sync_with_stdio(0), cin.tie(0), cout.tie(0); ; cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> l[i] >> r[i] >> q[i]; for (int j = 0; j < mask; j++) { if (q[i] & (1 << j)) { bit[j][l[i]]++; bit[j][r[i] + 1]--; } } } for (int i = 1; i <= n; i++) { for (int j = 0; j < mask; j++) { bit[j][i] = bit[j][i] + bit[j][i - 1]; } for (int j = 0; j < mask; j++) { if (bit[j][i]) { a[i] += (1 << j); } } } build(1, 1, n); for (int i = 1; i <= m; i++) { if (tap(1, 1, n, l[i], r[i]) != q[i]) return cout << "NO", 0; } cout << "YES" << endl; for (int i = 1; i <= n; i++) cout << a[i] << " "; return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int answers[100100]; int n, m; int lft[100100]; int rgt[100100]; int query[100100]; int cnts[100100]; int diff[100100]; bool solve(int b) { memset(cnts, 0, sizeof(cnts)); memset(diff, 0, sizeof(diff)); for (int i = 0; i < m; i++) { int t = (query[i] >> b) & 1; cnts[lft[i]] += t; cnts[rgt[i] + 1] -= t; } for (int i = 0; i < n; i++) { if (cnts[i] > 0) { answers[i] |= (1 << b); } cnts[i + 1] += cnts[i]; } for (int i = 0; i < n; i++) { diff[i + 1] += diff[i] + !cnts[i]; } for (int i = 0; i < m; i++) { int t = (query[i] >> b) & 1; if (t == 0 && diff[rgt[i] + 1] == diff[lft[i]]) { return false; } } return true; } int main() { cin >> n >> m; for (int i = 0; i < m; i++) { cin >> lft[i] >> rgt[i] >> query[i]; lft[i]--; rgt[i]--; } bool ok = true; for (int i = 0; i < 30; i++) { ok &= solve(i); } if (ok) { cout << "YES" << endl; for (int i = 0; i < n; i++) { cout << answers[i] << ' '; } cout << endl; } else { cout << "NO" << endl; } }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int SIZEN = 100010; int N, M; int chafen[33][SIZEN] = {0}; int ans[SIZEN] = {0}; int a[SIZEN], b[SIZEN], c[SIZEN]; int main() { int N, M; scanf("%d%d", &N, &M); for (int i = 1; i <= M; i++) { scanf("%d%d%d", &a[i], &b[i], &c[i]); int now = 0; int tmp = c[i]; while (tmp) { now++; if (tmp & 1) { chafen[now][a[i]]++; chafen[now][b[i] + 1]--; } tmp >>= 1; } } for (int j = 1; j <= 31; j++) { for (int i = 1; i <= N; i++) { chafen[j][i] += chafen[j][i - 1]; } for (int i = 1; i <= N; i++) if (chafen[j][i]) chafen[j][i] = 1; for (int i = 1; i <= N; i++) { chafen[j][i] += chafen[j][i - 1]; } } for (int i = 1; i <= M; i++) { int now = 0; int tmp = c[i]; while (now < 31) { now++; if (!(tmp & 1)) { int x = chafen[now][b[i]] - chafen[now][a[i] - 1]; if (x == b[i] - a[i] + 1) { printf("NO"); return 0; } } tmp >>= 1; } } for (int i = 1; i <= 31; i++) { for (int j = 1; j <= N; j++) { ans[j] |= (1 << i - 1) * (chafen[i][j] - chafen[i][j - 1]); } } printf("YES\n"); for (int i = 1; i <= N; i++) printf("%d ", ans[i]); printf("\n"); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class C { static class Node { int l, r, value; Node left, right; public Node(int l, int r) { this.l = l; this.r = r; value = 0; if (l != r) { int mid = (l + r) / 2; left = new Node(l, mid); right = new Node(mid + 1, r); } } public void setValue(int index, int value) { if (l == r) { this.value = value; return; } int mid = (l + r) / 2; if (index <= mid) { left.setValue(index, value); } else { right.setValue(index, value); } this.value = (left.value & right.value); } public int getAnd(int l, int r) { if (this.r < l || this.l > r) { return ~0; } if (l <= this.l && this.r <= r) { return this.value; } else { int leftAnd = left.getAnd(l, r); int rightAnd = right.getAnd(l, r); return leftAnd & rightAnd; } } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] parts = br.readLine().split(" "); int n = Integer.parseInt(parts[0]); int m = Integer.parseInt(parts[1]); int[][] on = new int[32][n + 1]; int[] l = new int[m], r = new int[m], q = new int[m]; for (int i = 0; i < m; ++i) { parts = br.readLine().split(" "); l[i] = Integer.parseInt(parts[0]) - 1; r[i] = Integer.parseInt(parts[1]) - 1; q[i] = Integer.parseInt(parts[2]); int k = 0; for (long j = 1; j < (1L << 31); j <<= 1, ++k) { if ((j & q[i]) > 0) { ++on[k][l[i]]; --on[k][r[i]+1]; } } } for (int i = 0; i < on.length; ++i) { for (int j = 1; j < on[i].length; ++j) { on[i][j] += on[i][j-1]; } } Node root = new Node(0, n-1); int[] nums = new int[n]; for (int i = 0; i < n; ++i) { int currNum = 0; for (int j = 0; j < 32; ++j) { currNum += on[j][i] > 0 ? 1 << j : 0; } nums[i] = currNum; root.setValue(i, currNum); } boolean valid = true; for (int i = 0; i < m && valid; ++i) { valid = root.getAnd(l[i], r[i]) == q[i]; } if (valid) { System.out.println("YES"); for (int i = 0; i < n; ++i) { System.out.print(nums[i]); if (i != n - 1) System.out.print(' '); } System.out.println(); } else { System.out.println("NO"); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.function.Supplier; import java.io.OutputStreamWriter; import java.util.function.IntFunction; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.function.Consumer; import java.io.Closeable; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); BInterestingArray solver = new BInterestingArray(); solver.solve(1, in, out); out.close(); } } static class BInterestingArray { Debug debug = new Debug(true); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.ri(); int m = in.ri(); SegTree<SumImpl, UpdateImpl> st = new SegTree<>(1, n, SumImpl::new, UpdateImpl::new, i -> { SumImpl ans = new SumImpl(); return ans; }); UpdateImpl bufUpd = new UpdateImpl(); SumImpl bufSum = new SumImpl(); int[][] limits = new int[m][3]; for (int i = 0; i < m; i++) { limits[i] = new int[]{in.ri(), in.ri(), in.ri()}; } for (int i = 0; i < m; i++) { int l = limits[i][0]; int r = limits[i][1]; bufUpd.or = limits[i][2]; st.update(l, r, 1, n, bufUpd); debug.debug("st", st); } for (int i = 0; i < m; i++) { int l = limits[i][0]; int r = limits[i][1]; bufSum.and = ~0; st.query(l, r, 1, n, bufSum); if (bufSum.and != limits[i][2]) { out.println("NO"); return; } } out.println("YES"); st.visitLeave(leaf -> { out.append(leaf.sum.and).append(' '); }); } } static interface Sum<S, U> extends Cloneable { void add(S s); void update(U u); void copy(S s); S clone(); } static class SegTree<S extends Sum<S, U>, U extends Update<U>> implements Cloneable { private SegTree<S, U> left; private SegTree<S, U> right; public S sum; private U update; private void modify(U x) { update.update(x); sum.update(x); } private void pushDown() { if (update.ofBoolean()) { left.modify(update); right.modify(update); update.clear(); assert !update.ofBoolean(); } } private void pushUp() { sum.copy(left.sum); sum.add(right.sum); } public SegTree(int l, int r, Supplier<S> sSupplier, Supplier<U> uSupplier, IntFunction<S> func) { update = uSupplier.get(); update.clear(); if (l < r) { sum = sSupplier.get(); int m = DigitUtils.floorAverage(l, r); left = new SegTree<>(l, m, sSupplier, uSupplier, func); right = new SegTree<>(m + 1, r, sSupplier, uSupplier, func); pushUp(); } else { sum = func.apply(l); } } private boolean cover(int L, int R, int l, int r) { return L <= l && R >= r; } private boolean leave(int L, int R, int l, int r) { return R < l || L > r; } public void update(int L, int R, int l, int r, U u) { if (leave(L, R, l, r)) { return; } if (cover(L, R, l, r)) { modify(u); return; } int m = DigitUtils.floorAverage(l, r); pushDown(); left.update(L, R, l, m, u); right.update(L, R, m + 1, r, u); pushUp(); } public void query(int L, int R, int l, int r, S s) { if (leave(L, R, l, r)) { return; } if (cover(L, R, l, r)) { s.add(sum); return; } int m = DigitUtils.floorAverage(l, r); pushDown(); left.query(L, R, l, m, s); right.query(L, R, m + 1, r, s); } public SegTree<S, U> deepClone() { SegTree<S, U> clone = clone(); clone.sum = clone.sum.clone(); clone.update = clone.update.clone(); if (clone.left != null) { clone.left = clone.left.deepClone(); clone.right = clone.right.deepClone(); } return clone; } public void visitLeave(Consumer<SegTree<S, U>> consumer) { if (left == null) { consumer.accept(this); return; } pushDown(); left.visitLeave(consumer); right.visitLeave(consumer); } public String toString() { StringBuilder ans = new StringBuilder(); deepClone().visitLeave(x -> ans.append(x.sum).append(' ')); return ans.toString(); } public SegTree<S, U> clone() { try { return (SegTree<S, U>) super.clone(); } catch (CloneNotSupportedException e) { throw new UnsupportedOperationException(e); } } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int ri() { return readInt(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class Debug { private boolean offline; private PrintStream out = System.err; static int[] empty = new int[0]; public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug debug(String name, Object x) { return debug(name, x, empty); } public Debug debug(String name, Object x, int... indexes) { if (offline) { if (x == null || !x.getClass().isArray()) { out.append(name); for (int i : indexes) { out.printf("[%d]", i); } out.append("=").append("" + x); out.println(); } else { indexes = Arrays.copyOf(indexes, indexes.length + 1); if (x instanceof byte[]) { byte[] arr = (byte[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof short[]) { short[] arr = (short[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof boolean[]) { boolean[] arr = (boolean[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof char[]) { char[] arr = (char[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof int[]) { int[] arr = (int[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof float[]) { float[] arr = (float[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof double[]) { double[] arr = (double[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else if (x instanceof long[]) { long[] arr = (long[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } else { Object[] arr = (Object[]) x; for (int i = 0; i < arr.length; i++) { indexes[indexes.length - 1] = i; debug(name, arr[i], indexes); } } } } return this; } } static class DigitUtils { private DigitUtils() { } public static int floorAverage(int x, int y) { return (x & y) + ((x ^ y) >> 1); } } static abstract class CloneSupportObject<T> implements Cloneable { public T clone() { try { return (T) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } } static class SumImpl implements Sum<SumImpl, UpdateImpl> { int and; public void add(SumImpl sum) { and &= sum.and; } public void update(UpdateImpl update) { and |= update.or; } public void copy(SumImpl sum) { and = sum.and; } public SumImpl clone() { SumImpl ans = new SumImpl(); ans.copy(this); return ans; } public String toString() { return "" + and; } } static interface Update<U extends Update<U>> extends Cloneable { void update(U u); void clear(); boolean ofBoolean(); U clone(); } static class FastOutput implements AutoCloseable, Closeable, Appendable { private static final int THRESHOLD = 32 << 10; private final Writer os; private StringBuilder cache = new StringBuilder(THRESHOLD * 2); public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } private void afterWrite() { if (cache.length() < THRESHOLD) { return; } flush(); } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); afterWrite(); return this; } public FastOutput append(int c) { cache.append(c); afterWrite(); return this; } public FastOutput append(String c) { cache.append(c); afterWrite(); return this; } public FastOutput println(String c) { return append(c).println(); } public FastOutput println() { return append(System.lineSeparator()); } public FastOutput flush() { try { // boolean success = false; // if (stringBuilderValueField != null) { // try { // char[] value = (char[]) stringBuilderValueField.get(cache); // os.write(value, 0, cache.length()); // success = true; // } catch (Exception e) { // } // } // if (!success) { os.append(cache); // } os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class UpdateImpl extends CloneSupportObject<UpdateImpl> implements Update<UpdateImpl> { int or; public void update(UpdateImpl update) { or |= update.or; } public void clear() { or = 0; } public boolean ofBoolean() { return or != 0; } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.awt.Point; import java.math.BigInteger; import static java.lang.Math.*; public class CodeforcesB implements Runnable { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { if (ONLINE_JUDGE) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } public static void main(String[] args) { new Thread(null, new CodeforcesB(), "", 128 * (1L << 20)).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); time(); memory(); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException { int n = readInt(); int m = readInt(); int[] l = new int[m], r = new int[m], q = new int[m]; for (int i = 0; i < m; i++) { l[i] = readInt() - 1; r[i] = readInt() - 1; q[i] = readInt(); } int[][] t = new int[31][n + 1]; for (int i = 0; i < m; i++) { int[] bits = new int[31]; int k = q[i]; int bit = 0; while (k > 0) { bits[bit++] = k % 2; k = k / 2; } for (bit = 0; bit < 31; bit++) { if (bits[bit] == 1) { t[bit][l[i]] += 1; t[bit][r[i] + 1] += -1; } } } for (int bit = 0; bit < 31; bit++) { int sum = 0; for (int i = 0; i < n; i++) { sum += t[bit][i]; t[bit][i] = sum; if (t[bit][i] > 1) t[bit][i] = 1; } } int[][] pref = new int[31][n]; for (int bit = 0; bit < 31; bit++) { pref[bit][0] = t[bit][0]; for (int i = 1; i < n; i++) pref[bit][i] = pref[bit][i - 1] + t[bit][i]; } for (int i = 0; i < m; i++) { int[] bits = new int[31]; int k = q[i]; int bit = 0; while (k > 0) { bits[bit++] = k % 2; k = k / 2; } for (bit = 0; bit < 31; bit++) { int sum = pref[bit][r[i]] - (l[i] == 0 ? 0 : pref[bit][l[i] - 1]); if (bits[bit] == 1 && sum != r[i] - l[i] + 1) { out.println("NO"); return; } if (bits[bit] == 0 && sum == r[i] - l[i] + 1) { out.println("NO"); return; } } } int[] pows = new int[31]; pows[0] = 1; for (int i = 1; i < 31; i++) pows[i] = pows[i - 1] * 2; out.println("YES"); for (int i = 0; i < n; i++) { int k = 0; for (int j = 0; j < 31; j++) k += t[j][i] * pows[j]; out.print(k + " "); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; bool sort_second(const pair<int, int>& left, const pair<int, int>& right) { return (left.second < right.second); } int main() { if (false) { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); } int n, m; cin >> n >> m; int len = 30; vector<pair<int, int> > l(m); vector<pair<int, int> > r(m); vector<unsigned int> q(m); int val1, val2; for (int i = 0; i < m; i++) { cin >> val1 >> val2 >> q[i]; l[i] = make_pair(val1 - 1, i); r[i] = make_pair(val2 - 1, i); } sort(l.begin(), l.end()); sort(r.begin(), r.end()); vector<unsigned int> ref(len); for (int i = 0; i < len; i++) { ref[i] = 1 << i; } vector<int> count(len, 0); unsigned int val = 0; vector<unsigned int> a(n, 0); vector<vector<int> > zeros(n, vector<int>(len, 0)); int ind1 = 0; int ind2 = 0; for (int i = 0; i < n; i++) { while (ind1 < m && l[ind1].first == i) { int ii = l[ind1].second; for (int j = 0; j < len; j++) { if ((q[ii] & ref[j])) { if (count[j] == 0) { val += ref[j]; } count[j]++; } } ind1++; } while (ind2 < m && r[ind2].first == (i - 1)) { int ii = r[ind2].second; for (int j = 0; j < len; j++) { if ((q[ii] & ref[j])) { count[j]--; if (count[j] == 0) { val -= ref[j]; } } } ind2++; } a[i] = val; for (int j = 0; j < len; j++) { if (i == 0) { zeros[i][j] = 0; } else { zeros[i][j] = zeros[i - 1][j]; } if (count[j] == 0) { zeros[i][j]++; } } } sort(l.begin(), l.end(), sort_second); sort(r.begin(), r.end(), sort_second); for (int i = 0; i < m; i++) { for (int j = 0; j < len; j++) { if ((q[i] & ref[j]) == 0 && (zeros[r[i].first][j] - (l[i].first == 0 ? 0 : zeros[l[i].first - 1][j])) == 0) { cout << "NO" << endl; return 0; } } } cout << "YES" << endl; for (int i = 0; i < n; i++) { if (i > 0) { cout << " "; } cout << a[i]; } cout << endl; if (false) { fclose(stdin); fclose(stdout); } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.*; public class B { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void solve() throws IOException { int n = nextInt(); int m = nextInt(); int[] low = new int[m]; int[] high = new int[m]; int[] val = new int[m]; for (int i = 0; i < m; i++) { low[i] = nextInt() - 1; high[i] = nextInt() - 1; val[i] = nextInt(); } int[] ans = new int[n]; for (int bit = 0; bit < 30; bit++) { int[] arr = new int[n + 1]; for (int i = 0; i < m; i++) { if ((val[i] & 1) == 1) { // System.err.println(bit + " " + i); arr[low[i]]++; arr[high[i] + 1]--; } } for (int i = 1; i <= n; i++) { arr[i] += arr[i - 1]; } for (int i = 0; i <= n; i++) { arr[i] = Math.min(arr[i], 1); } int[] sums = new int[n + 1]; sums[0] = arr[0]; for (int i = 1; i <= n; i++) { sums[i] = sums[i - 1] + arr[i]; } for (int i = 0; i < m; i++) { if ((val[i] & 1) == 0) { int sum = sums[high[i]]; if (low[i] > 0) { sum -= sums[low[i] - 1]; } if (sum == high[i] - low[i] + 1) { out.println("NO"); return; } } } for (int i = 0; i < n; i++) { ans[i] |= arr[i] << bit; } for (int i = 0; i < m; i++) { val[i] >>= 1; } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(ans[i] + " "); } } B() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new B(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static int N, M; public static int[][] delta, value, prefixes, inputs; public static int[] res; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); delta = new int[32][N + 1]; value = new int[32][N + 1]; prefixes = new int[32][N + 1]; inputs = new int[M][3]; res = new int[N + 1]; for (int iter = 0; iter < M; iter++) { st = new StringTokenizer(f.readLine()); int l = Integer.parseInt(st.nextToken()); int r = Integer.parseInt(st.nextToken()); int a = Integer.parseInt(st.nextToken()); inputs[iter][0] = l; inputs[iter][1] = r; inputs[iter][2] = a; for (int k = 31; k >= 0; k--) { if (((a >> k) & 1) == 1) { delta[k][l - 1]++; delta[k][r]--; } } } for (int k = 31; k >= 0; k--) { int curr = 0; for (int i = 1; i <= N; i++) { curr += delta[k][i - 1]; if (curr > 0) { value[k][i] = 1; res[i] |= (1 << k); } prefixes[k][i] = prefixes[k][i - 1] + value[k][i]; } } for (int[] is : inputs) { int l = is[0]; int r = is[1]; int a = is[2]; for (int k = 31; k >= 0; k--) { if (((a >> k) & 1) == 0) { if (prefixes[k][r] - prefixes[k][l - 1] == (r - l + 1)) { System.out.println("NO"); return; } } } } StringBuilder sb = new StringBuilder(); sb.append("YES").append("\n"); for (int i = 1; i <= N; i++) { sb.append(res[i]).append(" "); } sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
//package CF; import java.io.*; import java.util.*; public class B{ public static void main(String[] args) throws Exception { Scanner bf = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = bf.nextInt(); int m = bf.nextInt(); int N = 1; while(N < n) N <<= 1; int[] in = new int[N + 1]; SegmentTree sg = new SegmentTree(in); Triple [] q = new Triple[m]; for (int i = 0; i < m; i++) { q[i] = new Triple(bf.nextInt(), bf.nextInt(), bf.nextInt()); sg.update_range(q[i].l, q[i].r, q[i].q); } boolean flag = true; for (int i = 0; i < q.length; i++) { if(sg.query(q[i].l, q[i].r) != q[i].q) { flag = false; break; } } if(flag){ out.println("YES"); for (int i = 1; i <= n; i++) { out.print(sg.query(i, i)+" "); } } else out.println("NO"); out.flush(); out.close(); } static class Triple{ int l; int r; int q; public Triple(int a, int b, int c){ l = a; r = b; q = c; } } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N<<1]; } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = sTree[node<<1] & sTree[node<<1|1]; } } void propagate(int node, int b, int mid, int e) { lazy[node<<1] |= lazy[node]; lazy[node<<1|1] |= lazy[node]; sTree[node<<1] |= lazy[node]; sTree[node<<1|1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1,1,N,i,j); } int query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return -1; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node<<1,b,mid,i,j); int q2 = query(node<<1|1,mid+1,e,i,j); return q1 & q2; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
//import java.awt.Dimension; import java.awt.Point; import java.io.*; import static java.lang.Character.*; import static java.lang.Math.*; import java.math.BigDecimal; import java.math.BigInteger; import static java.math.BigInteger.*; import java.util.*; import static java.util.Arrays.*; import java.util.logging.Level; import java.util.logging.Logger; //import java.math.BigInteger; //import static java.lang.Character.*; //import static java.lang.Math.*; //import static java.math.BigInteger.*; //import static java.util.Arrays.*; //import java.awt.Point; // interger !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //import java.awt.Polygon; //import java.awt.Rectangle; //import java.awt.geom.AffineTransform; //import java.awt.geom.Line2D; //import java.awt.geom.Point2D; //import javafx.scene.shape.Line; //import javafx.scene.transform.Rotate; //<editor-fold defaultstate="collapsed" desc="Main"> public class Main { // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display private void run() { try { Locale.setDefault(Locale.US); } catch (Exception e) { } boolean oj = true; try { oj = System.getProperty("MYLOCAL") == null; } catch (Exception e) { } if (oj) { sc = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } else { try { sc = new FastScanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); } catch (IOException e) { MLE(); } } Solver s = new Solver(); s.sc = sc; s.out = out; s.solve(); if (!oj) { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); } out.flush(); } private void show(int[] arr) { for (int v : arr) { err.print(" " + v); } err.println(); } public static void exit() { err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3); err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20); out.flush(); out.close(); System.exit(0); } public static void MLE() { int[][] arr = new int[1024 * 1024][]; for (int i = 0; i < arr.length; i++) { arr[i] = new int[1024 * 1024]; } } public static void main(String[] args) { new Main().run(); } static long timeBegin = System.currentTimeMillis(); static FastScanner sc; static PrintWriter out; static PrintStream err = System.err; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="FastScanner"> class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStreamReader reader) { br = new BufferedReader(reader); st = new StringTokenizer(""); } String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception ex) { return null; } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return br.readLine(); } catch (IOException ex) { return null; } } } //</editor-fold> class Solver { void myAssert(boolean OK) { if (!OK) { Main.MLE(); } } FastScanner sc; PrintWriter out; static PrintStream err = System.err; int getSum(int[] s, int l, int r) { if( l == 0 ) return s[r]; return s[r] - s[l-1]; } class Qwest{ int l, r, val; public Qwest(int l, int r, int val) { this.l = l; this.r = r; this.val = val; } } int cntBits = 31; int n, m; Qwest[] qw; int[][] sum1; void solve() { n = sc.nextInt(); m = sc.nextInt(); qw = new Qwest[m]; sum1 = new int[cntBits][n+1]; for (int i = 0; i < m; i++) { Qwest q = qw[i] = new Qwest(sc.nextInt()-1, sc.nextInt()-1, sc.nextInt()); for (int bit = 0; bit < cntBits; bit++) { if( (q.val&(1L<<bit)) != 0 ){ ++sum1[bit][q.l]; --sum1[bit][q.r+1]; } } } for (int bit = 0; bit < cntBits; bit++) { for (int i = 1; i < sum1[bit].length; i++) { sum1[bit][i] += sum1[bit][i-1]; } for (int i = 0; i < sum1[bit].length; i++) { sum1[bit][i] = min( 1, sum1[bit][i] ); } for (int i = 1; i < sum1[bit].length; i++) { sum1[bit][i] += sum1[bit][i-1]; } } for (Qwest q : qw) { for (int bit = 0; bit < cntBits; bit++) { if( (q.val&(1L<<bit)) == 0 ){ long s = sum1[bit][q.r] - (q.l==0?0:sum1[bit][q.l-1]); if( s == q.r-q.l+1 ){ out.println( "NO" ); return ; } } } } out.println( "YES" ); for( int i = 0; i < n; ++i ){ long ans = 0; for (int bit = 0; bit < cntBits; bit++) { if( getSum(sum1[bit],i,i) != 0 ) ans |= 1L << bit; } out.print( " " + ans ); } out.println(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; long long tree[400005]; long long ans[100005]; long long n, MAXBIT = 30; void build(long long tl, long long tr, long long nd) { if (tl == tr) { tree[nd] = ans[tl]; return; } long long mid = (tl + tr) / 2; build(tl, mid, 2 * nd); build(mid + 1, tr, 2 * nd + 1); tree[nd] = tree[2 * nd] & tree[2 * nd + 1]; } long long query(long long l, long long r, long long tl, long long tr, long long nd) { if (tr < l or tl > r) return (2147483647LL); if (l <= tl and r >= tr) return tree[nd]; long long mid = (tr + tl) / 2; return query(l, r, tl, mid, 2 * nd) & query(l, r, mid + 1, tr, 2 * nd + 1); } void solve() { vector<long long> v; vector<pair<long long, long long>> vp; map<long long, long long> mp; set<long long> st; multiset<long long> mst; long long m = 0, i = 0, j = 0, k = 0, c = 0, l = 0, r = 0, p = 1e9 + 9, q = 0, x = 0, y = 0, z = 0, flag; string s, t; cin >> n >> m; long long a[n + 5][35]; memset(a, 0, sizeof(a)); vector<vector<long long>> ve(m, vector<long long>(3)); for (i = 0; i < m; i++) cin >> ve[i][0] >> ve[i][1] >> ve[i][2]; long long sum[n + 5]; for (int bit = 0; bit <= MAXBIT; bit++) { for (int i = 0; i <= n; i++) sum[i] = 0; for (int i = 0; i < m; i++) { if ((ve[i][2] >> bit) & 1) { sum[ve[i][0]]++; sum[ve[i][1] + 1]--; } } for (int i = 0; i <= n; i++) { if (i > 0) sum[i] += sum[i - 1]; if (sum[i] > 0) { ans[i] |= (1 << bit); } } } build(1, n, 1); for (i = 0; i < m; i++) { if (query(ve[i][0], ve[i][1], 1, n, 1) != ve[i][2]) { cout << "NO\n"; return; } } cout << "YES\n"; for (i = 1; i <= n; i++) cout << ans[i] << " "; cout << '\n'; } bool imp = false; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t = 1; if (imp) cin >> t; long long j = t; while (t--) { solve(); } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 10; const int M = 1e5 + 10; int n, m; int l[M], r[M], q[M]; int d[30][N]; int sum[30][N]; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) { scanf("%d%d%d", l + i, r + i, q + i); } for (int i = 0; i < m; ++i) { bitset<30> tmp = q[i]; for (int j = 0; j < 30; ++j) { if (tmp[j]) { d[j][l[i]] += 1; d[j][r[i] + 1] -= 1; } } } for (int i = 0; i < 30; ++i) { for (int j = 1; j <= n; ++j) { d[i][j] += d[i][j - 1]; } } for (int i = 0; i < 30; ++i) { for (int j = 1; j <= n; ++j) { if (d[i][j] > 0) { d[i][j] = 1; } } } for (int i = 0; i < 30; ++i) { for (int j = 1; j <= n; ++j) { sum[i][j] = sum[i][j - 1] + d[i][j]; } } int ff = 1; for (int i = 0; i < m; ++i) { bitset<30> tmp = q[i]; for (int j = 0; j < 30; ++j) { if (tmp[j]) { if (sum[j][r[i]] - sum[j][l[i] - 1] != r[i] - l[i] + 1) { ff = 0; j = 30; i = m; } } else { if (sum[j][r[i]] - sum[j][l[i] - 1] == r[i] - l[i] + 1) { ff = 0; j = 30; i = m; } } } } if (ff) { printf("YES\n"); for (int i = 1; i <= n; ++i) { int tmp = 0; for (int j = 0; j < 30; ++j) { tmp |= d[j][i] << j; } printf("%d%c", tmp, " \n"[i == n]); } } else { printf("NO\n"); } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int base = 1331; const int N = 1e5 + 1; template <typename T> inline void Cin(T& x) { char c = getchar(); x = 0; while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); } template <typename T, typename... Args> inline void Cin(T& a, Args&... args) { Cin(a); Cin(args...); } int s[N][31], n, m, a[N], l[N], r[N], q[N], res, ST[4 * N]; void build(int id, int l, int r) { if (l == r) { ST[id] = a[l]; return; } int mid = (l + r) / 2; build(id * 2, l, mid); build(id * 2 + 1, mid + 1, r); ST[id] = ST[id * 2] & ST[id * 2 + 1]; } void Get(int id, int l, int r, int u, int v) { if (l > v || r < u) return; if (l >= u && r <= v) { res = res & ST[id]; return; } int mid = (l + r) / 2; Get(id * 2, l, mid, u, v); Get(id * 2 + 1, mid + 1, r, u, v); } void read(void) { cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> l[i] >> r[i] >> q[i]; for (int j = 0; j <= 30; j++) { if (q[i] >> j & 1 == 1) { s[l[i]][j]++; s[r[i] + 1][j]--; } } } for (int j = 0; j <= 30; j++) { for (int i = 1; i <= n; i++) { s[i][j] += s[i - 1][j]; if (s[i][j] > 0) a[i] += (1 << j); } } build(1, 1, n); for (int i = 1; i <= m; i++) { res = a[l[i]]; Get(1, 1, n, l[i], r[i]); if (res != q[i]) { cout << "NO"; return; } } cout << "YES" << '\n'; for (int i = 1; i <= n; i++) cout << a[i] << ' '; } signed main(void) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); read(); }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class InterestingArray { private static int[] segmentTree; private static int[] num; private static final int MAX_BITS = 30; private static final int ONE_BITS = Integer.MAX_VALUE; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st; st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); int[] l = new int[m], r = new int[m], q = new int[m]; int[][] prefixSum = new int[n][MAX_BITS]; for (int i = 0; i < m; i++) { st = new StringTokenizer(br.readLine()); l[i] = Integer.parseInt(st.nextToken()) - 1; r[i] = Integer.parseInt(st.nextToken()) - 1; q[i] = Integer.parseInt(st.nextToken()); int p = 0; int temp = q[i]; while (temp > 0) { int mod = (temp & 1); if (mod == 1) { prefixSum[l[i]][p]++; if (r[i] + 1 < n) { prefixSum[r[i] + 1][p]--; } } temp >>= 1; p++; } } for (int i = 1; i < n; i++) { for (int j = 0; j < MAX_BITS; j++) { prefixSum[i][j] += prefixSum[i - 1][j]; } } num = new int[n]; for (int i = 0; i < n; i++) { int temp = prefixSum[i][0] > 0 ? 1 : 0; int pow2 = 1; for (int j = 1; j < MAX_BITS; j++) { pow2 <<= 1; if (prefixSum[i][j] > 0) { temp += pow2; } } num[i] = temp; } int numNodes = (int) Math.pow(2.0, Math.ceil(Math.log(n) / Math.log(2.0)) + 1) - 1; segmentTree = new int[numNodes]; buildTree(0, n - 1, 0); for (int i = 0; i < m; i++) { if (query(0, n - 1, 0, l[i], r[i]) != q[i]) { out.println("NO"); out.close(); } } out.println("YES"); for (int i = 0; i < n; i++) { out.print(num[i] + " "); } out.println(); out.close(); } private static void buildTree(int l, int r, int level) { if (l == r) { segmentTree[level] = num[l]; return; } int mid = (l + r) >> 1; int lC = (level << 1) + 1, rC = lC + 1; buildTree(l, mid, lC); buildTree(mid + 1, r, rC); segmentTree[level] = segmentTree[lC] & segmentTree[rC]; } private static int query(int l, int r, int level, int lQ, int rQ) { if (l > rQ || r < lQ) { return ONE_BITS; } if (l >= lQ && r <= rQ) { return segmentTree[level]; } int mid = (l + r) >> 1; int lC = (level << 1) + 1, rC = lC + 1; return query(l, mid, lC, lQ, rQ) & query(mid + 1, r, rC, lQ, rQ); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:512000000") using namespace std; int n, m; int l, r, q; int mas[100005]; int nm[31][100005]; const int magic = 1 << 17; int tree[magic * 2]; const int ret = (1 << 30) - 1; int lg[100005]; int rg[100005]; int qq[100005]; int get(int vl, int trl, int trr, int l, int r) { if (l > r) { return ret; } if (trl == l && trr == r) { return tree[vl]; } int m = trl + trr; m >>= 1; vl <<= 1; return get(vl, trl, m, l, min(r, m)) & get(vl | 1, m + 1, trr, max(m + 1, l), r); } void build() { for (int i = magic - 1; i; i--) { tree[i] = tree[i << 1] & tree[(i << 1) | 1]; } } int main() { time_t start = clock(); fill(tree, tree + 2 * magic, ret); scanf("%d %d", &n, &m); for (int i = 0; i < m; i++) { scanf("%d %d %d", &l, &r, &q); lg[i] = l; rg[i] = r; qq[i] = q; for (int j = 0; j < 31; j++) { if (q & (1 << j)) { nm[j][l - 1]++; nm[j][r]--; } } } for (int i = 0, a; i < 31; i++) { int add = 0; for (int j = 0; j < n; j++) { add += nm[i][j]; a = add > 0; mas[j] |= (a << i); } } for (int i = 0; i < n; i++) { tree[i + magic] = mas[i]; } build(); for (int i = 0, val; i < m; i++) { val = get(1, 0, magic - 1, lg[i] - 1, rg[i] - 1); if (val != qq[i]) { return !printf("NO"); } } puts("YES"); for (int i = 0; i < n; i++) { printf("%d ", mas[i]); } fprintf(stderr, "\n%0.3lf\n", (clock() - start) * 1.0 / CLOCKS_PER_SEC); return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.util.*; import java.io.*; import java.text.*; public class B482 { static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] = val; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] & sTree[index << 1 | 1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] |= lazy[node]; lazy[node << 1 | 1] |= lazy[node]; sTree[node << 1] |= lazy[node]; sTree[node << 1 | 1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return (1<<30)-1; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return q1 & q2; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int m =sc.nextInt(); int N = 1; while(N<n) N*=2; int [] arr = new int [N+1]; SegmentTree st = new SegmentTree(arr); int [] l = new int [m]; int [] r = new int [m]; int [] q = new int [m]; for(int i =0 ;i<m;i++) { l[i]=sc.nextInt(); r[i]=sc.nextInt(); q[i]=sc.nextInt(); st.update_range(l[i], r[i],q[i]); } for(int i = 0;i<m;i++) { if(st.query(l[i], r[i])!=q[i]) { pw.println("NO"); pw.flush(); pw.close(); return; } } pw.println("YES"); for(int i = 1;i<=n;i++) { pw.print(st.query(i, i)+" "); } pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.util.*; import java.io.*; public class abc{ static void Construct(int seg[],int l,int r,int pos,int a[]){ if(l==r){ seg[pos]=a[l]; return; } int m=(l+r)/2; Construct(seg,l,m,2*pos+1,a); Construct(seg,m+1,r,2*pos+2,a); seg[pos]=(seg[2*pos+1]&seg[2*pos+2]); } static int Query(int seg[],int l,int r,int ql,int qr,int pos){ if(qr<l||ql>r) return(-1); else if(ql<=l&&qr>=r) return(seg[pos]); int m=(l+r)/2; int x1= Query(seg,l,m,ql,qr,2*pos+1); int x2= Query(seg,m+1,r,ql,qr,2*pos+2); return(x1&x2); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int MAXBIT=30; int n = sc.nextInt(); int m = sc.nextInt(); int L[] = new int[m]; int R[] = new int[m]; int q[] = new int[m]; for(int i=0;i<m;i++){ L[i]=sc.nextInt(); R[i]=sc.nextInt(); q[i]=sc.nextInt(); L[i]--; } int sum[] = new int[n+2]; int a[] = new int[n]; int seg[] = new int[4*n]; for(int bit = 0; bit <= MAXBIT; bit++) { for(int i = 0; i < n; i++) sum[i] = 0; for(int i = 0; i < m; i++) { if (((q[i] >> bit)&1)>0) { sum[L[i]]++; sum[R[i]]--; } } for(int i = 0; i < n; i++) { if (i > 0) sum[i] += sum[i - 1]; if (sum[i] > 0) a[i] |= (1 << bit); } } Construct(seg,0,n-1,0,a); int flag=1; for(int i=0;i<m;i++){ if(Query(seg,0,n-1,L[i],R[i]-1,0)!=q[i]){ flag=0; break; } } if(flag==0) out.println("NO"); else{ out.println("YES"); for(int i=0;i<n;i++) out.print(a[i]+" "); } out.flush(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { private int n; private int[] result; private int[] st; private int[] low; private int[] high; public void solve(int testNumber, Scanner in, PrintWriter out) { n = in.nextInt(); int q = in.nextInt(); int left[] = new int[q]; int right[] = new int[q]; int queryNum[] = new int[q]; result = new int[n]; low = new int[4 * n + 1]; high = new int[4 * n + 1]; st = new int[4 * n + 1]; Arrays.fill(st, Integer.MAX_VALUE); for (int i = 0; i < q; i++) { left[i] = in.nextInt() - 1; right[i] = in.nextInt() - 1; queryNum[i] = in.nextInt(); } for (int pos = 0; pos <= 30; pos++) { int sum[] = new int[n]; for (int i = 0; i < q; i++) { if ((queryNum[i] & (1 << pos)) > 0) { sum[left[i]]++; if (right[i] + 1 < n) { sum[right[i] + 1]--; } } } for (int i = 0; i < n; i++) { if (i > 0) { sum[i] += sum[i - 1]; } if (sum[i] > 0) { result[i] |= (1 << pos); } } } init(1, 0, n - 1); //System.out.println(Arrays.toString(result)); for (int i = 0; i < q; i++) { int r = raq(left[i], right[i]); if (r != queryNum[i]) { out.println("NO"); return; } } StringBuffer st = new StringBuffer(""); for (int i = 0; i < n; i++) { st.append(result[i] + " "); } out.println("YES"); out.println(st.toString()); } public void init(int index, int a, int b) { //System.out.println("A = " + a + " B = " + b); low[index] = a; high[index] = b; if (a == b) { st[index] = result[a]; return; } int m = a + b; m /= 2; int left = 2 * index; int right = left + 1; init(left, a, m); init(right, m + 1, b); st[index] = st[left] & st[right]; } public int raq(int a, int b) { int left = Math.min(a, b); int right = Math.max(a, b); return raq(1, left, right); } public int raq(int index, int a, int b) { if (a > high[index] || b < low[index]) { return Integer.MAX_VALUE; } if (a <= low[index] && b >= high[index]) { return st[index]; } int left = 2 * index; int right = left + 1; int leftNum = raq(left, a, b); int rightNum = raq(right, a, b); return leftNum & rightNum; } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; int n, m; int tree[400005]; bool flag; struct q { int l, r, q; } q[100005]; void add(int l, int r, int q, int L, int R, int i) { if (l == L && r == R) { tree[i] = tree[i] | q; return; } int M = (L + R) / 2; if (r <= M) add(l, r, q, L, M, i * 2); else if (l > M) add(l, r, q, M + 1, R, i * 2 + 1); else { add(l, M, q, L, M, i * 2); add(M + 1, r, q, M + 1, R, i * 2 + 1); } } int AND(int l, int r, int L, int R, int i) { if (l == L && r == R) return tree[i]; int M = (L + R) / 2; if (r <= M) return AND(l, r, L, M, i * 2); if (l > M) return AND(l, r, M + 1, R, i * 2 + 1); return AND(l, M, L, M, i * 2) & AND(M + 1, r, M + 1, R, i * 2 + 1); } int read(int f, int l, int r, int i) { if (l == r) return tree[i]; int M = (l + r) / 2; if (f <= M) return tree[i] | read(f, l, M, i * 2); if (f > M) return tree[i] | read(f, M + 1, r, i * 2 + 1); } int main() { int k = 1; while (cin >> n >> m) { memset(tree, 0, sizeof(tree)); flag = 0; for (int i = 0; i < m; i++) { scanf("%d %d %d", &q[i].l, &q[i].r, &q[i].q); q[i].l--; q[i].r--; } for (int i = 0; i < m; i++) add(q[i].l, q[i].r, q[i].q, 0, n - 1, 1); for (int i = 0; i < m; i++) if (AND(q[i].l, q[i].r, 0, n - 1, 1) != q[i].q) flag = 1; if (flag) cout << "NO" << endl; else { cout << "YES" << endl; for (int i = 0; i < n; i++) { if (i) printf(" "); printf("%d", read(i, 0, n - 1, 1)); } printf("\n"); } } return 0; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import java.text.*; public class cf482b { static BufferedReader br; static Scanner sc; static PrintWriter out; public static void initA() { try { br = new BufferedReader(new InputStreamReader(System.in)); sc = new Scanner(System.in); out = new PrintWriter(System.out); } catch (Exception e) { } } static boolean next_permutation(Integer[] p) { for (int a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) { for (int b = p.length - 1;; --b) { if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } } } return false; } public static String getString() { try { return br.readLine(); } catch (Exception e) { } return ""; } public static Integer getInt() { try { return Integer.parseInt(br.readLine()); } catch (Exception e) { } return 0; } public static Integer[] getIntArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Integer temp2[] = new Integer[n]; for (int i = 0; i < n; i++) { temp2[i] = Integer.parseInt(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static Long[] getLongArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); Long temp2[] = new Long[n]; for (int i = 0; i < n; i++) { temp2[i] = Long.parseLong(temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static String[] getStringArr() { try { StringTokenizer temp = new StringTokenizer(br.readLine()); int n = temp.countTokens(); String temp2[] = new String[n]; for (int i = 0; i < n; i++) { temp2[i] = (temp.nextToken()); } return temp2; } catch (Exception e) { } return null; } public static void print(Object a) { out.print(a); } public static void println(Object a) { out.println(a); } public static void print(String s, Object... a) { out.printf(s, a); } public static int nextInt() { return sc.nextInt(); } public static double nextDouble() { return sc.nextDouble(); } public static void main(String[] ar) { initA(); cf482b c = new cf482b(); c.solve(); out.flush(); } int tree[], lazy[]; int m = 0; void update(int node, int cl, int cr, int l, int r, int v) { tree[node] |= lazy[node]; if (cl != cr) { lazy[node * 2] |= lazy[node]; lazy[node * 2 + 1] |= lazy[node]; } lazy[node] = 0; if (cl > r || cr < l) { return; } if (cl >= l && cr <= r) { tree[node] |= v; // print("SETx %d - %d = %d\n", cl, cr, tree[node]); if (cl != cr) { lazy[node * 2] |= v; lazy[node * 2 + 1] |= v; } return; } int mid = (cl + cr) / 2; update(node * 2, cl, mid, l, r, v); update(node * 2 + 1, mid + 1, cr, l, r, v); int a = tree[node * 2], b = tree[node * 2 + 1]; tree[node] = tree[node * 2] & tree[node * 2 + 1]; //print("SET NODE %d = %d - %d dari %d dan %d = %d\n", node, cl, cr, a, b, tree[node]); } int q(int node, int cl, int cr, int l, int r) { //System.out.printf("%d %d %d %d %d\n",node,cl,cr,l,r); tree[node] |= lazy[node]; if (cl != cr) { lazy[node * 2] |= lazy[node]; lazy[node * 2 + 1] |= lazy[node]; } lazy[node] = 0; if (cl > r || cr < l) { return m; } if (cl >= l && cr <= r) { return tree[node]; } int mid = (cl + cr) / 2; int a = q(node * 2, cl, mid, l, r); int b = q(node * 2 + 1, mid + 1, cr, l, r); return a & b; } void solve() { Integer xx[] = getIntArr(); int n = xx[0], q = xx[1]; tree = new int[n * 4 + 1]; lazy = new int[n * 4 + 1]; int lqx[] = new int[q]; int lqy[] = new int[q]; int lqv[] = new int[q]; for (int i = 0; i < q; i++) { xx = getIntArr(); int from = xx[0], to = xx[1], v = xx[2]; m |= v; // print("QUERY %d\n", i + 1); update(1, 1, n, from, to, v); lqx[i] = from; lqy[i] = to; lqv[i] = v; } for (int i = 0; i < q; i++) { int from = lqx[i], to = lqy[i], v = lqv[i]; int rq = q(1, 1, n, from, to); // print("%d - %d = %d\n", from, to, rq); if (rq != v) { println("NO"); return; } } println("YES"); for (int i = 1; i <= n; i++) { int v = q(1, 1, n, i, i); print(v+" "); } println(""); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int N = 1; while (N < n) N <<= 1; int m = sc.nextInt(); int[][] cons = new int[3][m]; SegmentTree st = new SegmentTree(new int[N + 1]); for (int i = 0; i < m; i++) { cons[0][i] = sc.nextInt(); cons[1][i] = sc.nextInt(); cons[2][i] = sc.nextInt(); st.update_range(cons[0][i], cons[1][i], cons[2][i]); } boolean poss = true; for (int i = 0; i < m; i++) { poss &= (st.query(cons[0][i], cons[1][i]) == cons[2][i]); } // System.err.println(Arrays.toString(st.sTree)); // System.err.println(Arrays.toString(st.lazy)); if (!poss) out.println("NO"); else { out.println("YES"); st.fill(1,1,N); for (int i = 1; i <= n ; i++) { out.print((st.sTree[i+st.N-1] | st.lazy[i]) + " "); } } out.flush(); out.close(); } public static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] |= val; while (index > 1) { index >>= 1; sTree[index] = sTree[index << 1] & sTree[index << 1 | 1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] |= val; lazy[node] |= val; } else { int mid = b + e >> 1; propagate(node); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] & sTree[node << 1 | 1]; } } void propagate(int node) { if (node >= N) return; lazy[node << 1] |= lazy[node]; lazy[node << 1 | 1] |= lazy[node]; sTree[node << 1] |= lazy[node]; sTree[node << 1 | 1] |= lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { // System.out.println(node + " " + b+ " " + e + " " + i + " " + j); if (i > e || j < b) return - 1; if (b >= i && e <= j) { // System.err.println(sTree[node]); return sTree[node]; } int mid = b + e >> 1; propagate(node); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); // System.out.println(q1 + " "+ q2); return q1 & q2; } void fill (int node , int b , int e){ if (b==e) return; propagate(node); int mid = (b+e)>>1; fill(node<<1 , b , mid); fill(node<<1|1 , mid+1 , e); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
import static java.lang.Math.*; public class B { private static class T1 { private final T1 L, R; private final int from, to, m; private long X = 0; public void or(long X, int from, int to) { assert(from >= this.from && to <= this.to && from < to); if (from == this.from && to == this.to) this.X |= X; else { if (from < m) L.or(X, from, min(to, m)); if (to > m) R.or(X, max(from, m), to); } } private long get(int i) { assert(from <= i && i < to); long res = X; if (i < m) res |= L.get(i); if (i >= m && m > from) res |= R.get(i); return res; } private T1(int from, int to) { assert(from < to); this.from = from; this.to = to; m = (from + to) / 2; if (m > from) { L = new T1(from, m); R = new T1(m, to); } else L = R = null; } } private static class T2 { private final T2 L, R; private final int from, to, m; private long X = INF; public void and(long X, int at) { assert(at >= from && at < to); this.X &= X; if (at < m) L.and(X, at); if (at >= m && at > from) R.and(X, at); } private long get(int from, int to) { assert(this.from <= from && to <= this.to); long res = INF; if (from == this.from && to == this.to) return X; if (from < m) res &= L.get(from, min(to, m)); if (to > m) res &= R.get(max(from, m), to); return res; } private T2(int from, int to) { assert(from < to); this.from = from; this.to = to; m = (from + to) / 2; if (m > from) { L = new T2(from, m); R = new T2(m, to); } else L = R = null; } } public B () { int N = sc.nextInt(), M = sc.nextInt(); int [][] Q = sc.nextInts(M); T1 U = new T1(0, N); for (int i : rep(M)) { int from = Q[i][0] - 1, to = Q[i][1], q = Q[i][2]; U.or(q, from, to); } long [] res = new long [N]; T2 V = new T2(0, N); for (int i : rep(N)) V.and(res[i] = U.get(i), i); for (int i : rep(M)) { int from = Q[i][0] - 1, to = Q[i][1], q = Q[i][2]; if (V.get(from, to) != q) exit("NO"); } print("YES"); exit(res); } private static final int INF = (1 << 30) - 1; private static int [] rep(int N) { return rep(0, N); } private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } //////////////////////////////////////////////////////////////////////////////////// private final static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static void print (Object o, Object ... A) { IOUtils.print(o, A); } private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { line = null; return readLine(); } public String [] nextStrings() { return split(nextLine()); } public int [] nextInts() { String [] L = nextStrings(); int [] res = new int [L.length]; for (int i = 0; i < L.length; ++i) res[i] = Integer.parseInt(L[i]); return res; } public int [][] nextInts (int N) { int [][] res = new int [N][]; for (int i = 0; i < N; ++i) res[i] = nextInts(); return res; } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim(String delim, Object o, Object ... A) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : A) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static void start() { if (t == 0) t = millis(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>) o) append(b, p, delim); else { if (o instanceof Double) o = new java.text.DecimalFormat("#.############").format(o); b.append(delim).append(o); } } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print(Object o, Object ... A) { pw.println(build(o, A)); } private static void err(Object o, Object ... A) { System.err.println(build(o, A)); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(IOUtils.time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } } public static void main (String[] args) { new B(); IOUtils.exit(); } }
JAVA
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const long long N = 1 << 17; long long bg[40][N]; long long en[40][N]; long long st[2 * N]; long long getAnd(int a, int b) { a += N; b += N; long long ans = (1ll << 40) - 1; for (; a <= b; a /= 2, b /= 2) { if (a & 1) { ans &= st[a++]; } if (~b & 1) { ans &= st[b--]; } } return ans; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); long long n, m; cin >> n >> m; vector<pair<long long, pair<long long, long long> > > v(m); for (long long i = 0; i < m; ++i) { cin >> v[i].first >> v[i].second.first >> v[i].second.second; --v[i].first; --v[i].second.first; for (long long j = 0; j < 40; ++j) { if (v[i].second.second & (1ll << j)) { ++bg[j][v[i].first]; ++en[j][v[i].second.first]; } } } long long cnt[40] = {0}; for (int i = 0; i < n; ++i) { long long val = 0; for (int j = 0; j < 40; ++j) { cnt[j] += bg[j][i]; if (cnt[j] > 0) { val |= 1ll << j; } } st[i + N] = val; for (int j = 0; j < 40; ++j) { cnt[j] -= en[j][i]; } } for (int i = N - 1; i; --i) { st[i] = st[i * 2] & st[i * 2 + 1]; } for (int i = 0; i < m; ++i) { if (getAnd(v[i].first, v[i].second.first) != v[i].second.second) { cout << "NO\n"; return 0; } } cout << "YES\n"; for (int i = 0; i < n; ++i) { cout << st[i + N] << ' '; } cout << '\n'; }
CPP
482_B. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≀ li ≀ ri ≀ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist. Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β€” as "and". Input The first line contains two integers n, m (1 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of elements in the array and the number of limits. Each of the next m lines contains three integers li, ri, qi (1 ≀ li ≀ ri ≀ n, 0 ≀ qi < 230) describing the i-th limit. Output If the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1], a[2], ..., a[n] (0 ≀ a[i] < 230) decribing the interesting array. If there are multiple answers, print any of them. If the interesting array doesn't exist, print "NO" (without the quotes) in the single line. Examples Input 3 1 1 3 3 Output YES 3 3 3 Input 3 2 1 3 3 1 3 2 Output NO
2
8
#include <bits/stdc++.h> using namespace std; const int MAXN = 100010 * 4; const int MAXM = 100010 * 8; const int INF = 1e9 + 7; const double pi = acos(0.0) * 2.0; const double eps = 1e-12; inline int read(int &x) { scanf("%d", &x); return x; } inline long long read(long long &x) { scanf("%I64d", &x); return x; } inline char read(char c) { c = getchar(); return c; } inline char *read(char *&x) { scanf("%s", x); return x; } inline char *readln(char *&x) { gets(x); return x; } inline string read(string &x) { cin >> x; return x; } inline string readln(string &x) { getline(cin, x); return x; } inline float read(float &x) { scanf("%f", &x); return x; } inline double read(double &x) { scanf("%lf", &x); return x; } inline void ToString(char *x, string &y) { y = x; } template <typename T> inline void read(vector<T> &a, int n) { a.clear(); T x; for (int i = 0; i < n; i++) a.push_back(read(x)); } template <typename T> inline void read(T a[], int n) { for (int i = 0; i < n; i++) read(a[i]); } inline int write(int x) { printf("%d", x); return x; } inline int writeln(int x) { printf("%d\n", x); return x; } inline long long write(long long x) { printf("%I64d", x); return x; } inline long long writeln(long long x) { printf("%I64d\n", x); return x; } inline char write(char c) { putchar(c); return c; } inline char writeln(char c) { putchar(c); putchar('\n'); return c; } inline char *write(char *x) { printf("%s", x); return x; } inline char *writeln(char *x) { puts(x); return x; } inline string write(string x) { cout << x; return x; } inline string writeln(string x) { cout << x << '\n'; return x; } inline float write(float x) { printf("%f", x); return x; } inline float writeln(float x) { printf("%f\n", x); return x; } inline double write(double x) { printf("%lf", x); return x; } inline double writeln(double x) { printf("%lf\n", x); return x; } template <typename T> inline void write(vector<T> &a, int n) { for (int i = 0; i < n - 1; i++) { write(a[i]); putchar(' '); } writeln(a[n - 1]); } template <typename T> inline void writeln(vector<T> &a, int n) { for (int i = 0; i < n; i++) writeln(a[i]); } template <typename T> inline void write(T a[], int n) { for (int i = 0; i < n - 1; i++) { write(a[i]); putchar(' '); } writeln(a[n - 1]); } template <typename T> inline void writeln(T a[], int n) { for (int i = 0; i < n; i++) writeln(a[i]); } template <class T> inline T abs1(T a) { return a < 0 ? -a : a; } template <class T> inline T max1(T a, T b) { return a > b ? a : b; } template <class T> inline T max1(T a, T b, T c) { return max1(max1(a, b), c); } template <class T> inline T max1(T a, T b, T c, T d) { return max1(max1(a, b, c), d); } template <class T> inline T max1(T a, T b, T c, T d, T e) { return max1(max1(a, b, c, d), e); } template <class T> inline T min1(T a, T b) { return a < b ? a : b; } template <class T> inline T min1(T a, T b, T c) { return min1(min1(a, b), c); } template <class T> inline T min1(T a, T b, T c, T d) { return min1(min1(a, b, c), d); } template <class T> inline T min1(T a, T b, T c, T d, T e) { return min1(min1(a, b, c, d), e); } inline int jud(double a, double b) { if (abs(a) < eps && abs(b) < eps) return 0; else if (abs1(a - b) / abs1(a) < eps) return 0; if (a < b) return -1; return 1; } template <typename t> inline int jud(t a, t b) { if (a < b) return -1; if (a == b) return 0; return 1; } struct segtree { int l[MAXN]; int r[MAXN]; int lson[MAXN]; int rson[MAXN]; int state[MAXN]; int ans[MAXN / 4]; int root, node; void build(int now, int left, int right) { l[now] = left; r[now] = right; if (left < right) { int mid = (left + right) >> 1; lson[now] = ++node; build(node, left, mid); rson[now] = ++node; build(node, mid + 1, right); } } void buildtree(int left, int right) { memset(state, 0, sizeof(state)); root = 0; node = 0; build(root, left, right); } void modify(int now, int left, int right, int q) { if ((state[now] | q) == state[now]) return; if (l[now] == left && r[now] == right) { state[now] |= q; return; } state[lson[now]] |= state[now]; state[rson[now]] |= state[now]; int mid = (l[now] + r[now]) >> 1; if (left <= mid) { modify(lson[now], left, min(mid, right), q); } if (right > mid) { modify(rson[now], max(left, mid + 1), right, q); } state[now] = (state[lson[now]] & state[rson[now]]); } bool query(int now, int left, int right, int q) { if (state[now] & q) return false; if (l[now] == left && r[now] == right) { return true; } int mid = (l[now] + r[now]) >> 1; bool res = false; state[lson[now]] |= state[now]; state[rson[now]] |= state[now]; if (left <= mid) { res = res || query(lson[now], left, min(mid, right), q); } if (right > mid) { res = res || query(rson[now], max(left, mid + 1), right, q); } return res; } void down(int now) { if (l[now] == r[now]) { ans[l[now]] = state[now]; return; } state[lson[now]] |= state[now]; state[rson[now]] |= state[now]; down(lson[now]); down(rson[now]); } } seg; int N, M; int q[MAXN / 4], l[MAXN / 4], r[MAXN / 4]; int con[33]; int ans[MAXN / 4]; int main() { read(N); read(M); for (int i = 0; i < 31; i++) con[i] = (1 << i); seg.buildtree(1, N); for (int i = 0; i < M; i++) { read(l[i]); read(r[i]); read(q[i]); seg.modify(0, l[i], r[i], q[i]); } memset(ans, 0, sizeof(ans)); for (int i = 0; i < M; i++) { q[i] = ~q[i]; for (int j = 0; j < 31; j++) if (q[i] & con[j]) if (!seg.query(0, l[i], r[i], con[j])) { puts("NO"); return 0; } } seg.down(0); puts("YES"); write(seg.ans + 1, N); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int n, m, ans, x, y, nrIN[100005]; vector<int> v[100005], N, ord[100005]; unordered_set<long long> S; bool viz[100005], viz2[100005]; long long to_ll(int x, int y) { return 1LL * x * 1e6 + y; } void dfs(int nod) { N.push_back(nod); viz[nod] = 1; for (auto it : v[nod]) { if (!viz[it]) dfs(it); } } int comp(int a, int b) { if (S.find(to_ll(b, a)) != S.end()) return 1; return 0; } void _sort(vector<int> &N) { vector<int> ans; for (int i = 0; i < N.size(); i++) if (nrIN[N[i]] == 0) ans.push_back(N[i]); for (int i = 0; i < ans.size(); i++) { for (auto it : ord[ans[i]]) { nrIN[it]--; if (nrIN[it] == 0) ans.push_back(it); } } if (ans.size() != N.size()) return; N = ans; } int main() { cin >> n >> m; for (int i = 1; i <= m; i++) { cin >> x >> y; v[x].push_back(y); v[y].push_back(x); ord[x].push_back(y); nrIN[y]++; S.insert(to_ll(x, y)); } for (int i = 1; i <= n; i++) { if (!viz[i]) { N.clear(); dfs(i); if (N.size() == 1) continue; _sort(N); int ok = 0; for (int j = 0; j < N.size() && !ok; j++) { viz2[N[j]] = 1; for (auto it : ord[N[j]]) { if (viz2[it]) { ok = 1; break; } } } ans += N.size() - 1 + ok; } } cout << ans << '\n'; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 100; const long long int mod = 998244353; const int inf = 1e7 + 100; bool mark[N]; vector<int> v, to, adj[N], g[N]; int ind[N]; void dfs(int u) { v.push_back(u); mark[u] = true; for (auto x : adj[u]) { if (!mark[x]) dfs(x); } } void dfs2(int u) { mark[u] = true; for (auto x : g[u]) { if (!mark[x]) dfs2(x); } to.push_back(u); } inline int solve() { int n = v.size(); for (auto u : v) mark[u] = false; for (auto u : v) { if (!mark[u]) dfs2(u); } for (int i = 0; i < n; i++) { ind[to[i]] = i; } bool fl = true; for (auto u : v) { for (auto x : g[u]) { if (ind[u] < ind[x]) fl = false; } } to.clear(); v.clear(); if (fl) return n - 1; else return n; } int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; g[x].push_back(y); adj[x].push_back(y); adj[y].push_back(x); } int ans = 0; for (int i = 0; i < n; i++) { if (!mark[i]) { dfs(i); ans += solve(); } } cout << ans << endl; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; static const int N = 100000; struct node { int data; node *next; }; node *a[N]; int done[N]; int onst[N]; int gk = 1; int br = 0; int component[N]; int ciklus[N]; int done2[N]; void dfs(int c) { done[c] = 1; onst[c] = 1; node *tmp = a[c]; while (tmp) { if (!done[tmp->data]) dfs(tmp->data); if (done[tmp->data] && onst[tmp->data]) ciklus[component[tmp->data]] = 1; tmp = tmp->next; } onst[c] = 0; } node *b[N]; void connect(int x, int y) { node *tmp; tmp = new node; tmp->data = y; tmp->next = b[x]; b[x] = tmp; } void dfs2(int c) { done2[c] = 1; component[c] = br; node *tmp = b[c]; while (tmp) { if (!done2[tmp->data]) { dfs2(tmp->data); } tmp = tmp->next; } } int main() { int n, m; scanf("%i", &n); scanf("%i", &m); int x, y; for (int i = 0; i < m; i++) { scanf("%i", &x); scanf("%i", &y); x--; y--; node *tmp; tmp = new node; tmp->data = y; tmp->next = a[x]; a[x] = tmp; connect(x, y); connect(y, x); } for (int i = 0; i < n; i++) if (!done2[i]) { dfs2(i); br++; } for (int i = 0; i < n; i++) if (!done[i]) dfs(i); int sum = 0; for (int i = 0; i < br; i++) if (ciklus[i]) sum++; printf("%i\n", n - br + sum); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> template <typename T> void scan(T &x) { x = 0; bool _ = 0; T c = getchar(); _ = c == 45; c = _ ? getchar() : c; while (c < 48 || c > 57) c = getchar(); for (; c < 48 || c > 57; c = getchar()) ; for (; c > 47 && c < 58; c = getchar()) x = (x << 3) + (x << 1) + (c & 15); x = _ ? -x : x; } template <typename T> void printn(T n) { bool _ = 0; _ = n < 0; n = _ ? -n : n; char snum[65]; int i = 0; do { snum[i++] = n % 10 + 48; n /= 10; } while (n); --i; if (_) putchar(45); while (i >= 0) putchar(snum[i--]); } template <typename First, typename... Ints> void scan(First &arg, Ints &...rest) { scan(arg); scan(rest...); } template <typename T> void print(T n) { printn(n); putchar(10); } template <typename First, typename... Ints> void print(First arg, Ints... rest) { printn(arg); putchar(32); print(rest...); } using namespace std; const int MM = 2e5 + 5; int n, m, dfn[MM], low[MM], t, path[MM], ptr, id[MM], sz[MM]; bool ins[MM]; vector<int> adj[MM]; set<int> adj2[MM]; void dfs(int cur) { ins[cur] = 1; path[++ptr] = cur; dfn[cur] = low[cur] = ++t; for (int u : adj[cur]) { if (!dfn[u]) { dfs(u); low[cur] = min(low[cur], low[u]); } else if (ins[u]) low[cur] = min(low[cur], dfn[u]); } if (dfn[cur] == low[cur]) { int u = 0; do { u = path[ptr--]; ins[u] = 0; id[u] = cur; sz[cur]++; } while (u != cur); } } int ans, par[MM], sz2[MM]; int cyc[MM]; int find(int x) { while (x != par[x]) x = par[x], par[x] = par[par[x]]; return x; } int va[MM], vb[MM]; int main() { scan(n, m); for (int i = 1; i <= n; i++) { par[i] = i; sz2[i] = 1; } for (int i = 0, a, b; i < m; i++) { scan(a, b); adj[a].emplace_back(b); va[i] = a, vb[i] = b; a = find(a), b = find(b); if (a != b) { par[a] = b; sz2[a] += sz2[b]; } } for (int i = 1; i <= n; i++) { if (!dfn[i]) dfs(i); } for (int i = 0, a, b; i < m; i++) { a = id[va[i]], b = id[vb[i]]; assert(a and b); if (a != b) { adj2[a].insert(b); } } for (int i = 1; i <= n; i++) { ans += sz2[i] - 1; if (sz[i] > 1) { if (!cyc[find(i)]) { ans++; cyc[find(i)] = 1; } } } print(ans); }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; vector<int> g[N], edge[N], temp; bool done[N], vis[N]; int got[N]; void dfs(int now) { if (done[now]) return; done[now] = 1; temp.emplace_back(now); for (int i = 0; i < g[now].size(); i++) { dfs(g[now][i]); } } int main() { int n, m; scanf("%d %d", &n, &m); while (m--) { int a, b; scanf("%d %d", &a, &b); edge[a].emplace_back(b); g[a].emplace_back(b); g[b].emplace_back(a); } int ans = 0; for (int i = 1; i <= n; i++) { if (done[i]) continue; temp.clear(); dfs(i); for (int j = 0; j < temp.size(); j++) { int cur = temp[j]; for (auto it : edge[cur]) { got[it]++; } } queue<int> q; int edges = 0; for (int j = 0; j < temp.size(); j++) { int cur = temp[j]; edges += edge[cur].size(); if (got[cur] == 0) { q.push(cur); } } while (!q.empty()) { int now = q.front(); q.pop(); if (vis[now]) continue; vis[now] = 1; for (auto it : edge[now]) { got[it]--; if (got[it] == 0) { q.push(it); } } edges -= edge[now].size(); } if (edges) ans += temp.size(); else ans += temp.size() - 1; } cout << ans << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.*; import java.math.*; import java.util.*; public class Main { public static int[] cnt = new int[100009]; public void run() { int n = reader.nextInt(), m = reader.nextInt(); ArrayList<Integer>[] E = new ArrayList[n]; for(int i = 0; i < n; ++i) E[i] = new ArrayList<Integer>(); int[] f = new int[n]; for(int i = 0; i < n; ++i) f[i] = i; for(int i = 0, u, v; i < m; ++i) { u = reader.nextInt() - 1; v = reader.nextInt() - 1; E[u].add(v); if(find(u, f) != find(v, f)) f[find(u, f)] = find(v, f); } ArrayList<Integer>[] son = new ArrayList[n]; for(int i = 0; i < n; ++i) son[i] = new ArrayList<Integer>(); for(int i = 0; i < n; ++i) { son[find(i, f)].add(i); } int ans = 0; for(int i = 0; i < n; ++i) if(find(i, f) == i){ if(check(n, i, son[i], E)) --ans; ans += son[i].size(); } writer.println(ans); writer.close(); } int find(int x, int[] f) { if(x == f[x]) return f[x]; return f[x] = find(f[x], f); } boolean check(int N, int x, ArrayList<Integer> A, ArrayList<Integer>[] E) { int n = A.size(), num = 0; for(int i : A) cnt[i] = 0; LinkedList<Integer> Q = new LinkedList(); for(int i : A) for(int j : E[i]) ++cnt[j]; for(int i : A) if(cnt[i] == 0) { ++num; Q.add(i); } while(!Q.isEmpty()) { int u = Q.getFirst(); Q.removeFirst(); for(int i : E[u]) { --cnt[i]; if(cnt[i] == 0) { ++num; Q.add(i); } } if(num == n) return true; } return num == n; } Main() { //try { reader = new InputReader(System.in); writer = new PrintWriter(System.out); //reader = new InputReader(new FileInputStream("tst.in")); //writer = new PrintWriter(new File("tst.out")); //} catch(FileNotFoundException ex) { //} } public static void main(String[] args) { new Main().run(); } private static void debug(Object...os) { System.err.println(Arrays.deepToString(os)); } private InputReader reader; private PrintWriter writer; } class InputReader { public InputReader(InputStream stream) { this.stream = stream; } public int nextChar() { if (charCount == -1) throw new InputMismatchException(); if (head >= charCount) { head = 0; try { charCount = stream.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (charCount <= 0) return -1; } return buffer[head ++]; } public int nextInt() { int c = nextChar(); while (isSpaceChar(c)) { c = nextChar(); } int sign = 1; if (c == '-') { sign = -1; c = nextChar(); } int result = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } result *= 10; result += c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return sign * result; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private InputStream stream; private int head, charCount; private byte[] buffer = new byte[1024]; }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int mxn = 1e5 + 10; vector<int> adj[mxn]; vector<int> tps[mxn]; vector<int> comp[mxn]; int sz[mxn] = {}; int initsz[mxn] = {}; int vis[mxn] = {}; int comind[mxn]; int mark = 0; stack<int> st; int n; int par[mxn]; int cyc[mxn] = {}; void dfs(int u) { vis[u] = 1; for (int i : adj[u]) if (!vis[i]) dfs(i); st.push(u); } void dfs2(int u, int m) { comp[m].push_back(u); comind[u] = m; sz[m]++; initsz[m]++; vis[u] = 1; for (int i : tps[u]) if (!vis[i]) dfs2(i, m); } void scc() { for (int i = 1; i <= n; i++) if (!vis[i]) dfs(i); for (int i = 0; i <= n; i++) vis[i] = 0; while (!st.empty()) { int u = st.top(); st.pop(); if (!vis[u]) { dfs2(u, mark++); } } } int findrep(int u) { if (par[u] == u) return u; return par[u] = findrep(par[u]); } void unionset(int u, int v) { int _u = findrep(u); int _v = findrep(v); par[_u] = _v; sz[_v] += sz[_u]; cyc[_v] |= cyc[_u]; } int main() { int m; cin >> n >> m; for (int i = 0; i <= n; i++) par[i] = i; for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); tps[v].push_back(u); } scc(); int rs = 0; for (int i = 0; i < mark; i++) if (sz[i] > 1) cyc[i] = 1; for (int i = 1; i <= n; i++) { for (int u : adj[i]) { if (comind[i] != comind[u] && findrep(comind[i]) != findrep(comind[u])) { unionset(comind[u], comind[i]); if (initsz[comind[u]] > 1) cyc[findrep(comind[u])] = 1; } } } for (int i = 0; i < mark; i++) if (par[i] == i) rs += sz[i] - (1 - cyc[i]); cout << rs << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> Colors, temp; vector<vector<int>> G, C, GForBfs; long long ans; bool dfs(int x); void bfs(int x); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> m; G.assign(n, vector<int>(0, 0)); GForBfs.assign(n, vector<int>(0, 0)); for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; x--, y--; G[x].push_back(y); GForBfs[x].push_back(y); GForBfs[y].push_back(x); } Colors.assign(n, 0); for (int i = 0; i < n; i++) { if (!Colors[i]) { C.push_back(vector<int>(0, 0)); bfs(i); } } temp.assign(n, 0); for (int i = 0; i < C.size(); i++) { for (int j = 0; j < C[i].size(); j++) { if (dfs(C[i][j])) { ans++; break; } } } for (int i = 0; i < C.size(); i++) { ans += max(0, int(C[i].size()) - 1); } cout << ans; } bool dfs(int x) { for (int y : G[x]) { if (!temp[y]) { temp[y] = 1; if (dfs(y)) { return 1; } } else if (temp[y] == 1) { return 1; } } temp[x] = 2; return 0; } void bfs(int x) { deque<int> O = {x}; Colors[x] = C.size(); C[C.size() - 1].push_back(x); while (!O.empty()) { x = O.front(); O.pop_front(); for (int y : GForBfs[x]) { if (!Colors[y]) { Colors[y] = C.size(); C[C.size() - 1].push_back(y); O.push_back(y); } } } }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; bool flag[100005]; int n, m, x, y; vector<int> a[100005], b[100005]; int d[100005]; int sum, num, ans, dq; queue<int> q; int dfs(int x) { int sum = 1; flag[x] = true; if (d[x] == 0) q.push(x); for (int i = 0; i < a[x].size(); ++i) { int y = a[x][i]; if (flag[y]) continue; sum += dfs(y); } return sum; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= m; ++i) { scanf("%d%d", &x, &y); a[x].push_back(y); a[y].push_back(x); b[x].push_back(y); ++d[y]; } memset(flag, false, sizeof(flag)); for (int i = 1; i <= n; ++i) { if (flag[i]) continue; sum = dfs(i); num = 0; while (!q.empty()) { int y = q.front(); q.pop(); ++num; for (int j = 0; j < b[y].size(); ++j) { dq = b[y][j]; --d[dq]; if (d[dq] == 0) q.push(dq); } } if (num == sum) ans += sum - 1; else ans += sum; } printf("%d\n", ans); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; struct DisjointSet { vector<int> label; DisjointSet(int n) { label.assign(n, -1); } int get(int u) { return label[u] < 0 ? u : label[u] = get(label[u]); } void join(int u, int v) { u = get(u); v = get(v); if (u == v) return; if (label[u] < label[v]) swap(u, v); label[v] += label[u]; label[u] = v; } }; const int N = (int)1e5; vector<int> vertices[N]; vector<int> graph[N]; bool visited[N]; int topo[N]; int counter; void dfs(int u) { if (visited[u]) return; visited[u] = true; for (int v : graph[u]) dfs(v); topo[u] = --counter; } int main() { ios::sync_with_stdio(false); int n; cin >> n; int m; cin >> m; DisjointSet ds(n); for (int i = 0; i < m; ++i) { int u; cin >> u; --u; int v; cin >> v; --v; graph[u].push_back(v); ds.join(u, v); } for (int u = 0; u < n; ++u) { vertices[ds.get(u)].push_back(u); dfs(u); } counter = n; int result = 0; for (int i = 0; i < n; ++i) if (!vertices[i].empty()) { bool isDAG = true; for (int u : vertices[i]) { for (int v : graph[u]) { isDAG &= topo[u] < topo[v]; } } result += vertices[i].size() - (isDAG ? 1 : 0); } cout << result << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int Maxn = 200000; int n, m, mark[Maxn]; bool res[Maxn], flag[Maxn], u[Maxn]; vector<int> nei[Maxn], rnei[Maxn], adj[Maxn]; vector<int> l; void dfs(int u, int c) { mark[u] = c; for (auto v : adj[u]) if (!mark[v]) dfs(v, c); } void Dfs(int u) { flag[u] = true; for (auto v : nei[u]) if (!flag[v]) Dfs(v); l.push_back(u); } int count(int u) { int ret = 1; res[u] = true; for (auto v : rnei[u]) if (!res[v]) ret += count(v); return ret; } int main() { ios::sync_with_stdio(0); cin.tie(); cin >> n >> m; for (int i = 0; i < m; i++) { int a, b; cin >> a >> b; a--; b--; nei[a].push_back(b); rnei[b].push_back(a); adj[a].push_back(b); adj[b].push_back(a); } int cmp = 0, ans = 0; for (int i = 0; i < n; i++) if (!mark[i]) cmp++, dfs(i, cmp); for (int i = 0; i < n; i++) if (!flag[i]) Dfs(i); while (((int)l.size())) { int cou = 0; if (!res[l.back()]) cou = count(l.back()); if (cou > 1 && !u[mark[l.back()]]) { u[mark[l.back()]] = true; ans++; } l.pop_back(); } cout << ans + n - cmp << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.util.*; import java.io.*; public class MrKitayutasTechnology { public static void main(String[] args) throws Exception { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int m = in.nextInt(); ArrayList<Integer>[] adj = new ArrayList[n]; for(int x = 0; x < adj.length; x++) { adj[x] = new ArrayList<Integer>(); } int[] degree = new int[n]; DisjointSet ds = new DisjointSet(n); int components = n; for(int y = 0; y < m; y++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; adj[a].add(b); degree[b]++; if(ds.union(a, b)) { components--; } } ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); for(int z = 0; z < degree.length; z++) { if(degree[z] == 0) { queue.add(z); } } boolean[] visited = new boolean[n]; while(queue.size() > 0) { int node = queue.remove(); visited[node] = true; for(int next : adj[node]) { degree[next]--; if(degree[next] == 0) { queue.add(next); } } } HashSet<Integer> hs = new HashSet<Integer>(); for(int a = 0; a < visited.length; a++) { if(!visited[a]) { hs.add(ds.find(a)); } } System.out.println(n - components + hs.size()); } static class DisjointSet { int[] parent; int[] rank; public DisjointSet(int n) { parent = new int[n]; rank = new int[n]; for(int i = 0; i < parent.length; i++) { parent[i] = i; } } public int find(int x) { if(parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } public boolean union(int x, int y) { int a = find(x); int b = find(y); if(a == b) { return false; } else { if(rank[a] < rank[b]) { parent[a] = b; } else if(rank[a] > rank[b]) { parent[b] = a; } else { parent[b] = a; rank[a]++; } return true; } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream input) { br = new BufferedReader(new InputStreamReader(input)); st = new StringTokenizer(""); } public String next() throws IOException { if(st.hasMoreTokens()) { return st.nextToken(); } else { st = new StringTokenizer(br.readLine()); return next(); } } public int nextInt() throws IOException { return Integer.parseInt(next()); } } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.*; import java.util.*; public class B { FastScanner in; PrintWriter out; List<Integer>[] graph, revGraph; List<Integer> order; int[] comp; void dfs(int u) { comp[u] = 0; for (int v : graph[u]) { if (comp[v] == -1) { dfs(v); } } order.add(u); } int dfsRev(int u, int c) { comp[u] = c; int ret = 1; for (int v : revGraph[u]) { if (comp[v] == -1) { ret += dfsRev(v, c); } } return ret; } void solve() { int n = in.nextInt(), m = in.nextInt(); graph = new List[n]; revGraph = new List[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); revGraph[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int from = in.nextInt() - 1, to = in.nextInt() - 1; graph[from].add(to); revGraph[to].add(from); } order = new ArrayList<>(); comp = new int[n]; Arrays.fill(comp, -1); for (int i = 0; i < n; i++) { if (comp[i] == -1) { dfs(i); } } Arrays.fill(comp, -1); int comps = 0; int[] sizes = new int[n]; Collections.reverse(order); for (int i : order) { if (comp[i] == -1) { sizes[comps] = dfsRev(i, comps); comps++; } } int ans = 0; DSU dsu = new DSU(comps); for (int i = 0; i < n; i++) { for (int j : graph[i]) { dsu.unite(comp[i], comp[j]); } } for (int i = 0; i < comps; i++) { int root = dsu.get(i); dsu.size[root] += sizes[i]; if (sizes[i] > 1 && !dsu.add[root]) { dsu.add[root] = true; } } for (int i = 0; i < comps; i++) { if (dsu.get(i) == i) { ans += dsu.size[i] - 1; if (dsu.add[i]) { ans++; } } } out.println(ans); } class DSU { int[] p; boolean[] add; int[] size; public DSU(int n) { p = new int[n]; size = new int[n]; add = new boolean[n]; for (int i = 0; i < n; i++) { p[i] = i; } } int get(int u) { if (p[u] == u) { return u; } return p[u] = get(p[u]); } boolean unite(int u, int v) { u = get(u); v = get(v); if (u != v) { p[v] = u; } return u != v; } } void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new B().run(); } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int MAXN = 100100; vector<int> g[MAXN]; vector<int> gd[MAXN]; bool mk[MAXN]; int cnt; vector<int> tmp; void dfs(int u) { if (mk[u]) { return; } mk[u] = true; tmp.push_back(u); for (int i = 0; i < g[u].size(); i++) { int v = g[u][i]; dfs(v); } } bool mk1[MAXN], mk2[MAXN]; bool cycle(int u, int p) { if (mk2[u]) { return true; } if (mk1[u]) { return false; } mk1[u] = mk2[u] = true; for (int i = 0; i < gd[u].size(); i++) { int v = gd[u][i]; if (cycle(v, u)) { return true; } } mk2[u] = false; return false; } int solve(int u) { cnt = 0; tmp.clear(); dfs(u); int sol = tmp.size() - 1; for (int i = 0; i < tmp.size(); i++) { int v = tmp[i]; if (cycle(v, -1)) { sol++; break; } } return sol; } int main() { ios::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); gd[u].push_back(v); } int sol = 0; for (int u = 1; u <= n; u++) { if (!mk[u]) { sol += solve(u); } } cout << sol << '\n'; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 50; const int mod = 1e9 + 7; const int inf = (1 << 30); vector<int> v[maxn][5], tpl; int ted[maxn], com[maxn], tmp = 1; bool visited[maxn]; bool dfs(int u, int d) { visited[u] = 1; bool rz = (ted[com[u]] == 1); if (d == 1) { com[u] = tmp; ted[tmp]++; } for (auto w : v[u][d]) { if (!visited[w]) { rz &= dfs(w, d); } } if (d == 0) tpl.push_back(u); return rz; } bool dfs1(int u) { visited[u] = 1; bool rz = (ted[com[u]] == 1); for (auto w : v[u][0]) if (!visited[w]) rz &= dfs1(w); for (auto w : v[u][1]) if (!visited[w]) rz &= dfs1(w); return rz; } int main() { ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; v[a][0].push_back(b); v[b][1].push_back(a); } for (int i = 1; i <= n; i++) if (!visited[i]) dfs(i, 0); memset(visited, 0, sizeof visited); for (int i = n - 1; i >= 0; i--) { int u = tpl[i]; if (!visited[u]) { dfs(u, 1); tmp++; } } memset(visited, 0, sizeof visited); long long ans = n; for (int i = 1; i <= n; i++) { if (!visited[i]) { bool k = dfs1(i); ans -= k; } } cout << ans << endl; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int n, m, ans, l; int mark[MAXN], comp[MAXN], scc[MAXN], cyc[MAXN]; vector<int> edge[MAXN], adj[MAXN], radj[MAXN]; deque<int> dq; void dfs(int source) { mark[source]++; ans++, comp[source] = l; for (auto &u : edge[source]) if (!mark[u]) dfs(u); } void dfs1(int source) { mark[source]++; for (auto &u : adj[source]) if (!mark[u]) dfs1(u); dq.push_back(source); } void rev(int source) { mark[source]++; scc[l]++; for (auto &u : radj[source]) if (mark[u] == 1) rev(u); } int main() { cin >> n >> m; while (m--) { int x, y; cin >> x >> y; edge[x].push_back(y), edge[y].push_back(x); adj[x].push_back(y), radj[y].push_back(x); } for (int i = 1; i <= n; i++) if (!mark[i]) ++l, dfs(i), ans--; fill(mark, mark + MAXN, 0); l = 0; for (int i = 1; i <= n; i++) if (!mark[i]) dfs1(i); while (dq.size()) { int x = dq.back(); dq.pop_back(); if (mark[x] < 2 && !cyc[comp[x]]) { ++l, rev(x); if (scc[l] > 1) cyc[comp[x]] = true, ans++; } } cout << ans; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.util.*; import java.io.*; public class _0505_D_MrKitayutasTechnology { static ArrayList<Integer> dgraph[]; public static void main(String[] args) throws IOException { int N = readInt(), M = readInt(); dgraph = new ArrayList[N+1]; ArrayList<Integer> graph[] = new ArrayList[N+1]; for(int i= 1; i<=N; i++) { graph[i] = new ArrayList<>(); dgraph[i] = new ArrayList<>(); } for(int i = 1; i<=M; i++) { int a = readInt(), b = readInt(); graph[a].add(b); graph[b].add(a); dgraph[a].add(b); } vis = new boolean[N+1]; instk = new boolean[N+1]; int sz[] = new int[N+1]; int clr[] = new int[N+1]; int cnt = 0; for(int i =1; i<=N; i++) if(!vis[i]) { cnt++; LinkedList<Integer> ll = new LinkedList<>(); ll.add(i); while(!ll.isEmpty()) { int n = ll.pop(); vis[n] = true; clr[n] = cnt; sz[cnt]++; for(int e : graph[n]) if(!vis[e]) { ll.add(e); vis[e] = true; } } } vis = new boolean[N+1]; boolean cycle[] = new boolean[cnt+1]; for(int i = 1; i<=N; i++) { if(cycle[clr[i]]) continue; if(!vis[i]) cycle[clr[i]] = cycle(i); } int tot = 0; for(int i = 1; i<=cnt; i++) { tot += sz[i]-1; if(cycle[i])tot++; } println(tot); exit(); } static boolean vis[]; static boolean instk[]; static boolean cycle(int n) { vis[n] = instk[n] = true; for(int e : dgraph[n]) { if(instk[e]) return true; if(!vis[e] && cycle(e)) return true; } instk[n] = false; return false; } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static 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 static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class KitayutaTechnology { int[] in; int[] low; int[] group; boolean[] groupHasCycle; int[] dfsNum; ArrayList<Integer>[] adj; ArrayList<Integer>[] comingIn; ArrayDeque<Integer> stack; int time; public static void main(String[] args) throws IOException { new KitayutaTechnology().solve(); } private void solve() throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer tokenizer = new StringTokenizer(f.readLine()); int n = Integer.parseInt(tokenizer.nextToken()); int m = Integer.parseInt(tokenizer.nextToken()); adj = new ArrayList[n]; comingIn = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); comingIn[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { tokenizer = new StringTokenizer(f.readLine()); int a = Integer.parseInt(tokenizer.nextToken()) - 1; int b = Integer.parseInt(tokenizer.nextToken()) - 1; adj[a].add(b); comingIn[b].add(a); } time = 0; in = new int[n]; low = new int[n]; group = new int[n]; groupHasCycle = new boolean[n]; Arrays.fill(group, -1); int groupNum = 0; for (int i = 0; i < n; i++) { if (group[i] == -1) { makeGroups(i, groupNum); groupNum++; } } Arrays.fill(in, 0); stack = new ArrayDeque<Integer>(); for (int i = 0; i < n; i++) { if (in[i] == 0) { dfs(i); } } int res = 0; int[] nodesInGroup = new int[n]; for (int i = 0; i < n; i++) { nodesInGroup[group[i]]++; } for (int i = 0; i < n; i++) { if (nodesInGroup[i] > 1) res += nodesInGroup[i] - 1; } for (boolean cycle : groupHasCycle) if (cycle) res++; out.println(res); out.close(); } private void makeGroups(int node, int groupNum) { group[node] = groupNum; for (int adjacent : adj[node]) { if (group[adjacent] == -1) makeGroups(adjacent, groupNum); } for (int adjacent : comingIn[node]) { if (group[adjacent] == -1) makeGroups(adjacent, groupNum); } } private void dfs(int node) { stack.addLast(node); in[node] = time; low[node] = time; time++; for (int adjacent : adj[node]) { if (in[adjacent] == 0) dfs(adjacent); if (in[adjacent] != -1) low[node] = Math.min(low[node], low[adjacent]); } if (low[node] == in[node]) { while (stack.getLast() != node) { groupHasCycle[group[node]] = true; in[stack.removeLast()] = -1; } in[stack.removeLast()] = -1; } } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.io.*; import java.math.*; import java.util.*; public class Main { public static class pair implements Comparable<pair> { int a; int b; public pair(int pa, int pb) { a = pa; b= pb; } @Override public int compareTo(pair o) { if(this.a < o.a) return -1; if(this.a > o.a) return 1; return Integer.compare(o.b, this.b); } } //int n = Integer.parseInt(in.readLine()); //int n = Integer.parseInt(spl[0]); //String[] spl = in.readLine().split(" "); public static boolean dag; public static int v[]; public static Stack<Integer> sta; public static ArrayList[] uadj; public static void main (String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] r = in.readLine().split(" "); int n = Integer.parseInt(r[0]); int m = Integer.parseInt(r[1]); ArrayList[] adj = new ArrayList[n]; uadj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); uadj[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { r = in.readLine().split(" "); int a = Integer.parseInt(r[0])-1; int b = Integer.parseInt(r[1])-1; adj[a].add(b); adj[b].add(a); uadj[a].add(b); } boolean[] vis = new boolean[n]; v = new int[n]; int ans = 0; for (int vert = 0; vert < n; vert++) { if(!vis[vert]) { Stack<Integer> st = new Stack<Integer>(); ArrayList<Integer> nums = new ArrayList<Integer>(); st.push(vert); while(!st.isEmpty()) { int cur = st.pop(); if(!vis[cur]) { vis[cur]=true; nums.add(cur); for (Object veci: adj[cur]) { if(!vis[(Integer) veci]) st.push((Integer) veci); } } } int cnt = nums.size(); for(Integer i: nums) v[i]=0; //white dag=true; sta = new Stack<Integer>(); for(Integer i: nums) if(v[i]==0) DFS(i); if(!dag) ans+=cnt; else ans+=cnt-1; //System.out.println(vert + " " + cnt+ " "+ans); } } System.out.println(ans); } public static void DFS(int a) { if(v[a]==1) { dag = false; //System.out.println(a); } if(v[a]>0) return; v[a] = 1; // gray for(Object i: uadj[a]) DFS((Integer) i); v[a] = 2; // black sta.push(a); } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 5; const int maxm = 1e5 + 5; bool vst[maxn], p[maxn]; int n, m, cnt, scc, timer, ans, tot; int tail[maxn], d[maxn], l[maxn], f[maxn], id[maxn], size[maxn]; struct edge { int u, v, next; } a[maxm]; stack<int> st; int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); } void insert(int u, int v) { a[++cnt] = (edge){u, v, tail[u]}; tail[u] = cnt; } void read() { int u, v; scanf("%d%d", &n, &m); for (int i = 1; i <= m; i++) { scanf("%d%d", &u, &v); insert(u, v); } } void tarjan(int u) { d[u] = l[u] = ++timer; vst[u] = 1; st.push(u); for (int i = tail[u]; i; i = a[i].next) if (!d[a[i].v]) tarjan(a[i].v), l[u] = ((l[u]) < (l[a[i].v]) ? (l[u]) : (l[a[i].v])); else if (vst[a[i].v]) l[u] = ((l[u]) < (d[a[i].v]) ? (l[u]) : (d[a[i].v])); if (d[u] == l[u]) { int v; scc++; while (true) { v = st.top(); st.pop(); vst[v] = 0; size[scc]++; id[v] = scc; if (v == u) break; } if (size[scc] > 1) p[scc] = 1; } } void Union(int x, int y) { if (find(x) == find(y)) return; size[f[y]] += size[f[x]]; size[f[x]] = 0; p[f[y]] |= p[f[x]]; f[f[x]] = f[y]; } void work() { for (int i = 1; i <= n; i++) if (!d[i]) tarjan(i); for (int i = 1; i <= scc; i++) f[i] = i; for (int i = 1; i <= m; i++) if (id[a[i].u] != id[a[i].v]) Union(id[a[i].u], id[a[i].v]); for (int i = 1; i <= scc; i++) if (size[i]) ans += size[i] - (!p[i]); printf("%d", ans); } int main() { read(); work(); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
import java.util.*; import java.io.*; public class Main{ static int n,m; static boolean isCycle=false; public static void main(String args[]) { InputReader in = new InputReader(System.in); ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> rlist = new ArrayList<ArrayList<Integer>>(); n=in.nextInt();m=in.nextInt(); for(int i=0;i<=n;i++) { list.add(i,new ArrayList<Integer>()); rlist.add(i,new ArrayList<Integer>()); } for(int i=0;i<m;i++) { int a=in.nextInt(),b=in.nextInt(); list.get(a).add(b); rlist.get(b).add(a); } int scc[]=new int[n+1]; Stack<Integer> stack =new Stack<Integer>(); int cc[]=new int[n+1],count[]=new int[n+2],num=1,comp=1; for(int i=1;i<=n;i++) { if(cc[i]==0) { dfs1(i,list,cc,comp,stack); comp++; } } while(!stack.isEmpty()) { int i=stack.pop(); if(scc[i]==0) { count[num]=dfs2(i,rlist,num,scc); num++; } } ArrayList<ArrayList<Integer>> sccList=new ArrayList<ArrayList<Integer>>(); for(int i=0;i<=num;i++) sccList.add(i,new ArrayList<Integer>()); for(int i=1;i<=n;i++) { Iterator<Integer> it=list.get(i).iterator(); while(it.hasNext()) { int e=it.next(); sccList.get(scc[i]).add(scc[e]); sccList.get(scc[e]).add(scc[i]); } } int ans=0; boolean visited[]=new boolean[num+1]; for(int i=1;i<num;i++) { if(!visited[i]) { ans +=dfs3(i,sccList,visited,count); ans += isCycle?0:-1; } isCycle=false; } System.out.println(ans); } public static void dfs1(int v,ArrayList<ArrayList<Integer>> list,int [] cc,int comp,Stack<Integer> stack) { cc[v]=comp; Iterator<Integer> it=list.get(v).iterator(); while(it.hasNext()) { int e=it.next(); if(cc[e]==0) dfs1(e,list,cc,comp,stack); } stack.add(v); } public static int dfs2(int v,ArrayList<ArrayList<Integer>> rlist,int current,int scc[]) { scc[v]=current; int cn=1; Iterator<Integer> it=rlist.get(v).iterator(); while(it.hasNext()) { int e=it.next(); if(scc[e]==0) cn+=dfs2(e,rlist,current,scc); } return cn; } public static int dfs3(int v,ArrayList<ArrayList<Integer>> list,boolean [] visited,int count[]) { int cn=count[v]; if(count[v]>1) isCycle=true; visited[v]=true; Iterator<Integer> it=list.get(v).iterator(); while(it.hasNext()) { int e=it.next(); if(!visited[e]) { cn+=dfs3(e,list,visited,count); } } return cn; } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
JAVA
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; vector<int> adj[100005], radj[100005]; vector<int> con[100005]; int chk[100005], cnt, vis[100005]; int val[100005], size[100005]; int T; int N, M, g[100005]; int ans; void DFS(int u) { chk[u] = 1; int i, v; for (i = 0; i < adj[u].size(); i++) { v = adj[u][i]; if (!chk[v]) DFS(v); } g[++cnt] = u; } void rDFS(int u) { chk[u] = 1, vis[u] = T; int i, v; for (i = 0; i < radj[u].size(); i++) { v = radj[u][i]; if (!chk[v]) rDFS(v); } cnt++; size[T]++; } int calc(int u) { int ret = 0, i, v; vis[u] = true; val[u] = size[u]; for (i = 0; i < con[u].size(); i++) { v = con[u][i]; if (!vis[v]) { ret += calc(v); val[u] += val[v]; } } return ret + 1; } int main() { int i, j, u, v; scanf("%d%d", &N, &M); for (i = 0; i < M; i++) { scanf("%d%d", &u, &v); adj[u].push_back(v); radj[v].push_back(u); } for (int i = 1; i <= N; i++) if (!chk[i]) DFS(i); T = 0; memset(chk, 0, sizeof chk); for (int i = N; i > 0; i--) if (!chk[g[i]]) { T++; rDFS(g[i]); } for (i = 1; i <= N; i++) { u = vis[i]; for (j = 0; j < adj[i].size(); j++) { v = vis[adj[i][j]]; if (v != u) { con[u].push_back(v); con[v].push_back(u); } } } memset(vis, 0, sizeof vis); for (i = 1; i <= T; i++) if (!vis[i]) { int m = calc(i); if (m == val[i]) ans += m - 1; else ans += val[i]; } printf("%d\n", ans); return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; class SCC { private: int n, comp_sz; vector<vector<int> > g, gt; vector<int> seq, vis; void dfs(int u, const vector<vector<int> > &adj) { for (int v : adj[u]) { if (vis[v] == -1) { vis[v] = comp_sz; dfs(v, adj); } } seq.push_back(u); } public: SCC(int _n) { n = _n; g.assign(n, vector<int>()); gt.assign(n, vector<int>()); } void add_edge(int u, int v) { g[u].push_back(v); gt[v].push_back(u); } pair<int, vector<int> > find_SCC() { vis.assign(n, -1); comp_sz = 0; for (int i = 0; i < n; i++) { if (vis[i] == -1) { vis[i] = comp_sz; dfs(i, g); } } vis.assign(n, -1); comp_sz = 0; for (int i = n - 1; i >= 0; i--) { int u = seq[i]; if (vis[u] == -1) { vis[u] = comp_sz; dfs(u, gt); comp_sz++; } } return {comp_sz, vis}; } vector<vector<int> > get_dag() { map<pair<int, int>, int> mmap; vector<vector<int> > dag(comp_sz, vector<int>()); for (int u = 0; u < n; u++) { for (int v : g[u]) { if (vis[u] == vis[v]) continue; if (!mmap.count(pair<int, int>(vis[u], vis[v]))) { dag[vis[u]].push_back(vis[v]); dag[vis[v]].push_back(vis[u]); mmap[pair<int, int>(vis[u], vis[v])] = 1; } } } return dag; } }; vector<int> vis, comp_sz; bool large = false; int dfs(const vector<vector<int> > &dag, int u) { int sz = 0; if (comp_sz[u] == 1) sz = 1; else if (large == false) { large = true; sz = 1; } for (int v : dag[u]) { if (!vis[v]) { vis[v] = 1; sz += dfs(dag, v); } } return sz; } int main() { int n, m; cin >> n >> m; SCC scc(n); for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; u--; v--; scc.add_edge(u, v); } int comps; vector<int> cmp; tie(comps, cmp) = scc.find_SCC(); comp_sz.assign(comps, 0); for (int i = 0; i < n; i++) { comp_sz[cmp[i]]++; } int res = 0; for (int i = 0; i < comps; i++) { res += ((comp_sz[i] > 1) ? comp_sz[i] : 0); } vector<vector<int> > dag = scc.get_dag(); vis.assign(comps, 0); for (int i = 0; i < comps; i++) { if (!vis[i]) { large = false; vis[i] = 1; int sz = dfs(dag, i); res += sz - 1; } } cout << res << endl; return 0; }
CPP
506_B. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly. Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai, bi) (1 ≀ i ≀ m) is important. He is planning to construct teleportation pipes so that for each important pair (ai, bi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities. Input The first line contains two space-separated integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively. The following m lines describe the important pairs. The i-th of them (1 ≀ i ≀ m) contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai β‰  bi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai, bi) are distinct. Output Print the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose. Examples Input 4 5 1 2 1 3 1 4 2 3 2 4 Output 3 Input 4 6 1 2 1 4 2 3 2 4 3 2 3 4 Output 4 Note For the first sample, one of the optimal ways to construct pipes is shown in the image below: <image> For the second sample, one of the optimal ways is shown below: <image>
2
8
#include <bits/stdc++.h> using namespace std; const int N = 100000; int n, m, t; vector<int> adj[N], radj[N], component; vector<pair<int, int> > finishing; bool undir_visit[N], visit[N], strongly_connected; void undir_dfs(int u) { undir_visit[u] = true; component.push_back(u); for (const int &v : adj[u]) { if (!undir_visit[v]) { undir_dfs(v); } } for (const int &v : radj[u]) { if (!undir_visit[v]) { undir_dfs(v); } } } void dfs(int u) { visit[u] = true; for (const int &v : adj[u]) { if (!visit[v]) { dfs(v); } } finishing.push_back({t++, u}); } void rdfs(int u) { visit[u] = true; for (const int &v : radj[u]) { if (!visit[v]) { strongly_connected = true; rdfs(v); } } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; u--, v--; adj[u].push_back(v); radj[v].push_back(u); } int sz = 0; for (int i = 0; i < n; ++i) { if (!undir_visit[i]) { component.clear(); strongly_connected = false; undir_dfs(i); finishing.clear(); for (int j = 0; j < component.size(); ++j) { if (!visit[component[j]]) { dfs(component[j]); } } sort(finishing.begin(), finishing.end()); reverse(finishing.begin(), finishing.end()); memset(visit, false, sizeof(visit)); for (const pair<int, int> &p : finishing) { if (!visit[p.second]) { rdfs(p.second); } } if (strongly_connected) { if (component.size() > 1) { sz += component.size(); } } else { sz += component.size() - 1; } } } cout << sz << "\n"; }
CPP